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 
getGoogleStyle()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 
format(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle (),StatusCheck CheckComplete=SC_ExpectComplete)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 
getStyleWithColumns(FormatStyle Style,unsigned ColumnLimit)55   FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) {
56     Style.ColumnLimit = ColumnLimit;
57     return Style;
58   }
59 
getLLVMStyleWithColumns(unsigned ColumnLimit)60   FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
61     return getStyleWithColumns(getLLVMStyle(), ColumnLimit);
62   }
63 
getGoogleStyleWithColumns(unsigned ColumnLimit)64   FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
65     return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
66   }
67 
_verifyFormat(const char * File,int Line,llvm::StringRef Expected,llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())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 
_verifyFormat(const char * File,int Line,llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())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 
_verifyIncompleteFormat(const char * File,int Line,llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())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 
_verifyIndependentOfContext(const char * File,int Line,llvm::StringRef Text,const FormatStyle & Style=getLLVMStyle ())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.
verifyNoCrash(llvm::StringRef Code,const FormatStyle & Style=getLLVMStyle ())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 
TEST_F(FormatTest,MessUp)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 
TEST_F(FormatTest,DefaultLLVMStyleIsCpp)128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
129   EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
130 }
131 
TEST_F(FormatTest,LLVMStyleOverride)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 
TEST_F(FormatTest,DoesNotChangeCorrectlyFormattedCode)141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
142   EXPECT_EQ(";", format(";"));
143 }
144 
TEST_F(FormatTest,FormatsGlobalStatementsAt0)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 
TEST_F(FormatTest,FormatsUnwrappedLinesAtFirstFormat)152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
153   EXPECT_EQ("int i;", format("int\ni;"));
154 }
155 
TEST_F(FormatTest,FormatsNestedBlockStatements)156 TEST_F(FormatTest, FormatsNestedBlockStatements) {
157   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
158 }
159 
TEST_F(FormatTest,FormatsNestedCall)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 
TEST_F(FormatTest,NestedNameSpecifiers)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 
TEST_F(FormatTest,OnlyGeneratesNecessaryReplacements)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 
TEST_F(FormatTest,RemovesEmptyLines)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 
TEST_F(FormatTest,RecognizesBinaryOperatorKeywords)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 
TEST_F(FormatTest,RecognizesUnaryOperatorKeywords)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 
TEST_F(FormatTest,FormatIfWithoutCompoundStatement)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 
TEST_F(FormatTest,FormatIfWithoutCompoundStatementButElseWith)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 
TEST_F(FormatTest,FormatLoopsWithoutCompoundStatement)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 
TEST_F(FormatTest,FormatShortBracedStatements)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 
TEST_F(FormatTest,UnderstandsMacros)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 
TEST_F(FormatTest,ShortBlocksInMacrosDontMergeWithCodeAfterMacro)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 
TEST_F(FormatTest,ParseIfElse)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 
TEST_F(FormatTest,ElseIf)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 
TEST_F(FormatTest,SeparatePointerReferenceAlignment)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 
TEST_F(FormatTest,FormatsForLoop)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 
TEST_F(FormatTest,RangeBasedForLoops)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 
TEST_F(FormatTest,ForEachLoops)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 
TEST_F(FormatTest,FormatsWhileLoop)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 
TEST_F(FormatTest,FormatsDoWhile)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 
TEST_F(FormatTest,FormatsSwitchStatement)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 
TEST_F(FormatTest,CaseRanges)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 
TEST_F(FormatTest,ShortEnums)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 
TEST_F(FormatTest,ShortCaseLabels)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 
TEST_F(FormatTest,FormatsLabels)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 
TEST_F(FormatTest,MultiLineControlStatements)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 
TEST_F(FormatTest,BeforeWhile)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 
TEST_F(FormatTest,DoesNotBreakSemiAfterClassDecl)3254 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
3255   verifyFormat("class A {};");
3256 }
3257 
TEST_F(FormatTest,UnderstandsAccessSpecifiers)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 
TEST_F(FormatTest,SeparatesLogicalBlocks)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 
TEST_F(FormatTest,FormatsClasses)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 
TEST_F(FormatTest,BreakInheritanceStyle)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 
TEST_F(FormatTest,FormatsVariableDeclarationsAfterRecord)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 
TEST_F(FormatTest,FormatsEnum)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 
TEST_F(FormatTest,FormatsEnumsWithErrors)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 
TEST_F(FormatTest,FormatsEnumStruct)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 
TEST_F(FormatTest,FormatsEnumClass)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 
TEST_F(FormatTest,FormatsEnumTypes)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 
TEST_F(FormatTest,FormatsTypedefEnum)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 
TEST_F(FormatTest,FormatsNSEnums)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 
TEST_F(FormatTest,FormatsBitfields)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 
TEST_F(FormatTest,FormatsNamespaces)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 
TEST_F(FormatTest,NamespaceMacros)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 
TEST_F(FormatTest,FormatsCompactNamespaces)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 
TEST_F(FormatTest,FormatsExternC)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 
TEST_F(FormatTest,IndentExternBlockStyle)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 
TEST_F(FormatTest,FormatsInlineASM)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 
TEST_F(FormatTest,FormatTryCatch)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 
TEST_F(FormatTest,FormatTryAsAVariable)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 
TEST_F(FormatTest,FormatSEHTryCatch)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 
TEST_F(FormatTest,IncompleteTryCatchBlocks)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 
TEST_F(FormatTest,FormatTryCatchBraceStyles)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 
TEST_F(FormatTest,StaticInitializers)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 
TEST_F(FormatTest,DesignatedInitializers)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 
TEST_F(FormatTest,NestedStaticInitializers)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 
TEST_F(FormatTest,FormatsSmallMacroDefinitionsInSingleLine)4845 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4846   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4847                "                      \\\n"
4848                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4849 }
4850 
TEST_F(FormatTest,DoesNotBreakPureVirtualFunctionDefinition)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 
TEST_F(FormatTest,BreaksStringLiteralsOnlyInDefine)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 
TEST_F(FormatTest,UnderstandsLinePPDirective)4876 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4877   EXPECT_EQ("# 123 \"A string literal\"",
4878             format("   #     123    \"A string literal\""));
4879 }
4880 
TEST_F(FormatTest,LayoutUnknownPPDirective)4881 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4882   EXPECT_EQ("#;", format("#;"));
4883   verifyFormat("#\n;\n;\n;");
4884 }
4885 
TEST_F(FormatTest,UnescapedEndOfLineEndsPPDirective)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 
TEST_F(FormatTest,EndOfFileEndsPPDirective)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 
TEST_F(FormatTest,DoesntRemoveUnknownTokens)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 
TEST_F(FormatTest,IndentsPPDirectiveWithPPIndentWidth)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 
TEST_F(FormatTest,IndentsPPDirectiveInReducedSpace)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 
TEST_F(FormatTest,HandlePreprocessorDirectiveContext)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 
TEST_F(FormatTest,LayoutSingleHash)4989 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4990 
TEST_F(FormatTest,LayoutCodeInMacroDefinitions)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 
TEST_F(FormatTest,LayoutRemainingTokens)5001 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
5002 
TEST_F(FormatTest,MacroDefinitionInsideStatement)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 
TEST_F(FormatTest,HashInMacroDefinition)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 
TEST_F(FormatTest,RespectWhitespaceInMacroDefinitions)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 
TEST_F(FormatTest,EmptyLinesInMacroDefinitions)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 
TEST_F(FormatTest,MacroDefinitionsWithIncompleteCode)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 
TEST_F(FormatTest,MacrosWithoutTrailingSemicolon)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 
TEST_F(FormatTest,MacroCallsWithoutTrailingSemicolon)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 
TEST_F(FormatTest,FormatsMacrosWithZeroColumnWidth)5357 TEST_F(FormatTest, FormatsMacrosWithZeroColumnWidth) {
5358   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
5359 
5360   verifyFormat("#define A LOOOOOOOOOOOOOOOOOOONG() LOOOOOOOOOOOOOOOOOOONG()",
5361                ZeroColumn);
5362 }
5363 
TEST_F(FormatTest,LayoutMacroDefinitionsStatementsSpanningBlocks)5364 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
5365   verifyFormat("#define A \\\n"
5366                "  f({     \\\n"
5367                "    g();  \\\n"
5368                "  });",
5369                getLLVMStyleWithColumns(11));
5370 }
5371 
TEST_F(FormatTest,IndentPreprocessorDirectives)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 
TEST_F(FormatTest,FormatHashIfNotAtStartOfLine)5746 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5747   verifyFormat("{\n  { a #c; }\n}");
5748 }
5749 
TEST_F(FormatTest,FormatUnbalancedStructuralElements)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 
TEST_F(FormatTest,EscapedNewlines)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 
TEST_F(FormatTest,CalculateSpaceOnConsecutiveLinesInMacro)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 
TEST_F(FormatTest,MixingPreprocessorDirectivesAndNormalCode)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 
TEST_F(FormatTest,LayoutStatementsAroundPreprocessorDirectives)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 
TEST_F(FormatTest,GraciouslyHandleIncorrectPreprocessorConditions)5916 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5917   verifyFormat("#endif\n"
5918                "#if B");
5919 }
5920 
TEST_F(FormatTest,FormatsJoinedLinesOnSubsequentRuns)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 
TEST_F(FormatTest,LayoutBlockInsideParens)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 
TEST_F(FormatTest,LayoutBlockInsideStatement)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 
TEST_F(FormatTest,LayoutNestedBlocks)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 
TEST_F(FormatTest,FormatNestedBlocksInMacros)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 
TEST_F(FormatTest,PutEmptyBlocksIntoOneLine)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 
TEST_F(FormatTest,FormatBeginBlockEndMacros)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 
TEST_F(FormatTest,PreventConfusingIndents)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 
TEST_F(FormatTest,LineBreakingInBinaryExpressions)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 
TEST_F(FormatTest,ExpressionIndentation)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 
TEST_F(FormatTest,ExpressionIndentationBreakingBeforeOperators)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 
TEST_F(FormatTest,ExpressionIndentationStrictAlign)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 
TEST_F(FormatTest,EnforcedOperatorWraps)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 
TEST_F(FormatTest,NoOperandAlignment)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 
TEST_F(FormatTest,BreakingBeforeNonAssigmentOperators)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 
TEST_F(FormatTest,AllowBinPackingInsideArguments)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 
TEST_F(FormatTest,BreakBinaryOperatorsInPresenceOfTemplates)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 
TEST_F(FormatTest,ConstructorInitializers)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 
TEST_F(FormatTest,AllowAllConstructorInitializersOnNextLine)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 
TEST_F(FormatTest,AllowAllArgumentsOnNextLine)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 
TEST_F(FormatTest,AllowAllArgumentsOnNextLineDontAlign)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 
TEST_F(FormatTest,BreakConstructorInitializersAfterColon)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.
TEST_F(FormatTest,MemoizationTests)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 
TEST_F(FormatTest,BreaksAsHighAsPossible)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 
TEST_F(FormatTest,BreaksFunctionDeclarations)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 
TEST_F(FormatTest,DontBreakBeforeQualifiedOperator)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 
TEST_F(FormatTest,TrailingReturnType)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 
TEST_F(FormatTest,DeductionGuides)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 
TEST_F(FormatTest,BreaksFunctionDeclarationsWithTrailingTokens)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 
TEST_F(FormatTest,FunctionAnnotations)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 
TEST_F(FormatTest,BreaksDesireably)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 
TEST_F(FormatTest,FormatsDeclarationsOnePerLine)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 
TEST_F(FormatTest,FormatsOneParameterPerLineIfNecessary)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 
TEST_F(FormatTest,AdaptiveOnePerLineFormatting)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 
TEST_F(FormatTest,FormatsBuilderPattern)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 
TEST_F(FormatTest,BreaksAccordingToOperatorPrecedence)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 
TEST_F(FormatTest,BreaksAfterAssignments)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 
TEST_F(FormatTest,ConfigurableBreakAssignmentPenalty)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 
TEST_F(FormatTest,AlignsAfterAssignments)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 
TEST_F(FormatTest,AlignsAfterReturn)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 
TEST_F(FormatTest,AlignsAfterOpenBracket)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 
TEST_F(FormatTest,ParenthesesAndOperandAlignment)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 
TEST_F(FormatTest,BreaksConditionalExpressions)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 
TEST_F(FormatTest,BreaksConditionalExpressionsAfterOperator)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 
TEST_F(FormatTest,DeclarationsOfMultipleVariables)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 
TEST_F(FormatTest,ConditionalExpressionsInBrackets)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 
TEST_F(FormatTest,AlignsStringLiterals)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 
TEST_F(FormatTest,ReturnTypeBreakingStyle)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 
TEST_F(FormatTest,AlwaysBreakBeforeMultilineStrings)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 
TEST_F(FormatTest,AlignsPipes)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 
TEST_F(FormatTest,KeepStringLabelValuePairsOnALine)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 
TEST_F(FormatTest,UnderstandsEquals)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 
TEST_F(FormatTest,WrapsAtFunctionCallsIfNecessary)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 
TEST_F(FormatTest,WrapsTemplateDeclarations)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 
TEST_F(FormatTest,WrapsTemplateDeclarationsWithComments)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 
TEST_F(FormatTest,WrapsTemplateParameters)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 
TEST_F(FormatTest,WrapsAtNestedNameSpecifiers)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 
TEST_F(FormatTest,UnderstandsTemplateParameters)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 
TEST_F(FormatTest,UnderstandsShiftOperators)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 
TEST_F(FormatTest,BitshiftOperatorWidth)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 
TEST_F(FormatTest,UnderstandsBinaryOperators)9791 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9792   verifyFormat("COMPARE(a, ==, b);");
9793   verifyFormat("auto s = sizeof...(Ts) - 1;");
9794 }
9795 
TEST_F(FormatTest,UnderstandsPointersToMembers)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 
TEST_F(FormatTest,UnderstandsUnaryOperators)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 
TEST_F(FormatTest,DoesNotIndentRelativeToUnaryOperators)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 
TEST_F(FormatTest,UnderstandsOverloadedOperators)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 
TEST_F(FormatTest,UnderstandsFunctionRefQualification)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 
TEST_F(FormatTest,UnderstandsNewAndDelete)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 
TEST_F(FormatTest,UnderstandsUsesOfStarAndAmp)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   verifyFormat("bool b = 3 == int{3} && true;");
10478 
10479   Style.PointerAlignment = FormatStyle::PAS_Middle;
10480   verifyFormat("struct {\n"
10481                "} * ptr;",
10482                Style);
10483   verifyFormat("union {\n"
10484                "} * ptr;",
10485                Style);
10486   verifyFormat("class {\n"
10487                "} * ptr;",
10488                Style);
10489   verifyFormat("struct {\n"
10490                "} && ptr = {};",
10491                Style);
10492   verifyFormat("union {\n"
10493                "} && ptr = {};",
10494                Style);
10495   verifyFormat("class {\n"
10496                "} && ptr = {};",
10497                Style);
10498 
10499   Style.PointerAlignment = FormatStyle::PAS_Right;
10500   verifyFormat("struct {\n"
10501                "} *ptr;",
10502                Style);
10503   verifyFormat("union {\n"
10504                "} *ptr;",
10505                Style);
10506   verifyFormat("class {\n"
10507                "} *ptr;",
10508                Style);
10509   verifyFormat("struct {\n"
10510                "} &&ptr = {};",
10511                Style);
10512   verifyFormat("union {\n"
10513                "} &&ptr = {};",
10514                Style);
10515   verifyFormat("class {\n"
10516                "} &&ptr = {};",
10517                Style);
10518 
10519   verifyIndependentOfContext("MACRO(int *i);");
10520   verifyIndependentOfContext("MACRO(auto *a);");
10521   verifyIndependentOfContext("MACRO(const A *a);");
10522   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
10523   verifyIndependentOfContext("MACRO(decltype(A) *a);");
10524   verifyIndependentOfContext("MACRO(typeof(A) *a);");
10525   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
10526   verifyIndependentOfContext("MACRO(A *const a);");
10527   verifyIndependentOfContext("MACRO(A *restrict a);");
10528   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
10529   verifyIndependentOfContext("MACRO(A *__restrict a);");
10530   verifyIndependentOfContext("MACRO(A *volatile a);");
10531   verifyIndependentOfContext("MACRO(A *__volatile a);");
10532   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
10533   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
10534   verifyIndependentOfContext("MACRO(A *_Nullable a);");
10535   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
10536   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
10537   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
10538   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
10539   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
10540   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
10541   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
10542   verifyIndependentOfContext("MACRO(A *__capability);");
10543   verifyIndependentOfContext("MACRO(A &__capability);");
10544   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
10545   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
10546   // If we add __my_qualifier to AttributeMacros it should always be parsed as
10547   // a type declaration:
10548   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
10549   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
10550   // Also check that TypenameMacros prevents parsing it as multiplication:
10551   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
10552   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
10553 
10554   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
10555   verifyFormat("void f() { f(float{1}, a * a); }");
10556   verifyFormat("void f() { f(float(1), a * a); }");
10557 
10558   verifyFormat("f((void (*)(int))g);");
10559   verifyFormat("f((void (&)(int))g);");
10560   verifyFormat("f((void (^)(int))g);");
10561 
10562   // FIXME: Is there a way to make this work?
10563   // verifyIndependentOfContext("MACRO(A *a);");
10564   verifyFormat("MACRO(A &B);");
10565   verifyFormat("MACRO(A *B);");
10566   verifyFormat("void f() { MACRO(A * B); }");
10567   verifyFormat("void f() { MACRO(A & B); }");
10568 
10569   // This lambda was mis-formatted after D88956 (treating it as a binop):
10570   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
10571   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
10572   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
10573   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
10574 
10575   verifyFormat("DatumHandle const *operator->() const { return input_; }");
10576   verifyFormat("return options != nullptr && operator==(*options);");
10577 
10578   EXPECT_EQ("#define OP(x)                                    \\\n"
10579             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
10580             "    return s << a.DebugString();                 \\\n"
10581             "  }",
10582             format("#define OP(x) \\\n"
10583                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
10584                    "    return s << a.DebugString(); \\\n"
10585                    "  }",
10586                    getLLVMStyleWithColumns(50)));
10587 
10588   // FIXME: We cannot handle this case yet; we might be able to figure out that
10589   // foo<x> d > v; doesn't make sense.
10590   verifyFormat("foo<a<b && c> d> v;");
10591 
10592   FormatStyle PointerMiddle = getLLVMStyle();
10593   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
10594   verifyFormat("delete *x;", PointerMiddle);
10595   verifyFormat("int * x;", PointerMiddle);
10596   verifyFormat("int *[] x;", PointerMiddle);
10597   verifyFormat("template <int * y> f() {}", PointerMiddle);
10598   verifyFormat("int * f(int * a) {}", PointerMiddle);
10599   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
10600   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
10601   verifyFormat("A<int *> a;", PointerMiddle);
10602   verifyFormat("A<int **> a;", PointerMiddle);
10603   verifyFormat("A<int *, int *> a;", PointerMiddle);
10604   verifyFormat("A<int *[]> a;", PointerMiddle);
10605   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
10606   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
10607   verifyFormat("T ** t = new T *;", PointerMiddle);
10608 
10609   // Member function reference qualifiers aren't binary operators.
10610   verifyFormat("string // break\n"
10611                "operator()() & {}");
10612   verifyFormat("string // break\n"
10613                "operator()() && {}");
10614   verifyGoogleFormat("template <typename T>\n"
10615                      "auto x() & -> int {}");
10616 
10617   // Should be binary operators when used as an argument expression (overloaded
10618   // operator invoked as a member function).
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   verifyFormat("void f() { a->operator()(*a * *a); }");
10623 
10624   verifyFormat("int operator()(T (&&)[N]) { return 1; }");
10625   verifyFormat("int operator()(T (&)[N]) { return 0; }");
10626 }
10627 
TEST_F(FormatTest,UnderstandsAttributes)10628 TEST_F(FormatTest, UnderstandsAttributes) {
10629   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
10630   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
10631                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10632   verifyFormat("__attribute__((nodebug)) ::qualified_type f();");
10633   FormatStyle AfterType = getLLVMStyle();
10634   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
10635   verifyFormat("__attribute__((nodebug)) void\n"
10636                "foo() {}\n",
10637                AfterType);
10638   verifyFormat("__unused void\n"
10639                "foo() {}",
10640                AfterType);
10641 
10642   FormatStyle CustomAttrs = getLLVMStyle();
10643   CustomAttrs.AttributeMacros.push_back("__unused");
10644   CustomAttrs.AttributeMacros.push_back("__attr1");
10645   CustomAttrs.AttributeMacros.push_back("__attr2");
10646   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
10647   verifyFormat("vector<SomeType *__attribute((foo))> v;");
10648   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
10649   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
10650   // Check that it is parsed as a multiplication without AttributeMacros and
10651   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
10652   verifyFormat("vector<SomeType * __attr1> v;");
10653   verifyFormat("vector<SomeType __attr1 *> v;");
10654   verifyFormat("vector<SomeType __attr1 *const> v;");
10655   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
10656   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
10657   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
10658   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
10659   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
10660   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
10661   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
10662   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
10663 
10664   // Check that these are not parsed as function declarations:
10665   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10666   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
10667   verifyFormat("SomeType s(InitValue);", CustomAttrs);
10668   verifyFormat("SomeType s{InitValue};", CustomAttrs);
10669   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
10670   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
10671   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
10672   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
10673   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
10674   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
10675 }
10676 
TEST_F(FormatTest,UnderstandsPointerQualifiersInCast)10677 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
10678   // Check that qualifiers on pointers don't break parsing of casts.
10679   verifyFormat("x = (foo *const)*v;");
10680   verifyFormat("x = (foo *volatile)*v;");
10681   verifyFormat("x = (foo *restrict)*v;");
10682   verifyFormat("x = (foo *__attribute__((foo)))*v;");
10683   verifyFormat("x = (foo *_Nonnull)*v;");
10684   verifyFormat("x = (foo *_Nullable)*v;");
10685   verifyFormat("x = (foo *_Null_unspecified)*v;");
10686   verifyFormat("x = (foo *_Nonnull)*v;");
10687   verifyFormat("x = (foo *[[clang::attr]])*v;");
10688   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
10689   verifyFormat("x = (foo *__ptr32)*v;");
10690   verifyFormat("x = (foo *__ptr64)*v;");
10691   verifyFormat("x = (foo *__capability)*v;");
10692 
10693   // Check that we handle multiple trailing qualifiers and skip them all to
10694   // determine that the expression is a cast to a pointer type.
10695   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
10696   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
10697   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
10698   StringRef AllQualifiers =
10699       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
10700       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
10701   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
10702   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
10703 
10704   // Also check that address-of is not parsed as a binary bitwise-and:
10705   verifyFormat("x = (foo *const)&v;");
10706   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
10707   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
10708 
10709   // Check custom qualifiers:
10710   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
10711   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
10712   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
10713   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
10714   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
10715                CustomQualifier);
10716   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
10717                CustomQualifier);
10718 
10719   // Check that unknown identifiers result in binary operator parsing:
10720   verifyFormat("x = (foo * __unknown_qualifier) * v;");
10721   verifyFormat("x = (foo * __unknown_qualifier) & v;");
10722 }
10723 
TEST_F(FormatTest,UnderstandsSquareAttributes)10724 TEST_F(FormatTest, UnderstandsSquareAttributes) {
10725   verifyFormat("SomeType s [[unused]] (InitValue);");
10726   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
10727   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
10728   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
10729   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
10730   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10731                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
10732   verifyFormat("[[nodiscard]] bool f() { return false; }");
10733   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
10734   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
10735   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
10736   verifyFormat("[[nodiscard]] ::qualified_type f();");
10737 
10738   // Make sure we do not mistake attributes for array subscripts.
10739   verifyFormat("int a() {}\n"
10740                "[[unused]] int b() {}\n");
10741   verifyFormat("NSArray *arr;\n"
10742                "arr[[Foo() bar]];");
10743 
10744   // On the other hand, we still need to correctly find array subscripts.
10745   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
10746 
10747   // Make sure that we do not mistake Objective-C method inside array literals
10748   // as attributes, even if those method names are also keywords.
10749   verifyFormat("@[ [foo bar] ];");
10750   verifyFormat("@[ [NSArray class] ];");
10751   verifyFormat("@[ [foo enum] ];");
10752 
10753   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
10754 
10755   // Make sure we do not parse attributes as lambda introducers.
10756   FormatStyle MultiLineFunctions = getLLVMStyle();
10757   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10758   verifyFormat("[[unused]] int b() {\n"
10759                "  return 42;\n"
10760                "}\n",
10761                MultiLineFunctions);
10762 }
10763 
TEST_F(FormatTest,AttributeClass)10764 TEST_F(FormatTest, AttributeClass) {
10765   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
10766   verifyFormat("class S {\n"
10767                "  S(S&&) = default;\n"
10768                "};",
10769                Style);
10770   verifyFormat("class [[nodiscard]] S {\n"
10771                "  S(S&&) = default;\n"
10772                "};",
10773                Style);
10774   verifyFormat("class __attribute((maybeunused)) S {\n"
10775                "  S(S&&) = default;\n"
10776                "};",
10777                Style);
10778   verifyFormat("struct S {\n"
10779                "  S(S&&) = default;\n"
10780                "};",
10781                Style);
10782   verifyFormat("struct [[nodiscard]] S {\n"
10783                "  S(S&&) = default;\n"
10784                "};",
10785                Style);
10786 }
10787 
TEST_F(FormatTest,AttributesAfterMacro)10788 TEST_F(FormatTest, AttributesAfterMacro) {
10789   FormatStyle Style = getLLVMStyle();
10790   verifyFormat("MACRO;\n"
10791                "__attribute__((maybe_unused)) int foo() {\n"
10792                "  //...\n"
10793                "}");
10794 
10795   verifyFormat("MACRO;\n"
10796                "[[nodiscard]] int foo() {\n"
10797                "  //...\n"
10798                "}");
10799 
10800   EXPECT_EQ("MACRO\n\n"
10801             "__attribute__((maybe_unused)) int foo() {\n"
10802             "  //...\n"
10803             "}",
10804             format("MACRO\n\n"
10805                    "__attribute__((maybe_unused)) int foo() {\n"
10806                    "  //...\n"
10807                    "}"));
10808 
10809   EXPECT_EQ("MACRO\n\n"
10810             "[[nodiscard]] int foo() {\n"
10811             "  //...\n"
10812             "}",
10813             format("MACRO\n\n"
10814                    "[[nodiscard]] int foo() {\n"
10815                    "  //...\n"
10816                    "}"));
10817 }
10818 
TEST_F(FormatTest,AttributePenaltyBreaking)10819 TEST_F(FormatTest, AttributePenaltyBreaking) {
10820   FormatStyle Style = getLLVMStyle();
10821   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
10822                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10823                Style);
10824   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
10825                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
10826                Style);
10827   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
10828                "shared_ptr<ALongTypeName> &C d) {\n}",
10829                Style);
10830 }
10831 
TEST_F(FormatTest,UnderstandsEllipsis)10832 TEST_F(FormatTest, UnderstandsEllipsis) {
10833   FormatStyle Style = getLLVMStyle();
10834   verifyFormat("int printf(const char *fmt, ...);");
10835   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
10836   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
10837 
10838   verifyFormat("template <int *...PP> a;", Style);
10839 
10840   Style.PointerAlignment = FormatStyle::PAS_Left;
10841   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
10842 
10843   verifyFormat("template <int*... PP> a;", Style);
10844 
10845   Style.PointerAlignment = FormatStyle::PAS_Middle;
10846   verifyFormat("template <int *... PP> a;", Style);
10847 }
10848 
TEST_F(FormatTest,AdaptivelyFormatsPointersAndReferences)10849 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
10850   EXPECT_EQ("int *a;\n"
10851             "int *a;\n"
10852             "int *a;",
10853             format("int *a;\n"
10854                    "int* a;\n"
10855                    "int *a;",
10856                    getGoogleStyle()));
10857   EXPECT_EQ("int* a;\n"
10858             "int* a;\n"
10859             "int* a;",
10860             format("int* a;\n"
10861                    "int* a;\n"
10862                    "int *a;",
10863                    getGoogleStyle()));
10864   EXPECT_EQ("int *a;\n"
10865             "int *a;\n"
10866             "int *a;",
10867             format("int *a;\n"
10868                    "int * a;\n"
10869                    "int *  a;",
10870                    getGoogleStyle()));
10871   EXPECT_EQ("auto x = [] {\n"
10872             "  int *a;\n"
10873             "  int *a;\n"
10874             "  int *a;\n"
10875             "};",
10876             format("auto x=[]{int *a;\n"
10877                    "int * a;\n"
10878                    "int *  a;};",
10879                    getGoogleStyle()));
10880 }
10881 
TEST_F(FormatTest,UnderstandsRvalueReferences)10882 TEST_F(FormatTest, UnderstandsRvalueReferences) {
10883   verifyFormat("int f(int &&a) {}");
10884   verifyFormat("int f(int a, char &&b) {}");
10885   verifyFormat("void f() { int &&a = b; }");
10886   verifyGoogleFormat("int f(int a, char&& b) {}");
10887   verifyGoogleFormat("void f() { int&& a = b; }");
10888 
10889   verifyIndependentOfContext("A<int &&> a;");
10890   verifyIndependentOfContext("A<int &&, int &&> a;");
10891   verifyGoogleFormat("A<int&&> a;");
10892   verifyGoogleFormat("A<int&&, int&&> a;");
10893 
10894   // Not rvalue references:
10895   verifyFormat("template <bool B, bool C> class A {\n"
10896                "  static_assert(B && C, \"Something is wrong\");\n"
10897                "};");
10898   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
10899   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
10900   verifyFormat("#define A(a, b) (a && b)");
10901 }
10902 
TEST_F(FormatTest,FormatsBinaryOperatorsPrecedingEquals)10903 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
10904   verifyFormat("void f() {\n"
10905                "  x[aaaaaaaaa -\n"
10906                "    b] = 23;\n"
10907                "}",
10908                getLLVMStyleWithColumns(15));
10909 }
10910 
TEST_F(FormatTest,FormatsCasts)10911 TEST_F(FormatTest, FormatsCasts) {
10912   verifyFormat("Type *A = static_cast<Type *>(P);");
10913   verifyFormat("static_cast<Type *>(P);");
10914   verifyFormat("static_cast<Type &>(Fun)(Args);");
10915   verifyFormat("static_cast<Type &>(*Fun)(Args);");
10916   verifyFormat("if (static_cast<int>(A) + B >= 0)\n  ;");
10917   // Check that static_cast<...>(...) does not require the next token to be on
10918   // the same line.
10919   verifyFormat("some_loooong_output << something_something__ << "
10920                "static_cast<const void *>(R)\n"
10921                "                    << something;");
10922   verifyFormat("a = static_cast<Type &>(*Fun)(Args);");
10923   verifyFormat("const_cast<Type &>(*Fun)(Args);");
10924   verifyFormat("dynamic_cast<Type &>(*Fun)(Args);");
10925   verifyFormat("reinterpret_cast<Type &>(*Fun)(Args);");
10926   verifyFormat("Type *A = (Type *)P;");
10927   verifyFormat("Type *A = (vector<Type *, int *>)P;");
10928   verifyFormat("int a = (int)(2.0f);");
10929   verifyFormat("int a = (int)2.0f;");
10930   verifyFormat("x[(int32)y];");
10931   verifyFormat("x = (int32)y;");
10932   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
10933   verifyFormat("int a = (int)*b;");
10934   verifyFormat("int a = (int)2.0f;");
10935   verifyFormat("int a = (int)~0;");
10936   verifyFormat("int a = (int)++a;");
10937   verifyFormat("int a = (int)sizeof(int);");
10938   verifyFormat("int a = (int)+2;");
10939   verifyFormat("my_int a = (my_int)2.0f;");
10940   verifyFormat("my_int a = (my_int)sizeof(int);");
10941   verifyFormat("return (my_int)aaa;");
10942   verifyFormat("#define x ((int)-1)");
10943   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
10944   verifyFormat("#define p(q) ((int *)&q)");
10945   verifyFormat("fn(a)(b) + 1;");
10946 
10947   verifyFormat("void f() { my_int a = (my_int)*b; }");
10948   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
10949   verifyFormat("my_int a = (my_int)~0;");
10950   verifyFormat("my_int a = (my_int)++a;");
10951   verifyFormat("my_int a = (my_int)-2;");
10952   verifyFormat("my_int a = (my_int)1;");
10953   verifyFormat("my_int a = (my_int *)1;");
10954   verifyFormat("my_int a = (const my_int)-1;");
10955   verifyFormat("my_int a = (const my_int *)-1;");
10956   verifyFormat("my_int a = (my_int)(my_int)-1;");
10957   verifyFormat("my_int a = (ns::my_int)-2;");
10958   verifyFormat("case (my_int)ONE:");
10959   verifyFormat("auto x = (X)this;");
10960   // Casts in Obj-C style calls used to not be recognized as such.
10961   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
10962 
10963   // FIXME: single value wrapped with paren will be treated as cast.
10964   verifyFormat("void f(int i = (kValue)*kMask) {}");
10965 
10966   verifyFormat("{ (void)F; }");
10967 
10968   // Don't break after a cast's
10969   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
10970                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
10971                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
10972 
10973   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(x)");
10974   verifyFormat("#define CONF_BOOL(x) (bool *)(x)");
10975   verifyFormat("#define CONF_BOOL(x) (bool)(x)");
10976   verifyFormat("bool *y = (bool *)(void *)(x);");
10977   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)(x)");
10978   verifyFormat("bool *y = (bool *)(void *)(int)(x);");
10979   verifyFormat("#define CONF_BOOL(x) (bool *)(void *)(int)foo(x)");
10980   verifyFormat("bool *y = (bool *)(void *)(int)foo(x);");
10981 
10982   // These are not casts.
10983   verifyFormat("void f(int *) {}");
10984   verifyFormat("f(foo)->b;");
10985   verifyFormat("f(foo).b;");
10986   verifyFormat("f(foo)(b);");
10987   verifyFormat("f(foo)[b];");
10988   verifyFormat("[](foo) { return 4; }(bar);");
10989   verifyFormat("(*funptr)(foo)[4];");
10990   verifyFormat("funptrs[4](foo)[4];");
10991   verifyFormat("void f(int *);");
10992   verifyFormat("void f(int *) = 0;");
10993   verifyFormat("void f(SmallVector<int>) {}");
10994   verifyFormat("void f(SmallVector<int>);");
10995   verifyFormat("void f(SmallVector<int>) = 0;");
10996   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10997   verifyFormat("int a = sizeof(int) * b;");
10998   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10999   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
11000   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
11001   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
11002 
11003   // These are not casts, but at some point were confused with casts.
11004   verifyFormat("virtual void foo(int *) override;");
11005   verifyFormat("virtual void foo(char &) const;");
11006   verifyFormat("virtual void foo(int *a, char *) const;");
11007   verifyFormat("int a = sizeof(int *) + b;");
11008   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
11009   verifyFormat("bool b = f(g<int>) && c;");
11010   verifyFormat("typedef void (*f)(int i) func;");
11011   verifyFormat("void operator++(int) noexcept;");
11012   verifyFormat("void operator++(int &) noexcept;");
11013   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
11014                "&) noexcept;");
11015   verifyFormat(
11016       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
11017   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
11018   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
11019   verifyFormat("void operator delete(nothrow_t &) noexcept;");
11020   verifyFormat("void operator delete(foo &) noexcept;");
11021   verifyFormat("void operator delete(foo) noexcept;");
11022   verifyFormat("void operator delete(int) noexcept;");
11023   verifyFormat("void operator delete(int &) noexcept;");
11024   verifyFormat("void operator delete(int &) volatile noexcept;");
11025   verifyFormat("void operator delete(int &) const");
11026   verifyFormat("void operator delete(int &) = default");
11027   verifyFormat("void operator delete(int &) = delete");
11028   verifyFormat("void operator delete(int &) [[noreturn]]");
11029   verifyFormat("void operator delete(int &) throw();");
11030   verifyFormat("void operator delete(int &) throw(int);");
11031   verifyFormat("auto operator delete(int &) -> int;");
11032   verifyFormat("auto operator delete(int &) override");
11033   verifyFormat("auto operator delete(int &) final");
11034 
11035   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
11036                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
11037   // FIXME: The indentation here is not ideal.
11038   verifyFormat(
11039       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11040       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
11041       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
11042 }
11043 
TEST_F(FormatTest,FormatsFunctionTypes)11044 TEST_F(FormatTest, FormatsFunctionTypes) {
11045   verifyFormat("A<bool()> a;");
11046   verifyFormat("A<SomeType()> a;");
11047   verifyFormat("A<void (*)(int, std::string)> a;");
11048   verifyFormat("A<void *(int)>;");
11049   verifyFormat("void *(*a)(int *, SomeType *);");
11050   verifyFormat("int (*func)(void *);");
11051   verifyFormat("void f() { int (*func)(void *); }");
11052   verifyFormat("template <class CallbackClass>\n"
11053                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
11054 
11055   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
11056   verifyGoogleFormat("void* (*a)(int);");
11057   verifyGoogleFormat(
11058       "template <class CallbackClass>\n"
11059       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
11060 
11061   // Other constructs can look somewhat like function types:
11062   verifyFormat("A<sizeof(*x)> a;");
11063   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
11064   verifyFormat("some_var = function(*some_pointer_var)[0];");
11065   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
11066   verifyFormat("int x = f(&h)();");
11067   verifyFormat("returnsFunction(&param1, &param2)(param);");
11068   verifyFormat("std::function<\n"
11069                "    LooooooooooongTemplatedType<\n"
11070                "        SomeType>*(\n"
11071                "        LooooooooooooooooongType type)>\n"
11072                "    function;",
11073                getGoogleStyleWithColumns(40));
11074 }
11075 
TEST_F(FormatTest,FormatsPointersToArrayTypes)11076 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
11077   verifyFormat("A (*foo_)[6];");
11078   verifyFormat("vector<int> (*foo_)[6];");
11079 }
11080 
TEST_F(FormatTest,BreaksLongVariableDeclarations)11081 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
11082   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11083                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
11084   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
11085                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
11086   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11087                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
11088 
11089   // Different ways of ()-initializiation.
11090   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11091                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
11092   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11093                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
11094   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11095                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
11096   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
11097                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
11098 
11099   // Lambdas should not confuse the variable declaration heuristic.
11100   verifyFormat("LooooooooooooooooongType\n"
11101                "    variable(nullptr, [](A *a) {});",
11102                getLLVMStyleWithColumns(40));
11103 }
11104 
TEST_F(FormatTest,BreaksLongDeclarations)11105 TEST_F(FormatTest, BreaksLongDeclarations) {
11106   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
11107                "    AnotherNameForTheLongType;");
11108   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
11109                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
11110   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11111                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
11112   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
11113                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
11114   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11115                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11116   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
11117                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11118   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
11119                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11120   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
11121                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11122   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
11123                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11124   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
11125                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11126   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
11127                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
11128   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11129                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
11130   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11131                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
11132   FormatStyle Indented = getLLVMStyle();
11133   Indented.IndentWrappedFunctionNames = true;
11134   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11135                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
11136                Indented);
11137   verifyFormat(
11138       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
11139       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11140       Indented);
11141   verifyFormat(
11142       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
11143       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11144       Indented);
11145   verifyFormat(
11146       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
11147       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
11148       Indented);
11149 
11150   // FIXME: Without the comment, this breaks after "(".
11151   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
11152                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
11153                getGoogleStyle());
11154 
11155   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
11156                "                  int LoooooooooooooooooooongParam2) {}");
11157   verifyFormat(
11158       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
11159       "                                   SourceLocation L, IdentifierIn *II,\n"
11160       "                                   Type *T) {}");
11161   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
11162                "ReallyReaaallyLongFunctionName(\n"
11163                "    const std::string &SomeParameter,\n"
11164                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11165                "        &ReallyReallyLongParameterName,\n"
11166                "    const SomeType<string, SomeOtherTemplateParameter>\n"
11167                "        &AnotherLongParameterName) {}");
11168   verifyFormat("template <typename A>\n"
11169                "SomeLoooooooooooooooooooooongType<\n"
11170                "    typename some_namespace::SomeOtherType<A>::Type>\n"
11171                "Function() {}");
11172 
11173   verifyGoogleFormat(
11174       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
11175       "    aaaaaaaaaaaaaaaaaaaaaaa;");
11176   verifyGoogleFormat(
11177       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
11178       "                                   SourceLocation L) {}");
11179   verifyGoogleFormat(
11180       "some_namespace::LongReturnType\n"
11181       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
11182       "    int first_long_parameter, int second_parameter) {}");
11183 
11184   verifyGoogleFormat("template <typename T>\n"
11185                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11186                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
11187   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11188                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
11189 
11190   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
11191                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11192                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11193   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11194                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
11195                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
11196   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
11197                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
11198                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
11199                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11200 
11201   verifyFormat("template <typename T> // Templates on own line.\n"
11202                "static int            // Some comment.\n"
11203                "MyFunction(int a);",
11204                getLLVMStyle());
11205 }
11206 
TEST_F(FormatTest,FormatsAccessModifiers)11207 TEST_F(FormatTest, FormatsAccessModifiers) {
11208   FormatStyle Style = getLLVMStyle();
11209   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
11210             FormatStyle::ELBAMS_LogicalBlock);
11211   verifyFormat("struct foo {\n"
11212                "private:\n"
11213                "  void f() {}\n"
11214                "\n"
11215                "private:\n"
11216                "  int i;\n"
11217                "\n"
11218                "protected:\n"
11219                "  int j;\n"
11220                "};\n",
11221                Style);
11222   verifyFormat("struct foo {\n"
11223                "private:\n"
11224                "  void f() {}\n"
11225                "\n"
11226                "private:\n"
11227                "  int i;\n"
11228                "\n"
11229                "protected:\n"
11230                "  int j;\n"
11231                "};\n",
11232                "struct foo {\n"
11233                "private:\n"
11234                "  void f() {}\n"
11235                "private:\n"
11236                "  int i;\n"
11237                "protected:\n"
11238                "  int j;\n"
11239                "};\n",
11240                Style);
11241   verifyFormat("struct foo { /* comment */\n"
11242                "private:\n"
11243                "  int i;\n"
11244                "  // comment\n"
11245                "private:\n"
11246                "  int j;\n"
11247                "};\n",
11248                Style);
11249   verifyFormat("struct foo {\n"
11250                "#ifdef FOO\n"
11251                "#endif\n"
11252                "private:\n"
11253                "  int i;\n"
11254                "#ifdef FOO\n"
11255                "private:\n"
11256                "#endif\n"
11257                "  int j;\n"
11258                "};\n",
11259                Style);
11260   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11261   verifyFormat("struct foo {\n"
11262                "private:\n"
11263                "  void f() {}\n"
11264                "private:\n"
11265                "  int i;\n"
11266                "protected:\n"
11267                "  int j;\n"
11268                "};\n",
11269                Style);
11270   verifyFormat("struct foo {\n"
11271                "private:\n"
11272                "  void f() {}\n"
11273                "private:\n"
11274                "  int i;\n"
11275                "protected:\n"
11276                "  int j;\n"
11277                "};\n",
11278                "struct foo {\n"
11279                "\n"
11280                "private:\n"
11281                "  void f() {}\n"
11282                "\n"
11283                "private:\n"
11284                "  int i;\n"
11285                "\n"
11286                "protected:\n"
11287                "  int j;\n"
11288                "};\n",
11289                Style);
11290   verifyFormat("struct foo { /* comment */\n"
11291                "private:\n"
11292                "  int i;\n"
11293                "  // comment\n"
11294                "private:\n"
11295                "  int j;\n"
11296                "};\n",
11297                "struct foo { /* comment */\n"
11298                "\n"
11299                "private:\n"
11300                "  int i;\n"
11301                "  // comment\n"
11302                "\n"
11303                "private:\n"
11304                "  int j;\n"
11305                "};\n",
11306                Style);
11307   verifyFormat("struct foo {\n"
11308                "#ifdef FOO\n"
11309                "#endif\n"
11310                "private:\n"
11311                "  int i;\n"
11312                "#ifdef FOO\n"
11313                "private:\n"
11314                "#endif\n"
11315                "  int j;\n"
11316                "};\n",
11317                "struct foo {\n"
11318                "#ifdef FOO\n"
11319                "#endif\n"
11320                "\n"
11321                "private:\n"
11322                "  int i;\n"
11323                "#ifdef FOO\n"
11324                "\n"
11325                "private:\n"
11326                "#endif\n"
11327                "  int j;\n"
11328                "};\n",
11329                Style);
11330   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11331   verifyFormat("struct foo {\n"
11332                "private:\n"
11333                "  void f() {}\n"
11334                "\n"
11335                "private:\n"
11336                "  int i;\n"
11337                "\n"
11338                "protected:\n"
11339                "  int j;\n"
11340                "};\n",
11341                Style);
11342   verifyFormat("struct foo {\n"
11343                "private:\n"
11344                "  void f() {}\n"
11345                "\n"
11346                "private:\n"
11347                "  int i;\n"
11348                "\n"
11349                "protected:\n"
11350                "  int j;\n"
11351                "};\n",
11352                "struct foo {\n"
11353                "private:\n"
11354                "  void f() {}\n"
11355                "private:\n"
11356                "  int i;\n"
11357                "protected:\n"
11358                "  int j;\n"
11359                "};\n",
11360                Style);
11361   verifyFormat("struct foo { /* comment */\n"
11362                "private:\n"
11363                "  int i;\n"
11364                "  // comment\n"
11365                "\n"
11366                "private:\n"
11367                "  int j;\n"
11368                "};\n",
11369                "struct foo { /* comment */\n"
11370                "private:\n"
11371                "  int i;\n"
11372                "  // comment\n"
11373                "\n"
11374                "private:\n"
11375                "  int j;\n"
11376                "};\n",
11377                Style);
11378   verifyFormat("struct foo {\n"
11379                "#ifdef FOO\n"
11380                "#endif\n"
11381                "\n"
11382                "private:\n"
11383                "  int i;\n"
11384                "#ifdef FOO\n"
11385                "\n"
11386                "private:\n"
11387                "#endif\n"
11388                "  int j;\n"
11389                "};\n",
11390                "struct foo {\n"
11391                "#ifdef FOO\n"
11392                "#endif\n"
11393                "private:\n"
11394                "  int i;\n"
11395                "#ifdef FOO\n"
11396                "private:\n"
11397                "#endif\n"
11398                "  int j;\n"
11399                "};\n",
11400                Style);
11401   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11402   EXPECT_EQ("struct foo {\n"
11403             "\n"
11404             "private:\n"
11405             "  void f() {}\n"
11406             "\n"
11407             "private:\n"
11408             "  int i;\n"
11409             "\n"
11410             "protected:\n"
11411             "  int j;\n"
11412             "};\n",
11413             format("struct foo {\n"
11414                    "\n"
11415                    "private:\n"
11416                    "  void f() {}\n"
11417                    "\n"
11418                    "private:\n"
11419                    "  int i;\n"
11420                    "\n"
11421                    "protected:\n"
11422                    "  int j;\n"
11423                    "};\n",
11424                    Style));
11425   verifyFormat("struct foo {\n"
11426                "private:\n"
11427                "  void f() {}\n"
11428                "private:\n"
11429                "  int i;\n"
11430                "protected:\n"
11431                "  int j;\n"
11432                "};\n",
11433                Style);
11434   EXPECT_EQ("struct foo { /* comment */\n"
11435             "\n"
11436             "private:\n"
11437             "  int i;\n"
11438             "  // comment\n"
11439             "\n"
11440             "private:\n"
11441             "  int j;\n"
11442             "};\n",
11443             format("struct foo { /* comment */\n"
11444                    "\n"
11445                    "private:\n"
11446                    "  int i;\n"
11447                    "  // comment\n"
11448                    "\n"
11449                    "private:\n"
11450                    "  int j;\n"
11451                    "};\n",
11452                    Style));
11453   verifyFormat("struct foo { /* comment */\n"
11454                "private:\n"
11455                "  int i;\n"
11456                "  // comment\n"
11457                "private:\n"
11458                "  int j;\n"
11459                "};\n",
11460                Style);
11461   EXPECT_EQ("struct foo {\n"
11462             "#ifdef FOO\n"
11463             "#endif\n"
11464             "\n"
11465             "private:\n"
11466             "  int i;\n"
11467             "#ifdef FOO\n"
11468             "\n"
11469             "private:\n"
11470             "#endif\n"
11471             "  int j;\n"
11472             "};\n",
11473             format("struct foo {\n"
11474                    "#ifdef FOO\n"
11475                    "#endif\n"
11476                    "\n"
11477                    "private:\n"
11478                    "  int i;\n"
11479                    "#ifdef FOO\n"
11480                    "\n"
11481                    "private:\n"
11482                    "#endif\n"
11483                    "  int j;\n"
11484                    "};\n",
11485                    Style));
11486   verifyFormat("struct foo {\n"
11487                "#ifdef FOO\n"
11488                "#endif\n"
11489                "private:\n"
11490                "  int i;\n"
11491                "#ifdef FOO\n"
11492                "private:\n"
11493                "#endif\n"
11494                "  int j;\n"
11495                "};\n",
11496                Style);
11497 
11498   FormatStyle NoEmptyLines = getLLVMStyle();
11499   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11500   verifyFormat("struct foo {\n"
11501                "private:\n"
11502                "  void f() {}\n"
11503                "\n"
11504                "private:\n"
11505                "  int i;\n"
11506                "\n"
11507                "public:\n"
11508                "protected:\n"
11509                "  int j;\n"
11510                "};\n",
11511                NoEmptyLines);
11512 
11513   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11514   verifyFormat("struct foo {\n"
11515                "private:\n"
11516                "  void f() {}\n"
11517                "private:\n"
11518                "  int i;\n"
11519                "public:\n"
11520                "protected:\n"
11521                "  int j;\n"
11522                "};\n",
11523                NoEmptyLines);
11524 
11525   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11526   verifyFormat("struct foo {\n"
11527                "private:\n"
11528                "  void f() {}\n"
11529                "\n"
11530                "private:\n"
11531                "  int i;\n"
11532                "\n"
11533                "public:\n"
11534                "\n"
11535                "protected:\n"
11536                "  int j;\n"
11537                "};\n",
11538                NoEmptyLines);
11539 }
11540 
TEST_F(FormatTest,FormatsAfterAccessModifiers)11541 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
11542 
11543   FormatStyle Style = getLLVMStyle();
11544   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
11545   verifyFormat("struct foo {\n"
11546                "private:\n"
11547                "  void f() {}\n"
11548                "\n"
11549                "private:\n"
11550                "  int i;\n"
11551                "\n"
11552                "protected:\n"
11553                "  int j;\n"
11554                "};\n",
11555                Style);
11556 
11557   // Check if lines are removed.
11558   verifyFormat("struct foo {\n"
11559                "private:\n"
11560                "  void f() {}\n"
11561                "\n"
11562                "private:\n"
11563                "  int i;\n"
11564                "\n"
11565                "protected:\n"
11566                "  int j;\n"
11567                "};\n",
11568                "struct foo {\n"
11569                "private:\n"
11570                "\n"
11571                "  void f() {}\n"
11572                "\n"
11573                "private:\n"
11574                "\n"
11575                "  int i;\n"
11576                "\n"
11577                "protected:\n"
11578                "\n"
11579                "  int j;\n"
11580                "};\n",
11581                Style);
11582 
11583   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11584   verifyFormat("struct foo {\n"
11585                "private:\n"
11586                "\n"
11587                "  void f() {}\n"
11588                "\n"
11589                "private:\n"
11590                "\n"
11591                "  int i;\n"
11592                "\n"
11593                "protected:\n"
11594                "\n"
11595                "  int j;\n"
11596                "};\n",
11597                Style);
11598 
11599   // Check if lines are added.
11600   verifyFormat("struct foo {\n"
11601                "private:\n"
11602                "\n"
11603                "  void f() {}\n"
11604                "\n"
11605                "private:\n"
11606                "\n"
11607                "  int i;\n"
11608                "\n"
11609                "protected:\n"
11610                "\n"
11611                "  int j;\n"
11612                "};\n",
11613                "struct foo {\n"
11614                "private:\n"
11615                "  void f() {}\n"
11616                "\n"
11617                "private:\n"
11618                "  int i;\n"
11619                "\n"
11620                "protected:\n"
11621                "  int j;\n"
11622                "};\n",
11623                Style);
11624 
11625   // Leave tests rely on the code layout, test::messUp can not be used.
11626   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11627   Style.MaxEmptyLinesToKeep = 0u;
11628   verifyFormat("struct foo {\n"
11629                "private:\n"
11630                "  void f() {}\n"
11631                "\n"
11632                "private:\n"
11633                "  int i;\n"
11634                "\n"
11635                "protected:\n"
11636                "  int j;\n"
11637                "};\n",
11638                Style);
11639 
11640   // Check if MaxEmptyLinesToKeep is respected.
11641   EXPECT_EQ("struct foo {\n"
11642             "private:\n"
11643             "  void f() {}\n"
11644             "\n"
11645             "private:\n"
11646             "  int i;\n"
11647             "\n"
11648             "protected:\n"
11649             "  int j;\n"
11650             "};\n",
11651             format("struct foo {\n"
11652                    "private:\n"
11653                    "\n\n\n"
11654                    "  void f() {}\n"
11655                    "\n"
11656                    "private:\n"
11657                    "\n\n\n"
11658                    "  int i;\n"
11659                    "\n"
11660                    "protected:\n"
11661                    "\n\n\n"
11662                    "  int j;\n"
11663                    "};\n",
11664                    Style));
11665 
11666   Style.MaxEmptyLinesToKeep = 1u;
11667   EXPECT_EQ("struct foo {\n"
11668             "private:\n"
11669             "\n"
11670             "  void f() {}\n"
11671             "\n"
11672             "private:\n"
11673             "\n"
11674             "  int i;\n"
11675             "\n"
11676             "protected:\n"
11677             "\n"
11678             "  int j;\n"
11679             "};\n",
11680             format("struct foo {\n"
11681                    "private:\n"
11682                    "\n"
11683                    "  void f() {}\n"
11684                    "\n"
11685                    "private:\n"
11686                    "\n"
11687                    "  int i;\n"
11688                    "\n"
11689                    "protected:\n"
11690                    "\n"
11691                    "  int j;\n"
11692                    "};\n",
11693                    Style));
11694   // Check if no lines are kept.
11695   EXPECT_EQ("struct foo {\n"
11696             "private:\n"
11697             "  void f() {}\n"
11698             "\n"
11699             "private:\n"
11700             "  int i;\n"
11701             "\n"
11702             "protected:\n"
11703             "  int j;\n"
11704             "};\n",
11705             format("struct foo {\n"
11706                    "private:\n"
11707                    "  void f() {}\n"
11708                    "\n"
11709                    "private:\n"
11710                    "  int i;\n"
11711                    "\n"
11712                    "protected:\n"
11713                    "  int j;\n"
11714                    "};\n",
11715                    Style));
11716   // Check if MaxEmptyLinesToKeep is respected.
11717   EXPECT_EQ("struct foo {\n"
11718             "private:\n"
11719             "\n"
11720             "  void f() {}\n"
11721             "\n"
11722             "private:\n"
11723             "\n"
11724             "  int i;\n"
11725             "\n"
11726             "protected:\n"
11727             "\n"
11728             "  int j;\n"
11729             "};\n",
11730             format("struct foo {\n"
11731                    "private:\n"
11732                    "\n\n\n"
11733                    "  void f() {}\n"
11734                    "\n"
11735                    "private:\n"
11736                    "\n\n\n"
11737                    "  int i;\n"
11738                    "\n"
11739                    "protected:\n"
11740                    "\n\n\n"
11741                    "  int j;\n"
11742                    "};\n",
11743                    Style));
11744 
11745   Style.MaxEmptyLinesToKeep = 10u;
11746   EXPECT_EQ("struct foo {\n"
11747             "private:\n"
11748             "\n\n\n"
11749             "  void f() {}\n"
11750             "\n"
11751             "private:\n"
11752             "\n\n\n"
11753             "  int i;\n"
11754             "\n"
11755             "protected:\n"
11756             "\n\n\n"
11757             "  int j;\n"
11758             "};\n",
11759             format("struct foo {\n"
11760                    "private:\n"
11761                    "\n\n\n"
11762                    "  void f() {}\n"
11763                    "\n"
11764                    "private:\n"
11765                    "\n\n\n"
11766                    "  int i;\n"
11767                    "\n"
11768                    "protected:\n"
11769                    "\n\n\n"
11770                    "  int j;\n"
11771                    "};\n",
11772                    Style));
11773 
11774   // Test with comments.
11775   Style = getLLVMStyle();
11776   verifyFormat("struct foo {\n"
11777                "private:\n"
11778                "  // comment\n"
11779                "  void f() {}\n"
11780                "\n"
11781                "private: /* comment */\n"
11782                "  int i;\n"
11783                "};\n",
11784                Style);
11785   verifyFormat("struct foo {\n"
11786                "private:\n"
11787                "  // comment\n"
11788                "  void f() {}\n"
11789                "\n"
11790                "private: /* comment */\n"
11791                "  int i;\n"
11792                "};\n",
11793                "struct foo {\n"
11794                "private:\n"
11795                "\n"
11796                "  // comment\n"
11797                "  void f() {}\n"
11798                "\n"
11799                "private: /* comment */\n"
11800                "\n"
11801                "  int i;\n"
11802                "};\n",
11803                Style);
11804 
11805   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11806   verifyFormat("struct foo {\n"
11807                "private:\n"
11808                "\n"
11809                "  // comment\n"
11810                "  void f() {}\n"
11811                "\n"
11812                "private: /* comment */\n"
11813                "\n"
11814                "  int i;\n"
11815                "};\n",
11816                "struct foo {\n"
11817                "private:\n"
11818                "  // comment\n"
11819                "  void f() {}\n"
11820                "\n"
11821                "private: /* comment */\n"
11822                "  int i;\n"
11823                "};\n",
11824                Style);
11825   verifyFormat("struct foo {\n"
11826                "private:\n"
11827                "\n"
11828                "  // comment\n"
11829                "  void f() {}\n"
11830                "\n"
11831                "private: /* comment */\n"
11832                "\n"
11833                "  int i;\n"
11834                "};\n",
11835                Style);
11836 
11837   // Test with preprocessor defines.
11838   Style = getLLVMStyle();
11839   verifyFormat("struct foo {\n"
11840                "private:\n"
11841                "#ifdef FOO\n"
11842                "#endif\n"
11843                "  void f() {}\n"
11844                "};\n",
11845                Style);
11846   verifyFormat("struct foo {\n"
11847                "private:\n"
11848                "#ifdef FOO\n"
11849                "#endif\n"
11850                "  void f() {}\n"
11851                "};\n",
11852                "struct foo {\n"
11853                "private:\n"
11854                "\n"
11855                "#ifdef FOO\n"
11856                "#endif\n"
11857                "  void f() {}\n"
11858                "};\n",
11859                Style);
11860 
11861   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11862   verifyFormat("struct foo {\n"
11863                "private:\n"
11864                "\n"
11865                "#ifdef FOO\n"
11866                "#endif\n"
11867                "  void f() {}\n"
11868                "};\n",
11869                "struct foo {\n"
11870                "private:\n"
11871                "#ifdef FOO\n"
11872                "#endif\n"
11873                "  void f() {}\n"
11874                "};\n",
11875                Style);
11876   verifyFormat("struct foo {\n"
11877                "private:\n"
11878                "\n"
11879                "#ifdef FOO\n"
11880                "#endif\n"
11881                "  void f() {}\n"
11882                "};\n",
11883                Style);
11884 }
11885 
TEST_F(FormatTest,FormatsAfterAndBeforeAccessModifiersInteraction)11886 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
11887   // Combined tests of EmptyLineAfterAccessModifier and
11888   // EmptyLineBeforeAccessModifier.
11889   FormatStyle Style = getLLVMStyle();
11890   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11891   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11892   verifyFormat("struct foo {\n"
11893                "private:\n"
11894                "\n"
11895                "protected:\n"
11896                "};\n",
11897                Style);
11898 
11899   Style.MaxEmptyLinesToKeep = 10u;
11900   // Both remove all new lines.
11901   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11902   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11903   verifyFormat("struct foo {\n"
11904                "private:\n"
11905                "protected:\n"
11906                "};\n",
11907                "struct foo {\n"
11908                "private:\n"
11909                "\n\n\n"
11910                "protected:\n"
11911                "};\n",
11912                Style);
11913 
11914   // Leave tests rely on the code layout, test::messUp can not be used.
11915   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11916   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11917   Style.MaxEmptyLinesToKeep = 10u;
11918   EXPECT_EQ("struct foo {\n"
11919             "private:\n"
11920             "\n\n\n"
11921             "protected:\n"
11922             "};\n",
11923             format("struct foo {\n"
11924                    "private:\n"
11925                    "\n\n\n"
11926                    "protected:\n"
11927                    "};\n",
11928                    Style));
11929   Style.MaxEmptyLinesToKeep = 3u;
11930   EXPECT_EQ("struct foo {\n"
11931             "private:\n"
11932             "\n\n\n"
11933             "protected:\n"
11934             "};\n",
11935             format("struct foo {\n"
11936                    "private:\n"
11937                    "\n\n\n"
11938                    "protected:\n"
11939                    "};\n",
11940                    Style));
11941   Style.MaxEmptyLinesToKeep = 1u;
11942   EXPECT_EQ("struct foo {\n"
11943             "private:\n"
11944             "\n\n\n"
11945             "protected:\n"
11946             "};\n",
11947             format("struct foo {\n"
11948                    "private:\n"
11949                    "\n\n\n"
11950                    "protected:\n"
11951                    "};\n",
11952                    Style)); // Based on new lines in original document and not
11953                             // on the setting.
11954 
11955   Style.MaxEmptyLinesToKeep = 10u;
11956   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11957   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11958   // Newlines are kept if they are greater than zero,
11959   // test::messUp removes all new lines which changes the logic
11960   EXPECT_EQ("struct foo {\n"
11961             "private:\n"
11962             "\n\n\n"
11963             "protected:\n"
11964             "};\n",
11965             format("struct foo {\n"
11966                    "private:\n"
11967                    "\n\n\n"
11968                    "protected:\n"
11969                    "};\n",
11970                    Style));
11971 
11972   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11973   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11974   // test::messUp removes all new lines which changes the logic
11975   EXPECT_EQ("struct foo {\n"
11976             "private:\n"
11977             "\n\n\n"
11978             "protected:\n"
11979             "};\n",
11980             format("struct foo {\n"
11981                    "private:\n"
11982                    "\n\n\n"
11983                    "protected:\n"
11984                    "};\n",
11985                    Style));
11986 
11987   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
11988   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11989   EXPECT_EQ("struct foo {\n"
11990             "private:\n"
11991             "\n\n\n"
11992             "protected:\n"
11993             "};\n",
11994             format("struct foo {\n"
11995                    "private:\n"
11996                    "\n\n\n"
11997                    "protected:\n"
11998                    "};\n",
11999                    Style)); // test::messUp removes all new lines which changes
12000                             // the logic.
12001 
12002   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
12003   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
12004   verifyFormat("struct foo {\n"
12005                "private:\n"
12006                "protected:\n"
12007                "};\n",
12008                "struct foo {\n"
12009                "private:\n"
12010                "\n\n\n"
12011                "protected:\n"
12012                "};\n",
12013                Style);
12014 
12015   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
12016   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
12017   EXPECT_EQ("struct foo {\n"
12018             "private:\n"
12019             "\n\n\n"
12020             "protected:\n"
12021             "};\n",
12022             format("struct foo {\n"
12023                    "private:\n"
12024                    "\n\n\n"
12025                    "protected:\n"
12026                    "};\n",
12027                    Style)); // test::messUp removes all new lines which changes
12028                             // the logic.
12029 
12030   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
12031   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
12032   verifyFormat("struct foo {\n"
12033                "private:\n"
12034                "protected:\n"
12035                "};\n",
12036                "struct foo {\n"
12037                "private:\n"
12038                "\n\n\n"
12039                "protected:\n"
12040                "};\n",
12041                Style);
12042 
12043   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
12044   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
12045   verifyFormat("struct foo {\n"
12046                "private:\n"
12047                "protected:\n"
12048                "};\n",
12049                "struct foo {\n"
12050                "private:\n"
12051                "\n\n\n"
12052                "protected:\n"
12053                "};\n",
12054                Style);
12055 
12056   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
12057   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
12058   verifyFormat("struct foo {\n"
12059                "private:\n"
12060                "protected:\n"
12061                "};\n",
12062                "struct foo {\n"
12063                "private:\n"
12064                "\n\n\n"
12065                "protected:\n"
12066                "};\n",
12067                Style);
12068 
12069   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
12070   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
12071   verifyFormat("struct foo {\n"
12072                "private:\n"
12073                "protected:\n"
12074                "};\n",
12075                "struct foo {\n"
12076                "private:\n"
12077                "\n\n\n"
12078                "protected:\n"
12079                "};\n",
12080                Style);
12081 }
12082 
TEST_F(FormatTest,FormatsArrays)12083 TEST_F(FormatTest, FormatsArrays) {
12084   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
12085                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
12086   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
12087                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
12088   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
12089                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
12090   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12091                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
12092   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12093                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
12094   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12095                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
12096                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
12097   verifyFormat(
12098       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
12099       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
12100       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
12101   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
12102                "    .aaaaaaaaaaaaaaaaaaaaaa();");
12103 
12104   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
12105                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
12106   verifyFormat(
12107       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
12108       "                                  .aaaaaaa[0]\n"
12109       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
12110   verifyFormat("a[::b::c];");
12111 
12112   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
12113 
12114   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12115   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
12116 }
12117 
TEST_F(FormatTest,LineStartsWithSpecialCharacter)12118 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
12119   verifyFormat("(a)->b();");
12120   verifyFormat("--a;");
12121 }
12122 
TEST_F(FormatTest,HandlesIncludeDirectives)12123 TEST_F(FormatTest, HandlesIncludeDirectives) {
12124   verifyFormat("#include <string>\n"
12125                "#include <a/b/c.h>\n"
12126                "#include \"a/b/string\"\n"
12127                "#include \"string.h\"\n"
12128                "#include \"string.h\"\n"
12129                "#include <a-a>\n"
12130                "#include < path with space >\n"
12131                "#include_next <test.h>"
12132                "#include \"abc.h\" // this is included for ABC\n"
12133                "#include \"some long include\" // with a comment\n"
12134                "#include \"some very long include path\"\n"
12135                "#include <some/very/long/include/path>\n",
12136                getLLVMStyleWithColumns(35));
12137   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
12138   EXPECT_EQ("#include <a>", format("#include<a>"));
12139 
12140   verifyFormat("#import <string>");
12141   verifyFormat("#import <a/b/c.h>");
12142   verifyFormat("#import \"a/b/string\"");
12143   verifyFormat("#import \"string.h\"");
12144   verifyFormat("#import \"string.h\"");
12145   verifyFormat("#if __has_include(<strstream>)\n"
12146                "#include <strstream>\n"
12147                "#endif");
12148 
12149   verifyFormat("#define MY_IMPORT <a/b>");
12150 
12151   verifyFormat("#if __has_include(<a/b>)");
12152   verifyFormat("#if __has_include_next(<a/b>)");
12153   verifyFormat("#define F __has_include(<a/b>)");
12154   verifyFormat("#define F __has_include_next(<a/b>)");
12155 
12156   // Protocol buffer definition or missing "#".
12157   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
12158                getLLVMStyleWithColumns(30));
12159 
12160   FormatStyle Style = getLLVMStyle();
12161   Style.AlwaysBreakBeforeMultilineStrings = true;
12162   Style.ColumnLimit = 0;
12163   verifyFormat("#import \"abc.h\"", Style);
12164 
12165   // But 'import' might also be a regular C++ namespace.
12166   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12167                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
12168 }
12169 
12170 //===----------------------------------------------------------------------===//
12171 // Error recovery tests.
12172 //===----------------------------------------------------------------------===//
12173 
TEST_F(FormatTest,IncompleteParameterLists)12174 TEST_F(FormatTest, IncompleteParameterLists) {
12175   FormatStyle NoBinPacking = getLLVMStyle();
12176   NoBinPacking.BinPackParameters = false;
12177   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
12178                "                        double *min_x,\n"
12179                "                        double *max_x,\n"
12180                "                        double *min_y,\n"
12181                "                        double *max_y,\n"
12182                "                        double *min_z,\n"
12183                "                        double *max_z, ) {}",
12184                NoBinPacking);
12185 }
12186 
TEST_F(FormatTest,IncorrectCodeTrailingStuff)12187 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
12188   verifyFormat("void f() { return; }\n42");
12189   verifyFormat("void f() {\n"
12190                "  if (0)\n"
12191                "    return;\n"
12192                "}\n"
12193                "42");
12194   verifyFormat("void f() { return }\n42");
12195   verifyFormat("void f() {\n"
12196                "  if (0)\n"
12197                "    return\n"
12198                "}\n"
12199                "42");
12200 }
12201 
TEST_F(FormatTest,IncorrectCodeMissingSemicolon)12202 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
12203   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
12204   EXPECT_EQ("void f() {\n"
12205             "  if (a)\n"
12206             "    return\n"
12207             "}",
12208             format("void  f  (  )  {  if  ( a )  return  }"));
12209   EXPECT_EQ("namespace N {\n"
12210             "void f()\n"
12211             "}",
12212             format("namespace  N  {  void f()  }"));
12213   EXPECT_EQ("namespace N {\n"
12214             "void f() {}\n"
12215             "void g()\n"
12216             "} // namespace N",
12217             format("namespace N  { void f( ) { } void g( ) }"));
12218 }
12219 
TEST_F(FormatTest,IndentationWithinColumnLimitNotPossible)12220 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
12221   verifyFormat("int aaaaaaaa =\n"
12222                "    // Overlylongcomment\n"
12223                "    b;",
12224                getLLVMStyleWithColumns(20));
12225   verifyFormat("function(\n"
12226                "    ShortArgument,\n"
12227                "    LoooooooooooongArgument);\n",
12228                getLLVMStyleWithColumns(20));
12229 }
12230 
TEST_F(FormatTest,IncorrectAccessSpecifier)12231 TEST_F(FormatTest, IncorrectAccessSpecifier) {
12232   verifyFormat("public:");
12233   verifyFormat("class A {\n"
12234                "public\n"
12235                "  void f() {}\n"
12236                "};");
12237   verifyFormat("public\n"
12238                "int qwerty;");
12239   verifyFormat("public\n"
12240                "B {}");
12241   verifyFormat("public\n"
12242                "{}");
12243   verifyFormat("public\n"
12244                "B { int x; }");
12245 }
12246 
TEST_F(FormatTest,IncorrectCodeUnbalancedBraces)12247 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
12248   verifyFormat("{");
12249   verifyFormat("#})");
12250   verifyNoCrash("(/**/[:!] ?[).");
12251 }
12252 
TEST_F(FormatTest,IncorrectUnbalancedBracesInMacrosWithUnicode)12253 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
12254   // Found by oss-fuzz:
12255   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
12256   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
12257   Style.ColumnLimit = 60;
12258   verifyNoCrash(
12259       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
12260       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
12261       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
12262       Style);
12263 }
12264 
TEST_F(FormatTest,IncorrectCodeDoNoWhile)12265 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
12266   verifyFormat("do {\n}");
12267   verifyFormat("do {\n}\n"
12268                "f();");
12269   verifyFormat("do {\n}\n"
12270                "wheeee(fun);");
12271   verifyFormat("do {\n"
12272                "  f();\n"
12273                "}");
12274 }
12275 
TEST_F(FormatTest,IncorrectCodeMissingParens)12276 TEST_F(FormatTest, IncorrectCodeMissingParens) {
12277   verifyFormat("if {\n  foo;\n  foo();\n}");
12278   verifyFormat("switch {\n  foo;\n  foo();\n}");
12279   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
12280   verifyIncompleteFormat("ERROR: for target;");
12281   verifyFormat("while {\n  foo;\n  foo();\n}");
12282   verifyFormat("do {\n  foo;\n  foo();\n} while;");
12283 }
12284 
TEST_F(FormatTest,DoesNotTouchUnwrappedLinesWithErrors)12285 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
12286   verifyIncompleteFormat("namespace {\n"
12287                          "class Foo { Foo (\n"
12288                          "};\n"
12289                          "} // namespace");
12290 }
12291 
TEST_F(FormatTest,IncorrectCodeErrorDetection)12292 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
12293   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
12294   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
12295   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
12296   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
12297 
12298   EXPECT_EQ("{\n"
12299             "  {\n"
12300             "    breakme(\n"
12301             "        qwe);\n"
12302             "  }\n",
12303             format("{\n"
12304                    "    {\n"
12305                    " breakme(qwe);\n"
12306                    "}\n",
12307                    getLLVMStyleWithColumns(10)));
12308 }
12309 
TEST_F(FormatTest,LayoutCallsInsideBraceInitializers)12310 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
12311   verifyFormat("int x = {\n"
12312                "    avariable,\n"
12313                "    b(alongervariable)};",
12314                getLLVMStyleWithColumns(25));
12315 }
12316 
TEST_F(FormatTest,LayoutBraceInitializersInReturnStatement)12317 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
12318   verifyFormat("return (a)(b){1, 2, 3};");
12319 }
12320 
TEST_F(FormatTest,LayoutCxx11BraceInitializers)12321 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
12322   verifyFormat("vector<int> x{1, 2, 3, 4};");
12323   verifyFormat("vector<int> x{\n"
12324                "    1,\n"
12325                "    2,\n"
12326                "    3,\n"
12327                "    4,\n"
12328                "};");
12329   verifyFormat("vector<T> x{{}, {}, {}, {}};");
12330   verifyFormat("f({1, 2});");
12331   verifyFormat("auto v = Foo{-1};");
12332   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
12333   verifyFormat("Class::Class : member{1, 2, 3} {}");
12334   verifyFormat("new vector<int>{1, 2, 3};");
12335   verifyFormat("new int[3]{1, 2, 3};");
12336   verifyFormat("new int{1};");
12337   verifyFormat("return {arg1, arg2};");
12338   verifyFormat("return {arg1, SomeType{parameter}};");
12339   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
12340   verifyFormat("new T{arg1, arg2};");
12341   verifyFormat("f(MyMap[{composite, key}]);");
12342   verifyFormat("class Class {\n"
12343                "  T member = {arg1, arg2};\n"
12344                "};");
12345   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
12346   verifyFormat("const struct A a = {.a = 1, .b = 2};");
12347   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
12348   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
12349   verifyFormat("int a = std::is_integral<int>{} + 0;");
12350 
12351   verifyFormat("int foo(int i) { return fo1{}(i); }");
12352   verifyFormat("int foo(int i) { return fo1{}(i); }");
12353   verifyFormat("auto i = decltype(x){};");
12354   verifyFormat("auto i = typeof(x){};");
12355   verifyFormat("auto i = _Atomic(x){};");
12356   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
12357   verifyFormat("Node n{1, Node{1000}, //\n"
12358                "       2};");
12359   verifyFormat("Aaaa aaaaaaa{\n"
12360                "    {\n"
12361                "        aaaa,\n"
12362                "    },\n"
12363                "};");
12364   verifyFormat("class C : public D {\n"
12365                "  SomeClass SC{2};\n"
12366                "};");
12367   verifyFormat("class C : public A {\n"
12368                "  class D : public B {\n"
12369                "    void f() { int i{2}; }\n"
12370                "  };\n"
12371                "};");
12372   verifyFormat("#define A {a, a},");
12373   // Don't confuse braced list initializers with compound statements.
12374   verifyFormat(
12375       "class A {\n"
12376       "  A() : a{} {}\n"
12377       "  A(int b) : b(b) {}\n"
12378       "  A(int a, int b) : a(a), bs{{bs...}} { f(); }\n"
12379       "  int a, b;\n"
12380       "  explicit Expr(const Scalar<Result> &x) : u{Constant<Result>{x}} {}\n"
12381       "  explicit Expr(Scalar<Result> &&x) : u{Constant<Result>{std::move(x)}} "
12382       "{}\n"
12383       "};");
12384 
12385   // Avoid breaking between equal sign and opening brace
12386   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
12387   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
12388   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
12389                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
12390                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
12391                "     {\"ccccccccccccccccccccc\", 2}};",
12392                AvoidBreakingFirstArgument);
12393 
12394   // Binpacking only if there is no trailing comma
12395   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
12396                "                      cccccccccc, dddddddddd};",
12397                getLLVMStyleWithColumns(50));
12398   verifyFormat("const Aaaaaa aaaaa = {\n"
12399                "    aaaaaaaaaaa,\n"
12400                "    bbbbbbbbbbb,\n"
12401                "    ccccccccccc,\n"
12402                "    ddddddddddd,\n"
12403                "};",
12404                getLLVMStyleWithColumns(50));
12405 
12406   // Cases where distinguising braced lists and blocks is hard.
12407   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
12408   verifyFormat("void f() {\n"
12409                "  return; // comment\n"
12410                "}\n"
12411                "SomeType t;");
12412   verifyFormat("void f() {\n"
12413                "  if (a) {\n"
12414                "    f();\n"
12415                "  }\n"
12416                "}\n"
12417                "SomeType t;");
12418 
12419   // In combination with BinPackArguments = false.
12420   FormatStyle NoBinPacking = getLLVMStyle();
12421   NoBinPacking.BinPackArguments = false;
12422   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
12423                "                      bbbbb,\n"
12424                "                      ccccc,\n"
12425                "                      ddddd,\n"
12426                "                      eeeee,\n"
12427                "                      ffffff,\n"
12428                "                      ggggg,\n"
12429                "                      hhhhhh,\n"
12430                "                      iiiiii,\n"
12431                "                      jjjjjj,\n"
12432                "                      kkkkkk};",
12433                NoBinPacking);
12434   verifyFormat("const Aaaaaa aaaaa = {\n"
12435                "    aaaaa,\n"
12436                "    bbbbb,\n"
12437                "    ccccc,\n"
12438                "    ddddd,\n"
12439                "    eeeee,\n"
12440                "    ffffff,\n"
12441                "    ggggg,\n"
12442                "    hhhhhh,\n"
12443                "    iiiiii,\n"
12444                "    jjjjjj,\n"
12445                "    kkkkkk,\n"
12446                "};",
12447                NoBinPacking);
12448   verifyFormat(
12449       "const Aaaaaa aaaaa = {\n"
12450       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
12451       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
12452       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
12453       "};",
12454       NoBinPacking);
12455 
12456   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12457   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
12458             "    CDDDP83848_BMCR_REGISTER,\n"
12459             "    CDDDP83848_BMSR_REGISTER,\n"
12460             "    CDDDP83848_RBR_REGISTER};",
12461             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
12462                    "                                CDDDP83848_BMSR_REGISTER,\n"
12463                    "                                CDDDP83848_RBR_REGISTER};",
12464                    NoBinPacking));
12465 
12466   // FIXME: The alignment of these trailing comments might be bad. Then again,
12467   // this might be utterly useless in real code.
12468   verifyFormat("Constructor::Constructor()\n"
12469                "    : some_value{         //\n"
12470                "                 aaaaaaa, //\n"
12471                "                 bbbbbbb} {}");
12472 
12473   // In braced lists, the first comment is always assumed to belong to the
12474   // first element. Thus, it can be moved to the next or previous line as
12475   // appropriate.
12476   EXPECT_EQ("function({// First element:\n"
12477             "          1,\n"
12478             "          // Second element:\n"
12479             "          2});",
12480             format("function({\n"
12481                    "    // First element:\n"
12482                    "    1,\n"
12483                    "    // Second element:\n"
12484                    "    2});"));
12485   EXPECT_EQ("std::vector<int> MyNumbers{\n"
12486             "    // First element:\n"
12487             "    1,\n"
12488             "    // Second element:\n"
12489             "    2};",
12490             format("std::vector<int> MyNumbers{// First element:\n"
12491                    "                           1,\n"
12492                    "                           // Second element:\n"
12493                    "                           2};",
12494                    getLLVMStyleWithColumns(30)));
12495   // A trailing comma should still lead to an enforced line break and no
12496   // binpacking.
12497   EXPECT_EQ("vector<int> SomeVector = {\n"
12498             "    // aaa\n"
12499             "    1,\n"
12500             "    2,\n"
12501             "};",
12502             format("vector<int> SomeVector = { // aaa\n"
12503                    "    1, 2, };"));
12504 
12505   // C++11 brace initializer list l-braces should not be treated any differently
12506   // when breaking before lambda bodies is enabled
12507   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
12508   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
12509   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
12510   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
12511   verifyFormat(
12512       "std::runtime_error{\n"
12513       "    \"Long string which will force a break onto the next line...\"};",
12514       BreakBeforeLambdaBody);
12515 
12516   FormatStyle ExtraSpaces = getLLVMStyle();
12517   ExtraSpaces.Cpp11BracedListStyle = false;
12518   ExtraSpaces.ColumnLimit = 75;
12519   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
12520   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
12521   verifyFormat("f({ 1, 2 });", ExtraSpaces);
12522   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
12523   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
12524   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
12525   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
12526   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
12527   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
12528   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
12529   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
12530   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
12531   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
12532   verifyFormat("class Class {\n"
12533                "  T member = { arg1, arg2 };\n"
12534                "};",
12535                ExtraSpaces);
12536   verifyFormat(
12537       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12538       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
12539       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
12540       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
12541       ExtraSpaces);
12542   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
12543   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
12544                ExtraSpaces);
12545   verifyFormat(
12546       "someFunction(OtherParam,\n"
12547       "             BracedList{ // comment 1 (Forcing interesting break)\n"
12548       "                         param1, param2,\n"
12549       "                         // comment 2\n"
12550       "                         param3, param4 });",
12551       ExtraSpaces);
12552   verifyFormat(
12553       "std::this_thread::sleep_for(\n"
12554       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
12555       ExtraSpaces);
12556   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
12557                "    aaaaaaa,\n"
12558                "    aaaaaaaaaa,\n"
12559                "    aaaaa,\n"
12560                "    aaaaaaaaaaaaaaa,\n"
12561                "    aaa,\n"
12562                "    aaaaaaaaaa,\n"
12563                "    a,\n"
12564                "    aaaaaaaaaaaaaaaaaaaaa,\n"
12565                "    aaaaaaaaaaaa,\n"
12566                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
12567                "    aaaaaaa,\n"
12568                "    a};");
12569   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
12570   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
12571   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
12572 
12573   // Avoid breaking between initializer/equal sign and opening brace
12574   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
12575   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
12576                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12577                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12578                "  { \"ccccccccccccccccccccc\", 2 }\n"
12579                "};",
12580                ExtraSpaces);
12581   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
12582                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
12583                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
12584                "  { \"ccccccccccccccccccccc\", 2 }\n"
12585                "};",
12586                ExtraSpaces);
12587 
12588   FormatStyle SpaceBeforeBrace = getLLVMStyle();
12589   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
12590   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
12591   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
12592 
12593   FormatStyle SpaceBetweenBraces = getLLVMStyle();
12594   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
12595   SpaceBetweenBraces.SpacesInParentheses = true;
12596   SpaceBetweenBraces.SpacesInSquareBrackets = true;
12597   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
12598   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
12599   verifyFormat("vector< int > x{ // comment 1\n"
12600                "                 1, 2, 3, 4 };",
12601                SpaceBetweenBraces);
12602   SpaceBetweenBraces.ColumnLimit = 20;
12603   EXPECT_EQ("vector< int > x{\n"
12604             "    1, 2, 3, 4 };",
12605             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12606   SpaceBetweenBraces.ColumnLimit = 24;
12607   EXPECT_EQ("vector< int > x{ 1, 2,\n"
12608             "                 3, 4 };",
12609             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
12610   EXPECT_EQ("vector< int > x{\n"
12611             "    1,\n"
12612             "    2,\n"
12613             "    3,\n"
12614             "    4,\n"
12615             "};",
12616             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
12617   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
12618   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
12619   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
12620 }
12621 
TEST_F(FormatTest,FormatsBracedListsInColumnLayout)12622 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
12623   verifyFormat("vector<int> x = {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,\n"
12628                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12629   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
12630                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12631                "                 1, 22, 333, 4444, 55555, //\n"
12632                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
12633                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
12634   verifyFormat(
12635       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12636       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
12637       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
12638       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12639       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12640       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
12641       "                 7777777};");
12642   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12643                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12644                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12645   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12646                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12647                "    // Separating comment.\n"
12648                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
12649   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
12650                "    // Leading comment\n"
12651                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
12652                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
12653   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12654                "                 1, 1, 1, 1};",
12655                getLLVMStyleWithColumns(39));
12656   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12657                "                 1, 1, 1, 1};",
12658                getLLVMStyleWithColumns(38));
12659   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
12660                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
12661                getLLVMStyleWithColumns(43));
12662   verifyFormat(
12663       "static unsigned SomeValues[10][3] = {\n"
12664       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
12665       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
12666   verifyFormat("static auto fields = new vector<string>{\n"
12667                "    \"aaaaaaaaaaaaa\",\n"
12668                "    \"aaaaaaaaaaaaa\",\n"
12669                "    \"aaaaaaaaaaaa\",\n"
12670                "    \"aaaaaaaaaaaaaa\",\n"
12671                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12672                "    \"aaaaaaaaaaaa\",\n"
12673                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
12674                "};");
12675   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
12676   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
12677                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
12678                "                 3, cccccccccccccccccccccc};",
12679                getLLVMStyleWithColumns(60));
12680 
12681   // Trailing commas.
12682   verifyFormat("vector<int> x = {\n"
12683                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
12684                "};",
12685                getLLVMStyleWithColumns(39));
12686   verifyFormat("vector<int> x = {\n"
12687                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
12688                "};",
12689                getLLVMStyleWithColumns(39));
12690   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
12691                "                 1, 1, 1, 1,\n"
12692                "                 /**/ /**/};",
12693                getLLVMStyleWithColumns(39));
12694 
12695   // Trailing comment in the first line.
12696   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
12697                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
12698                "    111111111,  222222222,  3333333333,  444444444,  //\n"
12699                "    11111111,   22222222,   333333333,   44444444};");
12700   // Trailing comment in the last line.
12701   verifyFormat("int aaaaa[] = {\n"
12702                "    1, 2, 3, // comment\n"
12703                "    4, 5, 6  // comment\n"
12704                "};");
12705 
12706   // With nested lists, we should either format one item per line or all nested
12707   // lists one on line.
12708   // FIXME: For some nested lists, we can do better.
12709   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
12710                "        {aaaaaaaaaaaaaaaaaaa},\n"
12711                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
12712                "        {aaaaaaaaaaaaaaaaa}};",
12713                getLLVMStyleWithColumns(60));
12714   verifyFormat(
12715       "SomeStruct my_struct_array = {\n"
12716       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
12717       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
12718       "    {aaa, aaa},\n"
12719       "    {aaa, aaa},\n"
12720       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
12721       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
12722       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
12723 
12724   // No column layout should be used here.
12725   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
12726                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
12727 
12728   verifyNoCrash("a<,");
12729 
12730   // No braced initializer here.
12731   verifyFormat("void f() {\n"
12732                "  struct Dummy {};\n"
12733                "  f(v);\n"
12734                "}");
12735 
12736   // Long lists should be formatted in columns even if they are nested.
12737   verifyFormat(
12738       "vector<int> x = function({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,\n"
12743       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
12744 
12745   // Allow "single-column" layout even if that violates the column limit. There
12746   // isn't going to be a better way.
12747   verifyFormat("std::vector<int> a = {\n"
12748                "    aaaaaaaa,\n"
12749                "    aaaaaaaa,\n"
12750                "    aaaaaaaa,\n"
12751                "    aaaaaaaa,\n"
12752                "    aaaaaaaaaa,\n"
12753                "    aaaaaaaa,\n"
12754                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
12755                getLLVMStyleWithColumns(30));
12756   verifyFormat("vector<int> aaaa = {\n"
12757                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12758                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
12759                "    aaaaaa.aaaaaaa,\n"
12760                "    aaaaaa.aaaaaaa,\n"
12761                "    aaaaaa.aaaaaaa,\n"
12762                "    aaaaaa.aaaaaaa,\n"
12763                "};");
12764 
12765   // Don't create hanging lists.
12766   verifyFormat("someFunction(Param, {List1, List2,\n"
12767                "                     List3});",
12768                getLLVMStyleWithColumns(35));
12769   verifyFormat("someFunction(Param, Param,\n"
12770                "             {List1, List2,\n"
12771                "              List3});",
12772                getLLVMStyleWithColumns(35));
12773   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
12774                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
12775 }
12776 
TEST_F(FormatTest,PullTrivialFunctionDefinitionsIntoSingleLine)12777 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
12778   FormatStyle DoNotMerge = getLLVMStyle();
12779   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
12780 
12781   verifyFormat("void f() { return 42; }");
12782   verifyFormat("void f() {\n"
12783                "  return 42;\n"
12784                "}",
12785                DoNotMerge);
12786   verifyFormat("void f() {\n"
12787                "  // Comment\n"
12788                "}");
12789   verifyFormat("{\n"
12790                "#error {\n"
12791                "  int a;\n"
12792                "}");
12793   verifyFormat("{\n"
12794                "  int a;\n"
12795                "#error {\n"
12796                "}");
12797   verifyFormat("void f() {} // comment");
12798   verifyFormat("void f() { int a; } // comment");
12799   verifyFormat("void f() {\n"
12800                "} // comment",
12801                DoNotMerge);
12802   verifyFormat("void f() {\n"
12803                "  int a;\n"
12804                "} // comment",
12805                DoNotMerge);
12806   verifyFormat("void f() {\n"
12807                "} // comment",
12808                getLLVMStyleWithColumns(15));
12809 
12810   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
12811   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
12812 
12813   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
12814   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
12815   verifyFormat("class C {\n"
12816                "  C()\n"
12817                "      : iiiiiiii(nullptr),\n"
12818                "        kkkkkkk(nullptr),\n"
12819                "        mmmmmmm(nullptr),\n"
12820                "        nnnnnnn(nullptr) {}\n"
12821                "};",
12822                getGoogleStyle());
12823 
12824   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
12825   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
12826   EXPECT_EQ("class C {\n"
12827             "  A() : b(0) {}\n"
12828             "};",
12829             format("class C{A():b(0){}};", NoColumnLimit));
12830   EXPECT_EQ("A()\n"
12831             "    : b(0) {\n"
12832             "}",
12833             format("A()\n:b(0)\n{\n}", NoColumnLimit));
12834 
12835   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
12836   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
12837       FormatStyle::SFS_None;
12838   EXPECT_EQ("A()\n"
12839             "    : b(0) {\n"
12840             "}",
12841             format("A():b(0){}", DoNotMergeNoColumnLimit));
12842   EXPECT_EQ("A()\n"
12843             "    : b(0) {\n"
12844             "}",
12845             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
12846 
12847   verifyFormat("#define A          \\\n"
12848                "  void f() {       \\\n"
12849                "    int i;         \\\n"
12850                "  }",
12851                getLLVMStyleWithColumns(20));
12852   verifyFormat("#define A           \\\n"
12853                "  void f() { int i; }",
12854                getLLVMStyleWithColumns(21));
12855   verifyFormat("#define A            \\\n"
12856                "  void f() {         \\\n"
12857                "    int i;           \\\n"
12858                "  }                  \\\n"
12859                "  int j;",
12860                getLLVMStyleWithColumns(22));
12861   verifyFormat("#define A             \\\n"
12862                "  void f() { int i; } \\\n"
12863                "  int j;",
12864                getLLVMStyleWithColumns(23));
12865 }
12866 
TEST_F(FormatTest,PullEmptyFunctionDefinitionsIntoSingleLine)12867 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
12868   FormatStyle MergeEmptyOnly = getLLVMStyle();
12869   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
12870   verifyFormat("class C {\n"
12871                "  int f() {}\n"
12872                "};",
12873                MergeEmptyOnly);
12874   verifyFormat("class C {\n"
12875                "  int f() {\n"
12876                "    return 42;\n"
12877                "  }\n"
12878                "};",
12879                MergeEmptyOnly);
12880   verifyFormat("int f() {}", MergeEmptyOnly);
12881   verifyFormat("int f() {\n"
12882                "  return 42;\n"
12883                "}",
12884                MergeEmptyOnly);
12885 
12886   // Also verify behavior when BraceWrapping.AfterFunction = true
12887   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12888   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
12889   verifyFormat("int f() {}", MergeEmptyOnly);
12890   verifyFormat("class C {\n"
12891                "  int f() {}\n"
12892                "};",
12893                MergeEmptyOnly);
12894 }
12895 
TEST_F(FormatTest,PullInlineFunctionDefinitionsIntoSingleLine)12896 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
12897   FormatStyle MergeInlineOnly = getLLVMStyle();
12898   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12899   verifyFormat("class C {\n"
12900                "  int f() { return 42; }\n"
12901                "};",
12902                MergeInlineOnly);
12903   verifyFormat("int f() {\n"
12904                "  return 42;\n"
12905                "}",
12906                MergeInlineOnly);
12907 
12908   // SFS_Inline implies SFS_Empty
12909   verifyFormat("class C {\n"
12910                "  int f() {}\n"
12911                "};",
12912                MergeInlineOnly);
12913   verifyFormat("int f() {}", MergeInlineOnly);
12914   // https://llvm.org/PR54147
12915   verifyFormat("auto lambda = []() {\n"
12916                "  // comment\n"
12917                "  f();\n"
12918                "  g();\n"
12919                "};",
12920                MergeInlineOnly);
12921 
12922   verifyFormat("class C {\n"
12923                "#ifdef A\n"
12924                "  int f() { return 42; }\n"
12925                "#endif\n"
12926                "};",
12927                MergeInlineOnly);
12928 
12929   verifyFormat("struct S {\n"
12930                "// comment\n"
12931                "#ifdef FOO\n"
12932                "  int foo() { bar(); }\n"
12933                "#endif\n"
12934                "};",
12935                MergeInlineOnly);
12936 
12937   // Also verify behavior when BraceWrapping.AfterFunction = true
12938   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
12939   MergeInlineOnly.BraceWrapping.AfterFunction = true;
12940   verifyFormat("class C {\n"
12941                "  int f() { return 42; }\n"
12942                "};",
12943                MergeInlineOnly);
12944   verifyFormat("int f()\n"
12945                "{\n"
12946                "  return 42;\n"
12947                "}",
12948                MergeInlineOnly);
12949 
12950   // SFS_Inline implies SFS_Empty
12951   verifyFormat("int f() {}", MergeInlineOnly);
12952   verifyFormat("class C {\n"
12953                "  int f() {}\n"
12954                "};",
12955                MergeInlineOnly);
12956 
12957   MergeInlineOnly.BraceWrapping.AfterClass = true;
12958   MergeInlineOnly.BraceWrapping.AfterStruct = true;
12959   verifyFormat("class C\n"
12960                "{\n"
12961                "  int f() { return 42; }\n"
12962                "};",
12963                MergeInlineOnly);
12964   verifyFormat("struct C\n"
12965                "{\n"
12966                "  int f() { return 42; }\n"
12967                "};",
12968                MergeInlineOnly);
12969   verifyFormat("int f()\n"
12970                "{\n"
12971                "  return 42;\n"
12972                "}",
12973                MergeInlineOnly);
12974   verifyFormat("int f() {}", MergeInlineOnly);
12975   verifyFormat("class C\n"
12976                "{\n"
12977                "  int f() { return 42; }\n"
12978                "};",
12979                MergeInlineOnly);
12980   verifyFormat("struct C\n"
12981                "{\n"
12982                "  int f() { return 42; }\n"
12983                "};",
12984                MergeInlineOnly);
12985   verifyFormat("struct C\n"
12986                "// comment\n"
12987                "/* comment */\n"
12988                "// comment\n"
12989                "{\n"
12990                "  int f() { return 42; }\n"
12991                "};",
12992                MergeInlineOnly);
12993   verifyFormat("/* comment */ struct C\n"
12994                "{\n"
12995                "  int f() { return 42; }\n"
12996                "};",
12997                MergeInlineOnly);
12998 }
12999 
TEST_F(FormatTest,PullInlineOnlyFunctionDefinitionsIntoSingleLine)13000 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
13001   FormatStyle MergeInlineOnly = getLLVMStyle();
13002   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
13003       FormatStyle::SFS_InlineOnly;
13004   verifyFormat("class C {\n"
13005                "  int f() { return 42; }\n"
13006                "};",
13007                MergeInlineOnly);
13008   verifyFormat("int f() {\n"
13009                "  return 42;\n"
13010                "}",
13011                MergeInlineOnly);
13012 
13013   // SFS_InlineOnly does not imply SFS_Empty
13014   verifyFormat("class C {\n"
13015                "  int f() {}\n"
13016                "};",
13017                MergeInlineOnly);
13018   verifyFormat("int f() {\n"
13019                "}",
13020                MergeInlineOnly);
13021 
13022   // Also verify behavior when BraceWrapping.AfterFunction = true
13023   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
13024   MergeInlineOnly.BraceWrapping.AfterFunction = true;
13025   verifyFormat("class C {\n"
13026                "  int f() { return 42; }\n"
13027                "};",
13028                MergeInlineOnly);
13029   verifyFormat("int f()\n"
13030                "{\n"
13031                "  return 42;\n"
13032                "}",
13033                MergeInlineOnly);
13034 
13035   // SFS_InlineOnly does not imply SFS_Empty
13036   verifyFormat("int f()\n"
13037                "{\n"
13038                "}",
13039                MergeInlineOnly);
13040   verifyFormat("class C {\n"
13041                "  int f() {}\n"
13042                "};",
13043                MergeInlineOnly);
13044 }
13045 
TEST_F(FormatTest,SplitEmptyFunction)13046 TEST_F(FormatTest, SplitEmptyFunction) {
13047   FormatStyle Style = getLLVMStyleWithColumns(40);
13048   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
13049   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13050   Style.BraceWrapping.AfterFunction = true;
13051   Style.BraceWrapping.SplitEmptyFunction = false;
13052 
13053   verifyFormat("int f()\n"
13054                "{}",
13055                Style);
13056   verifyFormat("int f()\n"
13057                "{\n"
13058                "  return 42;\n"
13059                "}",
13060                Style);
13061   verifyFormat("int f()\n"
13062                "{\n"
13063                "  // some comment\n"
13064                "}",
13065                Style);
13066 
13067   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
13068   verifyFormat("int f() {}", Style);
13069   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13070                "{}",
13071                Style);
13072   verifyFormat("int f()\n"
13073                "{\n"
13074                "  return 0;\n"
13075                "}",
13076                Style);
13077 
13078   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
13079   verifyFormat("class Foo {\n"
13080                "  int f() {}\n"
13081                "};\n",
13082                Style);
13083   verifyFormat("class Foo {\n"
13084                "  int f() { return 0; }\n"
13085                "};\n",
13086                Style);
13087   verifyFormat("class Foo {\n"
13088                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13089                "  {}\n"
13090                "};\n",
13091                Style);
13092   verifyFormat("class Foo {\n"
13093                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13094                "  {\n"
13095                "    return 0;\n"
13096                "  }\n"
13097                "};\n",
13098                Style);
13099 
13100   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
13101   verifyFormat("int f() {}", Style);
13102   verifyFormat("int f() { return 0; }", Style);
13103   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13104                "{}",
13105                Style);
13106   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
13107                "{\n"
13108                "  return 0;\n"
13109                "}",
13110                Style);
13111 }
13112 
TEST_F(FormatTest,SplitEmptyFunctionButNotRecord)13113 TEST_F(FormatTest, SplitEmptyFunctionButNotRecord) {
13114   FormatStyle Style = getLLVMStyleWithColumns(40);
13115   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
13116   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13117   Style.BraceWrapping.AfterFunction = true;
13118   Style.BraceWrapping.SplitEmptyFunction = true;
13119   Style.BraceWrapping.SplitEmptyRecord = false;
13120 
13121   verifyFormat("class C {};", Style);
13122   verifyFormat("struct C {};", Style);
13123   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
13124                "       int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
13125                "{\n"
13126                "}",
13127                Style);
13128   verifyFormat("class C {\n"
13129                "  C()\n"
13130                "      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa(),\n"
13131                "        bbbbbbbbbbbbbbbbbbb()\n"
13132                "  {\n"
13133                "  }\n"
13134                "  void\n"
13135                "  m(int aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
13136                "    int bbbbbbbbbbbbbbbbbbbbbbbb)\n"
13137                "  {\n"
13138                "  }\n"
13139                "};",
13140                Style);
13141 }
13142 
TEST_F(FormatTest,KeepShortFunctionAfterPPElse)13143 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
13144   FormatStyle Style = getLLVMStyle();
13145   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
13146   verifyFormat("#ifdef A\n"
13147                "int f() {}\n"
13148                "#else\n"
13149                "int g() {}\n"
13150                "#endif",
13151                Style);
13152 }
13153 
TEST_F(FormatTest,SplitEmptyClass)13154 TEST_F(FormatTest, SplitEmptyClass) {
13155   FormatStyle Style = getLLVMStyle();
13156   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13157   Style.BraceWrapping.AfterClass = true;
13158   Style.BraceWrapping.SplitEmptyRecord = false;
13159 
13160   verifyFormat("class Foo\n"
13161                "{};",
13162                Style);
13163   verifyFormat("/* something */ class Foo\n"
13164                "{};",
13165                Style);
13166   verifyFormat("template <typename X> class Foo\n"
13167                "{};",
13168                Style);
13169   verifyFormat("class Foo\n"
13170                "{\n"
13171                "  Foo();\n"
13172                "};",
13173                Style);
13174   verifyFormat("typedef class Foo\n"
13175                "{\n"
13176                "} Foo_t;",
13177                Style);
13178 
13179   Style.BraceWrapping.SplitEmptyRecord = true;
13180   Style.BraceWrapping.AfterStruct = true;
13181   verifyFormat("class rep\n"
13182                "{\n"
13183                "};",
13184                Style);
13185   verifyFormat("struct rep\n"
13186                "{\n"
13187                "};",
13188                Style);
13189   verifyFormat("template <typename T> class rep\n"
13190                "{\n"
13191                "};",
13192                Style);
13193   verifyFormat("template <typename T> struct rep\n"
13194                "{\n"
13195                "};",
13196                Style);
13197   verifyFormat("class rep\n"
13198                "{\n"
13199                "  int x;\n"
13200                "};",
13201                Style);
13202   verifyFormat("struct rep\n"
13203                "{\n"
13204                "  int x;\n"
13205                "};",
13206                Style);
13207   verifyFormat("template <typename T> class rep\n"
13208                "{\n"
13209                "  int x;\n"
13210                "};",
13211                Style);
13212   verifyFormat("template <typename T> struct rep\n"
13213                "{\n"
13214                "  int x;\n"
13215                "};",
13216                Style);
13217   verifyFormat("template <typename T> class rep // Foo\n"
13218                "{\n"
13219                "  int x;\n"
13220                "};",
13221                Style);
13222   verifyFormat("template <typename T> struct rep // Bar\n"
13223                "{\n"
13224                "  int x;\n"
13225                "};",
13226                Style);
13227 
13228   verifyFormat("template <typename T> class rep<T>\n"
13229                "{\n"
13230                "  int x;\n"
13231                "};",
13232                Style);
13233 
13234   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13235                "{\n"
13236                "  int x;\n"
13237                "};",
13238                Style);
13239   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
13240                "{\n"
13241                "};",
13242                Style);
13243 
13244   verifyFormat("#include \"stdint.h\"\n"
13245                "namespace rep {}",
13246                Style);
13247   verifyFormat("#include <stdint.h>\n"
13248                "namespace rep {}",
13249                Style);
13250   verifyFormat("#include <stdint.h>\n"
13251                "namespace rep {}",
13252                "#include <stdint.h>\n"
13253                "namespace rep {\n"
13254                "\n"
13255                "\n"
13256                "}",
13257                Style);
13258 }
13259 
TEST_F(FormatTest,SplitEmptyStruct)13260 TEST_F(FormatTest, SplitEmptyStruct) {
13261   FormatStyle Style = getLLVMStyle();
13262   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13263   Style.BraceWrapping.AfterStruct = true;
13264   Style.BraceWrapping.SplitEmptyRecord = false;
13265 
13266   verifyFormat("struct Foo\n"
13267                "{};",
13268                Style);
13269   verifyFormat("/* something */ struct Foo\n"
13270                "{};",
13271                Style);
13272   verifyFormat("template <typename X> struct Foo\n"
13273                "{};",
13274                Style);
13275   verifyFormat("struct Foo\n"
13276                "{\n"
13277                "  Foo();\n"
13278                "};",
13279                Style);
13280   verifyFormat("typedef struct Foo\n"
13281                "{\n"
13282                "} Foo_t;",
13283                Style);
13284   // typedef struct Bar {} Bar_t;
13285 }
13286 
TEST_F(FormatTest,SplitEmptyUnion)13287 TEST_F(FormatTest, SplitEmptyUnion) {
13288   FormatStyle Style = getLLVMStyle();
13289   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13290   Style.BraceWrapping.AfterUnion = true;
13291   Style.BraceWrapping.SplitEmptyRecord = false;
13292 
13293   verifyFormat("union Foo\n"
13294                "{};",
13295                Style);
13296   verifyFormat("/* something */ union Foo\n"
13297                "{};",
13298                Style);
13299   verifyFormat("union Foo\n"
13300                "{\n"
13301                "  A,\n"
13302                "};",
13303                Style);
13304   verifyFormat("typedef union Foo\n"
13305                "{\n"
13306                "} Foo_t;",
13307                Style);
13308 }
13309 
TEST_F(FormatTest,SplitEmptyNamespace)13310 TEST_F(FormatTest, SplitEmptyNamespace) {
13311   FormatStyle Style = getLLVMStyle();
13312   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13313   Style.BraceWrapping.AfterNamespace = true;
13314   Style.BraceWrapping.SplitEmptyNamespace = false;
13315 
13316   verifyFormat("namespace Foo\n"
13317                "{};",
13318                Style);
13319   verifyFormat("/* something */ namespace Foo\n"
13320                "{};",
13321                Style);
13322   verifyFormat("inline namespace Foo\n"
13323                "{};",
13324                Style);
13325   verifyFormat("/* something */ inline namespace Foo\n"
13326                "{};",
13327                Style);
13328   verifyFormat("export namespace Foo\n"
13329                "{};",
13330                Style);
13331   verifyFormat("namespace Foo\n"
13332                "{\n"
13333                "void Bar();\n"
13334                "};",
13335                Style);
13336 }
13337 
TEST_F(FormatTest,NeverMergeShortRecords)13338 TEST_F(FormatTest, NeverMergeShortRecords) {
13339   FormatStyle Style = getLLVMStyle();
13340 
13341   verifyFormat("class Foo {\n"
13342                "  Foo();\n"
13343                "};",
13344                Style);
13345   verifyFormat("typedef class Foo {\n"
13346                "  Foo();\n"
13347                "} Foo_t;",
13348                Style);
13349   verifyFormat("struct Foo {\n"
13350                "  Foo();\n"
13351                "};",
13352                Style);
13353   verifyFormat("typedef struct Foo {\n"
13354                "  Foo();\n"
13355                "} Foo_t;",
13356                Style);
13357   verifyFormat("union Foo {\n"
13358                "  A,\n"
13359                "};",
13360                Style);
13361   verifyFormat("typedef union Foo {\n"
13362                "  A,\n"
13363                "} Foo_t;",
13364                Style);
13365   verifyFormat("namespace Foo {\n"
13366                "void Bar();\n"
13367                "};",
13368                Style);
13369 
13370   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
13371   Style.BraceWrapping.AfterClass = true;
13372   Style.BraceWrapping.AfterStruct = true;
13373   Style.BraceWrapping.AfterUnion = true;
13374   Style.BraceWrapping.AfterNamespace = true;
13375   verifyFormat("class Foo\n"
13376                "{\n"
13377                "  Foo();\n"
13378                "};",
13379                Style);
13380   verifyFormat("typedef class Foo\n"
13381                "{\n"
13382                "  Foo();\n"
13383                "} Foo_t;",
13384                Style);
13385   verifyFormat("struct Foo\n"
13386                "{\n"
13387                "  Foo();\n"
13388                "};",
13389                Style);
13390   verifyFormat("typedef struct Foo\n"
13391                "{\n"
13392                "  Foo();\n"
13393                "} Foo_t;",
13394                Style);
13395   verifyFormat("union Foo\n"
13396                "{\n"
13397                "  A,\n"
13398                "};",
13399                Style);
13400   verifyFormat("typedef union Foo\n"
13401                "{\n"
13402                "  A,\n"
13403                "} Foo_t;",
13404                Style);
13405   verifyFormat("namespace Foo\n"
13406                "{\n"
13407                "void Bar();\n"
13408                "};",
13409                Style);
13410 }
13411 
TEST_F(FormatTest,UnderstandContextOfRecordTypeKeywords)13412 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
13413   // Elaborate type variable declarations.
13414   verifyFormat("struct foo a = {bar};\nint n;");
13415   verifyFormat("class foo a = {bar};\nint n;");
13416   verifyFormat("union foo a = {bar};\nint n;");
13417 
13418   // Elaborate types inside function definitions.
13419   verifyFormat("struct foo f() {}\nint n;");
13420   verifyFormat("class foo f() {}\nint n;");
13421   verifyFormat("union foo f() {}\nint n;");
13422 
13423   // Templates.
13424   verifyFormat("template <class X> void f() {}\nint n;");
13425   verifyFormat("template <struct X> void f() {}\nint n;");
13426   verifyFormat("template <union X> void f() {}\nint n;");
13427 
13428   // Actual definitions...
13429   verifyFormat("struct {\n} n;");
13430   verifyFormat(
13431       "template <template <class T, class Y>, class Z> class X {\n} n;");
13432   verifyFormat("union Z {\n  int n;\n} x;");
13433   verifyFormat("class MACRO Z {\n} n;");
13434   verifyFormat("class MACRO(X) Z {\n} n;");
13435   verifyFormat("class __attribute__(X) Z {\n} n;");
13436   verifyFormat("class __declspec(X) Z {\n} n;");
13437   verifyFormat("class A##B##C {\n} n;");
13438   verifyFormat("class alignas(16) Z {\n} n;");
13439   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
13440   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
13441 
13442   // Redefinition from nested context:
13443   verifyFormat("class A::B::C {\n} n;");
13444 
13445   // Template definitions.
13446   verifyFormat(
13447       "template <typename F>\n"
13448       "Matcher(const Matcher<F> &Other,\n"
13449       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
13450       "                             !is_same<F, T>::value>::type * = 0)\n"
13451       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
13452 
13453   // FIXME: This is still incorrectly handled at the formatter side.
13454   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
13455   verifyFormat("int i = SomeFunction(a<b, a> b);");
13456 
13457   // FIXME:
13458   // This now gets parsed incorrectly as class definition.
13459   // verifyFormat("class A<int> f() {\n}\nint n;");
13460 
13461   // Elaborate types where incorrectly parsing the structural element would
13462   // break the indent.
13463   verifyFormat("if (true)\n"
13464                "  class X x;\n"
13465                "else\n"
13466                "  f();\n");
13467 
13468   // This is simply incomplete. Formatting is not important, but must not crash.
13469   verifyFormat("class A:");
13470 }
13471 
TEST_F(FormatTest,DoNotInterfereWithErrorAndWarning)13472 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
13473   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
13474             format("#error Leave     all         white!!!!! space* alone!\n"));
13475   EXPECT_EQ(
13476       "#warning Leave     all         white!!!!! space* alone!\n",
13477       format("#warning Leave     all         white!!!!! space* alone!\n"));
13478   EXPECT_EQ("#error 1", format("  #  error   1"));
13479   EXPECT_EQ("#warning 1", format("  #  warning 1"));
13480 }
13481 
TEST_F(FormatTest,FormatHashIfExpressions)13482 TEST_F(FormatTest, FormatHashIfExpressions) {
13483   verifyFormat("#if AAAA && BBBB");
13484   verifyFormat("#if (AAAA && BBBB)");
13485   verifyFormat("#elif (AAAA && BBBB)");
13486   // FIXME: Come up with a better indentation for #elif.
13487   verifyFormat(
13488       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
13489       "    defined(BBBBBBBB)\n"
13490       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
13491       "    defined(BBBBBBBB)\n"
13492       "#endif",
13493       getLLVMStyleWithColumns(65));
13494 }
13495 
TEST_F(FormatTest,MergeHandlingInTheFaceOfPreprocessorDirectives)13496 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
13497   FormatStyle AllowsMergedIf = getGoogleStyle();
13498   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
13499       FormatStyle::SIS_WithoutElse;
13500   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
13501   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
13502   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
13503   EXPECT_EQ("if (true) return 42;",
13504             format("if (true)\nreturn 42;", AllowsMergedIf));
13505   FormatStyle ShortMergedIf = AllowsMergedIf;
13506   ShortMergedIf.ColumnLimit = 25;
13507   verifyFormat("#define A \\\n"
13508                "  if (true) return 42;",
13509                ShortMergedIf);
13510   verifyFormat("#define A \\\n"
13511                "  f();    \\\n"
13512                "  if (true)\n"
13513                "#define B",
13514                ShortMergedIf);
13515   verifyFormat("#define A \\\n"
13516                "  f();    \\\n"
13517                "  if (true)\n"
13518                "g();",
13519                ShortMergedIf);
13520   verifyFormat("{\n"
13521                "#ifdef A\n"
13522                "  // Comment\n"
13523                "  if (true) continue;\n"
13524                "#endif\n"
13525                "  // Comment\n"
13526                "  if (true) continue;\n"
13527                "}",
13528                ShortMergedIf);
13529   ShortMergedIf.ColumnLimit = 33;
13530   verifyFormat("#define A \\\n"
13531                "  if constexpr (true) return 42;",
13532                ShortMergedIf);
13533   verifyFormat("#define A \\\n"
13534                "  if CONSTEXPR (true) return 42;",
13535                ShortMergedIf);
13536   ShortMergedIf.ColumnLimit = 29;
13537   verifyFormat("#define A                   \\\n"
13538                "  if (aaaaaaaaaa) return 1; \\\n"
13539                "  return 2;",
13540                ShortMergedIf);
13541   ShortMergedIf.ColumnLimit = 28;
13542   verifyFormat("#define A         \\\n"
13543                "  if (aaaaaaaaaa) \\\n"
13544                "    return 1;     \\\n"
13545                "  return 2;",
13546                ShortMergedIf);
13547   verifyFormat("#define A                \\\n"
13548                "  if constexpr (aaaaaaa) \\\n"
13549                "    return 1;            \\\n"
13550                "  return 2;",
13551                ShortMergedIf);
13552   verifyFormat("#define A                \\\n"
13553                "  if CONSTEXPR (aaaaaaa) \\\n"
13554                "    return 1;            \\\n"
13555                "  return 2;",
13556                ShortMergedIf);
13557 
13558   verifyFormat("//\n"
13559                "#define a \\\n"
13560                "  if      \\\n"
13561                "  0",
13562                getChromiumStyle(FormatStyle::LK_Cpp));
13563 }
13564 
TEST_F(FormatTest,FormatStarDependingOnContext)13565 TEST_F(FormatTest, FormatStarDependingOnContext) {
13566   verifyFormat("void f(int *a);");
13567   verifyFormat("void f() { f(fint * b); }");
13568   verifyFormat("class A {\n  void f(int *a);\n};");
13569   verifyFormat("class A {\n  int *a;\n};");
13570   verifyFormat("namespace a {\n"
13571                "namespace b {\n"
13572                "class A {\n"
13573                "  void f() {}\n"
13574                "  int *a;\n"
13575                "};\n"
13576                "} // namespace b\n"
13577                "} // namespace a");
13578 }
13579 
TEST_F(FormatTest,SpecialTokensAtEndOfLine)13580 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
13581   verifyFormat("while");
13582   verifyFormat("operator");
13583 }
13584 
TEST_F(FormatTest,SkipsDeeplyNestedLines)13585 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
13586   // This code would be painfully slow to format if we didn't skip it.
13587   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
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(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
13592                    "A(1, 1)\n"
13593                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
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                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
13603   // Deeply nested part is untouched, rest is formatted.
13604   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
13605             format(std::string("int    i;\n") + Code + "int    j;\n",
13606                    getLLVMStyle(), SC_ExpectIncomplete));
13607 }
13608 
13609 //===----------------------------------------------------------------------===//
13610 // Objective-C tests.
13611 //===----------------------------------------------------------------------===//
13612 
TEST_F(FormatTest,FormatForObjectiveCMethodDecls)13613 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
13614   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
13615   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
13616             format("-(NSUInteger)indexOfObject:(id)anObject;"));
13617   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
13618   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
13619   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
13620             format("-(NSInteger)Method3:(id)anObject;"));
13621   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
13622             format("-(NSInteger)Method4:(id)anObject;"));
13623   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
13624             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
13625   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
13626             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
13627   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13628             "forAllCells:(BOOL)flag;",
13629             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
13630                    "forAllCells:(BOOL)flag;"));
13631 
13632   // Very long objectiveC method declaration.
13633   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
13634                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
13635   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
13636                "                    inRange:(NSRange)range\n"
13637                "                   outRange:(NSRange)out_range\n"
13638                "                  outRange1:(NSRange)out_range1\n"
13639                "                  outRange2:(NSRange)out_range2\n"
13640                "                  outRange3:(NSRange)out_range3\n"
13641                "                  outRange4:(NSRange)out_range4\n"
13642                "                  outRange5:(NSRange)out_range5\n"
13643                "                  outRange6:(NSRange)out_range6\n"
13644                "                  outRange7:(NSRange)out_range7\n"
13645                "                  outRange8:(NSRange)out_range8\n"
13646                "                  outRange9:(NSRange)out_range9;");
13647 
13648   // When the function name has to be wrapped.
13649   FormatStyle Style = getLLVMStyle();
13650   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
13651   // and always indents instead.
13652   Style.IndentWrappedFunctionNames = false;
13653   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13654                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
13655                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
13656                "}",
13657                Style);
13658   Style.IndentWrappedFunctionNames = true;
13659   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
13660                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
13661                "               anotherName:(NSString)dddddddddddddd {\n"
13662                "}",
13663                Style);
13664 
13665   verifyFormat("- (int)sum:(vector<int>)numbers;");
13666   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
13667   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
13668   // protocol lists (but not for template classes):
13669   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
13670 
13671   verifyFormat("- (int (*)())foo:(int (*)())f;");
13672   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
13673 
13674   // If there's no return type (very rare in practice!), LLVM and Google style
13675   // agree.
13676   verifyFormat("- foo;");
13677   verifyFormat("- foo:(int)f;");
13678   verifyGoogleFormat("- foo:(int)foo;");
13679 }
13680 
TEST_F(FormatTest,BreaksStringLiterals)13681 TEST_F(FormatTest, BreaksStringLiterals) {
13682   EXPECT_EQ("\"some text \"\n"
13683             "\"other\";",
13684             format("\"some text other\";", getLLVMStyleWithColumns(12)));
13685   EXPECT_EQ("\"some text \"\n"
13686             "\"other\";",
13687             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
13688   EXPECT_EQ(
13689       "#define A  \\\n"
13690       "  \"some \"  \\\n"
13691       "  \"text \"  \\\n"
13692       "  \"other\";",
13693       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
13694   EXPECT_EQ(
13695       "#define A  \\\n"
13696       "  \"so \"    \\\n"
13697       "  \"text \"  \\\n"
13698       "  \"other\";",
13699       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
13700 
13701   EXPECT_EQ("\"some text\"",
13702             format("\"some text\"", getLLVMStyleWithColumns(1)));
13703   EXPECT_EQ("\"some text\"",
13704             format("\"some text\"", getLLVMStyleWithColumns(11)));
13705   EXPECT_EQ("\"some \"\n"
13706             "\"text\"",
13707             format("\"some text\"", getLLVMStyleWithColumns(10)));
13708   EXPECT_EQ("\"some \"\n"
13709             "\"text\"",
13710             format("\"some text\"", getLLVMStyleWithColumns(7)));
13711   EXPECT_EQ("\"some\"\n"
13712             "\" tex\"\n"
13713             "\"t\"",
13714             format("\"some text\"", getLLVMStyleWithColumns(6)));
13715   EXPECT_EQ("\"some\"\n"
13716             "\" tex\"\n"
13717             "\" and\"",
13718             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
13719   EXPECT_EQ("\"some\"\n"
13720             "\"/tex\"\n"
13721             "\"/and\"",
13722             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
13723 
13724   EXPECT_EQ("variable =\n"
13725             "    \"long string \"\n"
13726             "    \"literal\";",
13727             format("variable = \"long string literal\";",
13728                    getLLVMStyleWithColumns(20)));
13729 
13730   EXPECT_EQ("variable = f(\n"
13731             "    \"long string \"\n"
13732             "    \"literal\",\n"
13733             "    short,\n"
13734             "    loooooooooooooooooooong);",
13735             format("variable = f(\"long string literal\", short, "
13736                    "loooooooooooooooooooong);",
13737                    getLLVMStyleWithColumns(20)));
13738 
13739   EXPECT_EQ(
13740       "f(g(\"long string \"\n"
13741       "    \"literal\"),\n"
13742       "  b);",
13743       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
13744   EXPECT_EQ("f(g(\"long string \"\n"
13745             "    \"literal\",\n"
13746             "    a),\n"
13747             "  b);",
13748             format("f(g(\"long string literal\", a), b);",
13749                    getLLVMStyleWithColumns(20)));
13750   EXPECT_EQ(
13751       "f(\"one two\".split(\n"
13752       "    variable));",
13753       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
13754   EXPECT_EQ("f(\"one two three four five six \"\n"
13755             "  \"seven\".split(\n"
13756             "      really_looooong_variable));",
13757             format("f(\"one two three four five six seven\"."
13758                    "split(really_looooong_variable));",
13759                    getLLVMStyleWithColumns(33)));
13760 
13761   EXPECT_EQ("f(\"some \"\n"
13762             "  \"text\",\n"
13763             "  other);",
13764             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
13765 
13766   // Only break as a last resort.
13767   verifyFormat(
13768       "aaaaaaaaaaaaaaaaaaaa(\n"
13769       "    aaaaaaaaaaaaaaaaaaaa,\n"
13770       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
13771 
13772   EXPECT_EQ("\"splitmea\"\n"
13773             "\"trandomp\"\n"
13774             "\"oint\"",
13775             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
13776 
13777   EXPECT_EQ("\"split/\"\n"
13778             "\"pathat/\"\n"
13779             "\"slashes\"",
13780             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13781 
13782   EXPECT_EQ("\"split/\"\n"
13783             "\"pathat/\"\n"
13784             "\"slashes\"",
13785             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
13786   EXPECT_EQ("\"split at \"\n"
13787             "\"spaces/at/\"\n"
13788             "\"slashes.at.any$\"\n"
13789             "\"non-alphanumeric%\"\n"
13790             "\"1111111111characte\"\n"
13791             "\"rs\"",
13792             format("\"split at "
13793                    "spaces/at/"
13794                    "slashes.at."
13795                    "any$non-"
13796                    "alphanumeric%"
13797                    "1111111111characte"
13798                    "rs\"",
13799                    getLLVMStyleWithColumns(20)));
13800 
13801   // Verify that splitting the strings understands
13802   // Style::AlwaysBreakBeforeMultilineStrings.
13803   EXPECT_EQ("aaaaaaaaaaaa(\n"
13804             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
13805             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
13806             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
13807                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13808                    "aaaaaaaaaaaaaaaaaaaaaa\");",
13809                    getGoogleStyle()));
13810   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13811             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
13812             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
13813                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
13814                    "aaaaaaaaaaaaaaaaaaaaaa\";",
13815                    getGoogleStyle()));
13816   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13817             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
13818             format("llvm::outs() << "
13819                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
13820                    "aaaaaaaaaaaaaaaaaaa\";"));
13821   EXPECT_EQ("ffff(\n"
13822             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
13823             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13824             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
13825                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
13826                    getGoogleStyle()));
13827 
13828   FormatStyle Style = getLLVMStyleWithColumns(12);
13829   Style.BreakStringLiterals = false;
13830   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
13831 
13832   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
13833   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13834   EXPECT_EQ("#define A \\\n"
13835             "  \"some \" \\\n"
13836             "  \"text \" \\\n"
13837             "  \"other\";",
13838             format("#define A \"some text other\";", AlignLeft));
13839 }
13840 
TEST_F(FormatTest,BreaksStringLiteralsAtColumnLimit)13841 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
13842   EXPECT_EQ("C a = \"some more \"\n"
13843             "      \"text\";",
13844             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
13845 }
13846 
TEST_F(FormatTest,FullyRemoveEmptyLines)13847 TEST_F(FormatTest, FullyRemoveEmptyLines) {
13848   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
13849   NoEmptyLines.MaxEmptyLinesToKeep = 0;
13850   EXPECT_EQ("int i = a(b());",
13851             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
13852 }
13853 
TEST_F(FormatTest,BreaksStringLiteralsWithTabs)13854 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
13855   EXPECT_EQ(
13856       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13857       "(\n"
13858       "    \"x\t\");",
13859       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
13860              "aaaaaaa("
13861              "\"x\t\");"));
13862 }
13863 
TEST_F(FormatTest,BreaksWideAndNSStringLiterals)13864 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
13865   EXPECT_EQ(
13866       "u8\"utf8 string \"\n"
13867       "u8\"literal\";",
13868       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
13869   EXPECT_EQ(
13870       "u\"utf16 string \"\n"
13871       "u\"literal\";",
13872       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
13873   EXPECT_EQ(
13874       "U\"utf32 string \"\n"
13875       "U\"literal\";",
13876       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
13877   EXPECT_EQ("L\"wide string \"\n"
13878             "L\"literal\";",
13879             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
13880   EXPECT_EQ("@\"NSString \"\n"
13881             "@\"literal\";",
13882             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
13883   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
13884 
13885   // This input makes clang-format try to split the incomplete unicode escape
13886   // sequence, which used to lead to a crasher.
13887   verifyNoCrash(
13888       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
13889       getLLVMStyleWithColumns(60));
13890 }
13891 
TEST_F(FormatTest,DoesNotBreakRawStringLiterals)13892 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
13893   FormatStyle Style = getGoogleStyleWithColumns(15);
13894   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
13895   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
13896   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
13897   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
13898   EXPECT_EQ("u8R\"x(raw literal)x\";",
13899             format("u8R\"x(raw literal)x\";", Style));
13900 }
13901 
TEST_F(FormatTest,BreaksStringLiteralsWithin_TMacro)13902 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
13903   FormatStyle Style = getLLVMStyleWithColumns(20);
13904   EXPECT_EQ(
13905       "_T(\"aaaaaaaaaaaaaa\")\n"
13906       "_T(\"aaaaaaaaaaaaaa\")\n"
13907       "_T(\"aaaaaaaaaaaa\")",
13908       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
13909   EXPECT_EQ("f(x,\n"
13910             "  _T(\"aaaaaaaaaaaa\")\n"
13911             "  _T(\"aaa\"),\n"
13912             "  z);",
13913             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
13914 
13915   // FIXME: Handle embedded spaces in one iteration.
13916   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
13917   //            "_T(\"aaaaaaaaaaaaa\")\n"
13918   //            "_T(\"aaaaaaaaaaaaa\")\n"
13919   //            "_T(\"a\")",
13920   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13921   //                   getLLVMStyleWithColumns(20)));
13922   EXPECT_EQ(
13923       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
13924       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
13925   EXPECT_EQ("f(\n"
13926             "#if !TEST\n"
13927             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13928             "#endif\n"
13929             ");",
13930             format("f(\n"
13931                    "#if !TEST\n"
13932                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
13933                    "#endif\n"
13934                    ");"));
13935   EXPECT_EQ("f(\n"
13936             "\n"
13937             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
13938             format("f(\n"
13939                    "\n"
13940                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
13941   // Regression test for accessing tokens past the end of a vector in the
13942   // TokenLexer.
13943   verifyNoCrash(R"(_T(
13944 "
13945 )
13946 )");
13947 }
13948 
13949 TEST_F(FormatTest, BreaksStringLiteralOperands) {
13950   // In a function call with two operands, the second can be broken with no line
13951   // break before it.
13952   EXPECT_EQ(
13953       "func(a, \"long long \"\n"
13954       "        \"long long\");",
13955       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
13956   // In a function call with three operands, the second must be broken with a
13957   // line break before it.
13958   EXPECT_EQ("func(a,\n"
13959             "     \"long long long \"\n"
13960             "     \"long\",\n"
13961             "     c);",
13962             format("func(a, \"long long long long\", c);",
13963                    getLLVMStyleWithColumns(24)));
13964   // In a function call with three operands, the third must be broken with a
13965   // line break before it.
13966   EXPECT_EQ("func(a, b,\n"
13967             "     \"long long long \"\n"
13968             "     \"long\");",
13969             format("func(a, b, \"long long long long\");",
13970                    getLLVMStyleWithColumns(24)));
13971   // In a function call with three operands, both the second and the third must
13972   // be broken with a line break before them.
13973   EXPECT_EQ("func(a,\n"
13974             "     \"long long long \"\n"
13975             "     \"long\",\n"
13976             "     \"long long long \"\n"
13977             "     \"long\");",
13978             format("func(a, \"long long long long\", \"long long long long\");",
13979                    getLLVMStyleWithColumns(24)));
13980   // In a chain of << with two operands, the second can be broken with no line
13981   // break before it.
13982   EXPECT_EQ("a << \"line line \"\n"
13983             "     \"line\";",
13984             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
13985   // In a chain of << with three operands, the second can be broken with no line
13986   // break before it.
13987   EXPECT_EQ(
13988       "abcde << \"line \"\n"
13989       "         \"line line\"\n"
13990       "      << c;",
13991       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
13992   // In a chain of << with three operands, the third must be broken with a line
13993   // break before it.
13994   EXPECT_EQ(
13995       "a << b\n"
13996       "  << \"line line \"\n"
13997       "     \"line\";",
13998       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
13999   // In a chain of << with three operands, the second can be broken with no line
14000   // break before it and the third must be broken with a line break before it.
14001   EXPECT_EQ("abcd << \"line line \"\n"
14002             "        \"line\"\n"
14003             "     << \"line line \"\n"
14004             "        \"line\";",
14005             format("abcd << \"line line line\" << \"line line line\";",
14006                    getLLVMStyleWithColumns(20)));
14007   // In a chain of binary operators with two operands, the second can be broken
14008   // with no line break before it.
14009   EXPECT_EQ(
14010       "abcd + \"line line \"\n"
14011       "       \"line line\";",
14012       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
14013   // In a chain of binary operators with three operands, the second must be
14014   // broken with a line break before it.
14015   EXPECT_EQ("abcd +\n"
14016             "    \"line line \"\n"
14017             "    \"line line\" +\n"
14018             "    e;",
14019             format("abcd + \"line line line line\" + e;",
14020                    getLLVMStyleWithColumns(20)));
14021   // In a function call with two operands, with AlignAfterOpenBracket enabled,
14022   // the first must be broken with a line break before it.
14023   FormatStyle Style = getLLVMStyleWithColumns(25);
14024   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14025   EXPECT_EQ("someFunction(\n"
14026             "    \"long long long \"\n"
14027             "    \"long\",\n"
14028             "    a);",
14029             format("someFunction(\"long long long long\", a);", Style));
14030 }
14031 
TEST_F(FormatTest,DontSplitStringLiteralsWithEscapedNewlines)14032 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
14033   EXPECT_EQ(
14034       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
14035       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
14036       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
14037       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
14038              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
14039              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
14040 }
14041 
TEST_F(FormatTest,CountsCharactersInMultilineRawStringLiterals)14042 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
14043   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
14044             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
14045   EXPECT_EQ("fffffffffff(g(R\"x(\n"
14046             "multiline raw string literal xxxxxxxxxxxxxx\n"
14047             ")x\",\n"
14048             "              a),\n"
14049             "            b);",
14050             format("fffffffffff(g(R\"x(\n"
14051                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14052                    ")x\", a), b);",
14053                    getGoogleStyleWithColumns(20)));
14054   EXPECT_EQ("fffffffffff(\n"
14055             "    g(R\"x(qqq\n"
14056             "multiline raw string literal xxxxxxxxxxxxxx\n"
14057             ")x\",\n"
14058             "      a),\n"
14059             "    b);",
14060             format("fffffffffff(g(R\"x(qqq\n"
14061                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14062                    ")x\", a), b);",
14063                    getGoogleStyleWithColumns(20)));
14064 
14065   EXPECT_EQ("fffffffffff(R\"x(\n"
14066             "multiline raw string literal xxxxxxxxxxxxxx\n"
14067             ")x\");",
14068             format("fffffffffff(R\"x(\n"
14069                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14070                    ")x\");",
14071                    getGoogleStyleWithColumns(20)));
14072   EXPECT_EQ("fffffffffff(R\"x(\n"
14073             "multiline raw string literal xxxxxxxxxxxxxx\n"
14074             ")x\" + bbbbbb);",
14075             format("fffffffffff(R\"x(\n"
14076                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14077                    ")x\" +   bbbbbb);",
14078                    getGoogleStyleWithColumns(20)));
14079   EXPECT_EQ("fffffffffff(\n"
14080             "    R\"x(\n"
14081             "multiline raw string literal xxxxxxxxxxxxxx\n"
14082             ")x\" +\n"
14083             "    bbbbbb);",
14084             format("fffffffffff(\n"
14085                    " R\"x(\n"
14086                    "multiline raw string literal xxxxxxxxxxxxxx\n"
14087                    ")x\" + bbbbbb);",
14088                    getGoogleStyleWithColumns(20)));
14089   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
14090             format("fffffffffff(\n"
14091                    " R\"(single line raw string)\" + bbbbbb);"));
14092 }
14093 
TEST_F(FormatTest,SkipsUnknownStringLiterals)14094 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
14095   verifyFormat("string a = \"unterminated;");
14096   EXPECT_EQ("function(\"unterminated,\n"
14097             "         OtherParameter);",
14098             format("function(  \"unterminated,\n"
14099                    "    OtherParameter);"));
14100 }
14101 
TEST_F(FormatTest,DoesNotTryToParseUDLiteralsInPreCpp11Code)14102 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
14103   FormatStyle Style = getLLVMStyle();
14104   Style.Standard = FormatStyle::LS_Cpp03;
14105   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
14106             format("#define x(_a) printf(\"foo\"_a);", Style));
14107 }
14108 
TEST_F(FormatTest,CppLexVersion)14109 TEST_F(FormatTest, CppLexVersion) {
14110   FormatStyle Style = getLLVMStyle();
14111   // Formatting of x * y differs if x is a type.
14112   verifyFormat("void foo() { MACRO(a * b); }", Style);
14113   verifyFormat("void foo() { MACRO(int *b); }", Style);
14114 
14115   // LLVM style uses latest lexer.
14116   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
14117   Style.Standard = FormatStyle::LS_Cpp17;
14118   // But in c++17, char8_t isn't a keyword.
14119   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
14120 }
14121 
TEST_F(FormatTest,UnderstandsCpp1y)14122 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
14123 
TEST_F(FormatTest,BreakStringLiteralsBeforeUnbreakableTokenSequence)14124 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
14125   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
14126             "             \"ddeeefff\");",
14127             format("someFunction(\"aaabbbcccdddeeefff\");",
14128                    getLLVMStyleWithColumns(25)));
14129   EXPECT_EQ("someFunction1234567890(\n"
14130             "    \"aaabbbcccdddeeefff\");",
14131             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14132                    getLLVMStyleWithColumns(26)));
14133   EXPECT_EQ("someFunction1234567890(\n"
14134             "    \"aaabbbcccdddeeeff\"\n"
14135             "    \"f\");",
14136             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14137                    getLLVMStyleWithColumns(25)));
14138   EXPECT_EQ("someFunction1234567890(\n"
14139             "    \"aaabbbcccdddeeeff\"\n"
14140             "    \"f\");",
14141             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
14142                    getLLVMStyleWithColumns(24)));
14143   EXPECT_EQ("someFunction(\n"
14144             "    \"aaabbbcc ddde \"\n"
14145             "    \"efff\");",
14146             format("someFunction(\"aaabbbcc ddde efff\");",
14147                    getLLVMStyleWithColumns(25)));
14148   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
14149             "             \"ddeeefff\");",
14150             format("someFunction(\"aaabbbccc ddeeefff\");",
14151                    getLLVMStyleWithColumns(25)));
14152   EXPECT_EQ("someFunction1234567890(\n"
14153             "    \"aaabb \"\n"
14154             "    \"cccdddeeefff\");",
14155             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
14156                    getLLVMStyleWithColumns(25)));
14157   EXPECT_EQ("#define A          \\\n"
14158             "  string s =       \\\n"
14159             "      \"123456789\"  \\\n"
14160             "      \"0\";         \\\n"
14161             "  int i;",
14162             format("#define A string s = \"1234567890\"; int i;",
14163                    getLLVMStyleWithColumns(20)));
14164   EXPECT_EQ("someFunction(\n"
14165             "    \"aaabbbcc \"\n"
14166             "    \"dddeeefff\");",
14167             format("someFunction(\"aaabbbcc dddeeefff\");",
14168                    getLLVMStyleWithColumns(25)));
14169 }
14170 
TEST_F(FormatTest,DoNotBreakStringLiteralsInEscapeSequence)14171 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
14172   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
14173   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
14174   EXPECT_EQ("\"test\"\n"
14175             "\"\\n\"",
14176             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
14177   EXPECT_EQ("\"tes\\\\\"\n"
14178             "\"n\"",
14179             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
14180   EXPECT_EQ("\"\\\\\\\\\"\n"
14181             "\"\\n\"",
14182             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
14183   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
14184   EXPECT_EQ("\"\\uff01\"\n"
14185             "\"test\"",
14186             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
14187   EXPECT_EQ("\"\\Uff01ff02\"",
14188             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
14189   EXPECT_EQ("\"\\x000000000001\"\n"
14190             "\"next\"",
14191             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
14192   EXPECT_EQ("\"\\x000000000001next\"",
14193             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
14194   EXPECT_EQ("\"\\x000000000001\"",
14195             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
14196   EXPECT_EQ("\"test\"\n"
14197             "\"\\000000\"\n"
14198             "\"000001\"",
14199             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
14200   EXPECT_EQ("\"test\\000\"\n"
14201             "\"00000000\"\n"
14202             "\"1\"",
14203             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
14204 }
14205 
TEST_F(FormatTest,DoNotCreateUnreasonableUnwrappedLines)14206 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
14207   verifyFormat("void f() {\n"
14208                "  return g() {}\n"
14209                "  void h() {}");
14210   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
14211                "g();\n"
14212                "}");
14213 }
14214 
TEST_F(FormatTest,DoNotPrematurelyEndUnwrappedLineForReturnStatements)14215 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
14216   verifyFormat(
14217       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
14218 }
14219 
TEST_F(FormatTest,FormatsClosingBracesInEmptyNestedBlocks)14220 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
14221   verifyFormat("class X {\n"
14222                "  void f() {\n"
14223                "  }\n"
14224                "};",
14225                getLLVMStyleWithColumns(12));
14226 }
14227 
TEST_F(FormatTest,ConfigurableIndentWidth)14228 TEST_F(FormatTest, ConfigurableIndentWidth) {
14229   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
14230   EightIndent.IndentWidth = 8;
14231   EightIndent.ContinuationIndentWidth = 8;
14232   verifyFormat("void f() {\n"
14233                "        someFunction();\n"
14234                "        if (true) {\n"
14235                "                f();\n"
14236                "        }\n"
14237                "}",
14238                EightIndent);
14239   verifyFormat("class X {\n"
14240                "        void f() {\n"
14241                "        }\n"
14242                "};",
14243                EightIndent);
14244   verifyFormat("int x[] = {\n"
14245                "        call(),\n"
14246                "        call()};",
14247                EightIndent);
14248 }
14249 
TEST_F(FormatTest,ConfigurableFunctionDeclarationIndentAfterType)14250 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
14251   verifyFormat("double\n"
14252                "f();",
14253                getLLVMStyleWithColumns(8));
14254 }
14255 
TEST_F(FormatTest,ConfigurableUseOfTab)14256 TEST_F(FormatTest, ConfigurableUseOfTab) {
14257   FormatStyle Tab = getLLVMStyleWithColumns(42);
14258   Tab.IndentWidth = 8;
14259   Tab.UseTab = FormatStyle::UT_Always;
14260   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14261 
14262   EXPECT_EQ("if (aaaaaaaa && // q\n"
14263             "    bb)\t\t// w\n"
14264             "\t;",
14265             format("if (aaaaaaaa &&// q\n"
14266                    "bb)// w\n"
14267                    ";",
14268                    Tab));
14269   EXPECT_EQ("if (aaa && bbb) // w\n"
14270             "\t;",
14271             format("if(aaa&&bbb)// w\n"
14272                    ";",
14273                    Tab));
14274 
14275   verifyFormat("class X {\n"
14276                "\tvoid f() {\n"
14277                "\t\tsomeFunction(parameter1,\n"
14278                "\t\t\t     parameter2);\n"
14279                "\t}\n"
14280                "};",
14281                Tab);
14282   verifyFormat("#define A                        \\\n"
14283                "\tvoid f() {               \\\n"
14284                "\t\tsomeFunction(    \\\n"
14285                "\t\t    parameter1,  \\\n"
14286                "\t\t    parameter2); \\\n"
14287                "\t}",
14288                Tab);
14289   verifyFormat("int a;\t      // x\n"
14290                "int bbbbbbbb; // x\n",
14291                Tab);
14292 
14293   FormatStyle TabAlignment = Tab;
14294   TabAlignment.AlignConsecutiveDeclarations.Enabled = true;
14295   TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
14296   verifyFormat("unsigned long long big;\n"
14297                "char*\t\t   ptr;",
14298                TabAlignment);
14299   TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
14300   verifyFormat("unsigned long long big;\n"
14301                "char *\t\t   ptr;",
14302                TabAlignment);
14303   TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
14304   verifyFormat("unsigned long long big;\n"
14305                "char\t\t  *ptr;",
14306                TabAlignment);
14307 
14308   Tab.TabWidth = 4;
14309   Tab.IndentWidth = 8;
14310   verifyFormat("class TabWidth4Indent8 {\n"
14311                "\t\tvoid f() {\n"
14312                "\t\t\t\tsomeFunction(parameter1,\n"
14313                "\t\t\t\t\t\t\t parameter2);\n"
14314                "\t\t}\n"
14315                "};",
14316                Tab);
14317 
14318   Tab.TabWidth = 4;
14319   Tab.IndentWidth = 4;
14320   verifyFormat("class TabWidth4Indent4 {\n"
14321                "\tvoid f() {\n"
14322                "\t\tsomeFunction(parameter1,\n"
14323                "\t\t\t\t\t parameter2);\n"
14324                "\t}\n"
14325                "};",
14326                Tab);
14327 
14328   Tab.TabWidth = 8;
14329   Tab.IndentWidth = 4;
14330   verifyFormat("class TabWidth8Indent4 {\n"
14331                "    void f() {\n"
14332                "\tsomeFunction(parameter1,\n"
14333                "\t\t     parameter2);\n"
14334                "    }\n"
14335                "};",
14336                Tab);
14337 
14338   Tab.TabWidth = 8;
14339   Tab.IndentWidth = 8;
14340   EXPECT_EQ("/*\n"
14341             "\t      a\t\tcomment\n"
14342             "\t      in multiple lines\n"
14343             "       */",
14344             format("   /*\t \t \n"
14345                    " \t \t a\t\tcomment\t \t\n"
14346                    " \t \t in multiple lines\t\n"
14347                    " \t  */",
14348                    Tab));
14349 
14350   TabAlignment.UseTab = FormatStyle::UT_ForIndentation;
14351   TabAlignment.PointerAlignment = FormatStyle::PAS_Left;
14352   verifyFormat("void f() {\n"
14353                "\tunsigned long long big;\n"
14354                "\tchar*              ptr;\n"
14355                "}",
14356                TabAlignment);
14357   TabAlignment.PointerAlignment = FormatStyle::PAS_Middle;
14358   verifyFormat("void f() {\n"
14359                "\tunsigned long long big;\n"
14360                "\tchar *             ptr;\n"
14361                "}",
14362                TabAlignment);
14363   TabAlignment.PointerAlignment = FormatStyle::PAS_Right;
14364   verifyFormat("void f() {\n"
14365                "\tunsigned long long big;\n"
14366                "\tchar              *ptr;\n"
14367                "}",
14368                TabAlignment);
14369 
14370   Tab.UseTab = FormatStyle::UT_ForIndentation;
14371   verifyFormat("{\n"
14372                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14373                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14374                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14375                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14376                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14377                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14378                "};",
14379                Tab);
14380   verifyFormat("enum AA {\n"
14381                "\ta1, // Force multiple lines\n"
14382                "\ta2,\n"
14383                "\ta3\n"
14384                "};",
14385                Tab);
14386   EXPECT_EQ("if (aaaaaaaa && // q\n"
14387             "    bb)         // w\n"
14388             "\t;",
14389             format("if (aaaaaaaa &&// q\n"
14390                    "bb)// w\n"
14391                    ";",
14392                    Tab));
14393   verifyFormat("class X {\n"
14394                "\tvoid f() {\n"
14395                "\t\tsomeFunction(parameter1,\n"
14396                "\t\t             parameter2);\n"
14397                "\t}\n"
14398                "};",
14399                Tab);
14400   verifyFormat("{\n"
14401                "\tQ(\n"
14402                "\t    {\n"
14403                "\t\t    int a;\n"
14404                "\t\t    someFunction(aaaaaaaa,\n"
14405                "\t\t                 bbbbbbb);\n"
14406                "\t    },\n"
14407                "\t    p);\n"
14408                "}",
14409                Tab);
14410   EXPECT_EQ("{\n"
14411             "\t/* aaaa\n"
14412             "\t   bbbb */\n"
14413             "}",
14414             format("{\n"
14415                    "/* aaaa\n"
14416                    "   bbbb */\n"
14417                    "}",
14418                    Tab));
14419   EXPECT_EQ("{\n"
14420             "\t/*\n"
14421             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14422             "\t  bbbbbbbbbbbbb\n"
14423             "\t*/\n"
14424             "}",
14425             format("{\n"
14426                    "/*\n"
14427                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14428                    "*/\n"
14429                    "}",
14430                    Tab));
14431   EXPECT_EQ("{\n"
14432             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14433             "\t// bbbbbbbbbbbbb\n"
14434             "}",
14435             format("{\n"
14436                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14437                    "}",
14438                    Tab));
14439   EXPECT_EQ("{\n"
14440             "\t/*\n"
14441             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14442             "\t  bbbbbbbbbbbbb\n"
14443             "\t*/\n"
14444             "}",
14445             format("{\n"
14446                    "\t/*\n"
14447                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14448                    "\t*/\n"
14449                    "}",
14450                    Tab));
14451   EXPECT_EQ("{\n"
14452             "\t/*\n"
14453             "\n"
14454             "\t*/\n"
14455             "}",
14456             format("{\n"
14457                    "\t/*\n"
14458                    "\n"
14459                    "\t*/\n"
14460                    "}",
14461                    Tab));
14462   EXPECT_EQ("{\n"
14463             "\t/*\n"
14464             " asdf\n"
14465             "\t*/\n"
14466             "}",
14467             format("{\n"
14468                    "\t/*\n"
14469                    " asdf\n"
14470                    "\t*/\n"
14471                    "}",
14472                    Tab));
14473 
14474   verifyFormat("void f() {\n"
14475                "\treturn true ? aaaaaaaaaaaaaaaaaa\n"
14476                "\t            : bbbbbbbbbbbbbbbbbb\n"
14477                "}",
14478                Tab);
14479   FormatStyle TabNoBreak = Tab;
14480   TabNoBreak.BreakBeforeTernaryOperators = false;
14481   verifyFormat("void f() {\n"
14482                "\treturn true ? aaaaaaaaaaaaaaaaaa :\n"
14483                "\t              bbbbbbbbbbbbbbbbbb\n"
14484                "}",
14485                TabNoBreak);
14486   verifyFormat("void f() {\n"
14487                "\treturn true ?\n"
14488                "\t           aaaaaaaaaaaaaaaaaaaa :\n"
14489                "\t           bbbbbbbbbbbbbbbbbbbb\n"
14490                "}",
14491                TabNoBreak);
14492 
14493   Tab.UseTab = FormatStyle::UT_Never;
14494   EXPECT_EQ("/*\n"
14495             "              a\t\tcomment\n"
14496             "              in multiple lines\n"
14497             "       */",
14498             format("   /*\t \t \n"
14499                    " \t \t a\t\tcomment\t \t\n"
14500                    " \t \t in multiple lines\t\n"
14501                    " \t  */",
14502                    Tab));
14503   EXPECT_EQ("/* some\n"
14504             "   comment */",
14505             format(" \t \t /* some\n"
14506                    " \t \t    comment */",
14507                    Tab));
14508   EXPECT_EQ("int a; /* some\n"
14509             "   comment */",
14510             format(" \t \t int a; /* some\n"
14511                    " \t \t    comment */",
14512                    Tab));
14513 
14514   EXPECT_EQ("int a; /* some\n"
14515             "comment */",
14516             format(" \t \t int\ta; /* some\n"
14517                    " \t \t    comment */",
14518                    Tab));
14519   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14520             "    comment */",
14521             format(" \t \t f(\"\t\t\"); /* some\n"
14522                    " \t \t    comment */",
14523                    Tab));
14524   EXPECT_EQ("{\n"
14525             "        /*\n"
14526             "         * Comment\n"
14527             "         */\n"
14528             "        int i;\n"
14529             "}",
14530             format("{\n"
14531                    "\t/*\n"
14532                    "\t * Comment\n"
14533                    "\t */\n"
14534                    "\t int i;\n"
14535                    "}",
14536                    Tab));
14537 
14538   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
14539   Tab.TabWidth = 8;
14540   Tab.IndentWidth = 8;
14541   EXPECT_EQ("if (aaaaaaaa && // q\n"
14542             "    bb)         // w\n"
14543             "\t;",
14544             format("if (aaaaaaaa &&// q\n"
14545                    "bb)// w\n"
14546                    ";",
14547                    Tab));
14548   EXPECT_EQ("if (aaa && bbb) // w\n"
14549             "\t;",
14550             format("if(aaa&&bbb)// w\n"
14551                    ";",
14552                    Tab));
14553   verifyFormat("class X {\n"
14554                "\tvoid f() {\n"
14555                "\t\tsomeFunction(parameter1,\n"
14556                "\t\t\t     parameter2);\n"
14557                "\t}\n"
14558                "};",
14559                Tab);
14560   verifyFormat("#define A                        \\\n"
14561                "\tvoid f() {               \\\n"
14562                "\t\tsomeFunction(    \\\n"
14563                "\t\t    parameter1,  \\\n"
14564                "\t\t    parameter2); \\\n"
14565                "\t}",
14566                Tab);
14567   Tab.TabWidth = 4;
14568   Tab.IndentWidth = 8;
14569   verifyFormat("class TabWidth4Indent8 {\n"
14570                "\t\tvoid f() {\n"
14571                "\t\t\t\tsomeFunction(parameter1,\n"
14572                "\t\t\t\t\t\t\t parameter2);\n"
14573                "\t\t}\n"
14574                "};",
14575                Tab);
14576   Tab.TabWidth = 4;
14577   Tab.IndentWidth = 4;
14578   verifyFormat("class TabWidth4Indent4 {\n"
14579                "\tvoid f() {\n"
14580                "\t\tsomeFunction(parameter1,\n"
14581                "\t\t\t\t\t parameter2);\n"
14582                "\t}\n"
14583                "};",
14584                Tab);
14585   Tab.TabWidth = 8;
14586   Tab.IndentWidth = 4;
14587   verifyFormat("class TabWidth8Indent4 {\n"
14588                "    void f() {\n"
14589                "\tsomeFunction(parameter1,\n"
14590                "\t\t     parameter2);\n"
14591                "    }\n"
14592                "};",
14593                Tab);
14594   Tab.TabWidth = 8;
14595   Tab.IndentWidth = 8;
14596   EXPECT_EQ("/*\n"
14597             "\t      a\t\tcomment\n"
14598             "\t      in multiple lines\n"
14599             "       */",
14600             format("   /*\t \t \n"
14601                    " \t \t a\t\tcomment\t \t\n"
14602                    " \t \t in multiple lines\t\n"
14603                    " \t  */",
14604                    Tab));
14605   verifyFormat("{\n"
14606                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14607                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14608                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14609                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14610                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14611                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14612                "};",
14613                Tab);
14614   verifyFormat("enum AA {\n"
14615                "\ta1, // Force multiple lines\n"
14616                "\ta2,\n"
14617                "\ta3\n"
14618                "};",
14619                Tab);
14620   EXPECT_EQ("if (aaaaaaaa && // q\n"
14621             "    bb)         // w\n"
14622             "\t;",
14623             format("if (aaaaaaaa &&// q\n"
14624                    "bb)// w\n"
14625                    ";",
14626                    Tab));
14627   verifyFormat("class X {\n"
14628                "\tvoid f() {\n"
14629                "\t\tsomeFunction(parameter1,\n"
14630                "\t\t\t     parameter2);\n"
14631                "\t}\n"
14632                "};",
14633                Tab);
14634   verifyFormat("{\n"
14635                "\tQ(\n"
14636                "\t    {\n"
14637                "\t\t    int a;\n"
14638                "\t\t    someFunction(aaaaaaaa,\n"
14639                "\t\t\t\t bbbbbbb);\n"
14640                "\t    },\n"
14641                "\t    p);\n"
14642                "}",
14643                Tab);
14644   EXPECT_EQ("{\n"
14645             "\t/* aaaa\n"
14646             "\t   bbbb */\n"
14647             "}",
14648             format("{\n"
14649                    "/* aaaa\n"
14650                    "   bbbb */\n"
14651                    "}",
14652                    Tab));
14653   EXPECT_EQ("{\n"
14654             "\t/*\n"
14655             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14656             "\t  bbbbbbbbbbbbb\n"
14657             "\t*/\n"
14658             "}",
14659             format("{\n"
14660                    "/*\n"
14661                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14662                    "*/\n"
14663                    "}",
14664                    Tab));
14665   EXPECT_EQ("{\n"
14666             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14667             "\t// bbbbbbbbbbbbb\n"
14668             "}",
14669             format("{\n"
14670                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14671                    "}",
14672                    Tab));
14673   EXPECT_EQ("{\n"
14674             "\t/*\n"
14675             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14676             "\t  bbbbbbbbbbbbb\n"
14677             "\t*/\n"
14678             "}",
14679             format("{\n"
14680                    "\t/*\n"
14681                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14682                    "\t*/\n"
14683                    "}",
14684                    Tab));
14685   EXPECT_EQ("{\n"
14686             "\t/*\n"
14687             "\n"
14688             "\t*/\n"
14689             "}",
14690             format("{\n"
14691                    "\t/*\n"
14692                    "\n"
14693                    "\t*/\n"
14694                    "}",
14695                    Tab));
14696   EXPECT_EQ("{\n"
14697             "\t/*\n"
14698             " asdf\n"
14699             "\t*/\n"
14700             "}",
14701             format("{\n"
14702                    "\t/*\n"
14703                    " asdf\n"
14704                    "\t*/\n"
14705                    "}",
14706                    Tab));
14707   EXPECT_EQ("/* some\n"
14708             "   comment */",
14709             format(" \t \t /* some\n"
14710                    " \t \t    comment */",
14711                    Tab));
14712   EXPECT_EQ("int a; /* some\n"
14713             "   comment */",
14714             format(" \t \t int a; /* some\n"
14715                    " \t \t    comment */",
14716                    Tab));
14717   EXPECT_EQ("int a; /* some\n"
14718             "comment */",
14719             format(" \t \t int\ta; /* some\n"
14720                    " \t \t    comment */",
14721                    Tab));
14722   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14723             "    comment */",
14724             format(" \t \t f(\"\t\t\"); /* some\n"
14725                    " \t \t    comment */",
14726                    Tab));
14727   EXPECT_EQ("{\n"
14728             "\t/*\n"
14729             "\t * Comment\n"
14730             "\t */\n"
14731             "\tint i;\n"
14732             "}",
14733             format("{\n"
14734                    "\t/*\n"
14735                    "\t * Comment\n"
14736                    "\t */\n"
14737                    "\t int i;\n"
14738                    "}",
14739                    Tab));
14740   Tab.TabWidth = 2;
14741   Tab.IndentWidth = 2;
14742   EXPECT_EQ("{\n"
14743             "\t/* aaaa\n"
14744             "\t\t bbbb */\n"
14745             "}",
14746             format("{\n"
14747                    "/* aaaa\n"
14748                    "\t bbbb */\n"
14749                    "}",
14750                    Tab));
14751   EXPECT_EQ("{\n"
14752             "\t/*\n"
14753             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14754             "\t\tbbbbbbbbbbbbb\n"
14755             "\t*/\n"
14756             "}",
14757             format("{\n"
14758                    "/*\n"
14759                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14760                    "*/\n"
14761                    "}",
14762                    Tab));
14763   Tab.AlignConsecutiveAssignments.Enabled = true;
14764   Tab.AlignConsecutiveDeclarations.Enabled = true;
14765   Tab.TabWidth = 4;
14766   Tab.IndentWidth = 4;
14767   verifyFormat("class Assign {\n"
14768                "\tvoid f() {\n"
14769                "\t\tint         x      = 123;\n"
14770                "\t\tint         random = 4;\n"
14771                "\t\tstd::string alphabet =\n"
14772                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
14773                "\t}\n"
14774                "};",
14775                Tab);
14776 
14777   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
14778   Tab.TabWidth = 8;
14779   Tab.IndentWidth = 8;
14780   EXPECT_EQ("if (aaaaaaaa && // q\n"
14781             "    bb)         // w\n"
14782             "\t;",
14783             format("if (aaaaaaaa &&// q\n"
14784                    "bb)// w\n"
14785                    ";",
14786                    Tab));
14787   EXPECT_EQ("if (aaa && bbb) // w\n"
14788             "\t;",
14789             format("if(aaa&&bbb)// w\n"
14790                    ";",
14791                    Tab));
14792   verifyFormat("class X {\n"
14793                "\tvoid f() {\n"
14794                "\t\tsomeFunction(parameter1,\n"
14795                "\t\t             parameter2);\n"
14796                "\t}\n"
14797                "};",
14798                Tab);
14799   verifyFormat("#define A                        \\\n"
14800                "\tvoid f() {               \\\n"
14801                "\t\tsomeFunction(    \\\n"
14802                "\t\t    parameter1,  \\\n"
14803                "\t\t    parameter2); \\\n"
14804                "\t}",
14805                Tab);
14806   Tab.TabWidth = 4;
14807   Tab.IndentWidth = 8;
14808   verifyFormat("class TabWidth4Indent8 {\n"
14809                "\t\tvoid f() {\n"
14810                "\t\t\t\tsomeFunction(parameter1,\n"
14811                "\t\t\t\t             parameter2);\n"
14812                "\t\t}\n"
14813                "};",
14814                Tab);
14815   Tab.TabWidth = 4;
14816   Tab.IndentWidth = 4;
14817   verifyFormat("class TabWidth4Indent4 {\n"
14818                "\tvoid f() {\n"
14819                "\t\tsomeFunction(parameter1,\n"
14820                "\t\t             parameter2);\n"
14821                "\t}\n"
14822                "};",
14823                Tab);
14824   Tab.TabWidth = 8;
14825   Tab.IndentWidth = 4;
14826   verifyFormat("class TabWidth8Indent4 {\n"
14827                "    void f() {\n"
14828                "\tsomeFunction(parameter1,\n"
14829                "\t             parameter2);\n"
14830                "    }\n"
14831                "};",
14832                Tab);
14833   Tab.TabWidth = 8;
14834   Tab.IndentWidth = 8;
14835   EXPECT_EQ("/*\n"
14836             "              a\t\tcomment\n"
14837             "              in multiple lines\n"
14838             "       */",
14839             format("   /*\t \t \n"
14840                    " \t \t a\t\tcomment\t \t\n"
14841                    " \t \t in multiple lines\t\n"
14842                    " \t  */",
14843                    Tab));
14844   verifyFormat("{\n"
14845                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14846                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14847                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14848                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14849                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14850                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
14851                "};",
14852                Tab);
14853   verifyFormat("enum AA {\n"
14854                "\ta1, // Force multiple lines\n"
14855                "\ta2,\n"
14856                "\ta3\n"
14857                "};",
14858                Tab);
14859   EXPECT_EQ("if (aaaaaaaa && // q\n"
14860             "    bb)         // w\n"
14861             "\t;",
14862             format("if (aaaaaaaa &&// q\n"
14863                    "bb)// w\n"
14864                    ";",
14865                    Tab));
14866   verifyFormat("class X {\n"
14867                "\tvoid f() {\n"
14868                "\t\tsomeFunction(parameter1,\n"
14869                "\t\t             parameter2);\n"
14870                "\t}\n"
14871                "};",
14872                Tab);
14873   verifyFormat("{\n"
14874                "\tQ(\n"
14875                "\t    {\n"
14876                "\t\t    int a;\n"
14877                "\t\t    someFunction(aaaaaaaa,\n"
14878                "\t\t                 bbbbbbb);\n"
14879                "\t    },\n"
14880                "\t    p);\n"
14881                "}",
14882                Tab);
14883   EXPECT_EQ("{\n"
14884             "\t/* aaaa\n"
14885             "\t   bbbb */\n"
14886             "}",
14887             format("{\n"
14888                    "/* aaaa\n"
14889                    "   bbbb */\n"
14890                    "}",
14891                    Tab));
14892   EXPECT_EQ("{\n"
14893             "\t/*\n"
14894             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14895             "\t  bbbbbbbbbbbbb\n"
14896             "\t*/\n"
14897             "}",
14898             format("{\n"
14899                    "/*\n"
14900                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14901                    "*/\n"
14902                    "}",
14903                    Tab));
14904   EXPECT_EQ("{\n"
14905             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14906             "\t// bbbbbbbbbbbbb\n"
14907             "}",
14908             format("{\n"
14909                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14910                    "}",
14911                    Tab));
14912   EXPECT_EQ("{\n"
14913             "\t/*\n"
14914             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14915             "\t  bbbbbbbbbbbbb\n"
14916             "\t*/\n"
14917             "}",
14918             format("{\n"
14919                    "\t/*\n"
14920                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14921                    "\t*/\n"
14922                    "}",
14923                    Tab));
14924   EXPECT_EQ("{\n"
14925             "\t/*\n"
14926             "\n"
14927             "\t*/\n"
14928             "}",
14929             format("{\n"
14930                    "\t/*\n"
14931                    "\n"
14932                    "\t*/\n"
14933                    "}",
14934                    Tab));
14935   EXPECT_EQ("{\n"
14936             "\t/*\n"
14937             " asdf\n"
14938             "\t*/\n"
14939             "}",
14940             format("{\n"
14941                    "\t/*\n"
14942                    " asdf\n"
14943                    "\t*/\n"
14944                    "}",
14945                    Tab));
14946   EXPECT_EQ("/* some\n"
14947             "   comment */",
14948             format(" \t \t /* some\n"
14949                    " \t \t    comment */",
14950                    Tab));
14951   EXPECT_EQ("int a; /* some\n"
14952             "   comment */",
14953             format(" \t \t int a; /* some\n"
14954                    " \t \t    comment */",
14955                    Tab));
14956   EXPECT_EQ("int a; /* some\n"
14957             "comment */",
14958             format(" \t \t int\ta; /* some\n"
14959                    " \t \t    comment */",
14960                    Tab));
14961   EXPECT_EQ("f(\"\t\t\"); /* some\n"
14962             "    comment */",
14963             format(" \t \t f(\"\t\t\"); /* some\n"
14964                    " \t \t    comment */",
14965                    Tab));
14966   EXPECT_EQ("{\n"
14967             "\t/*\n"
14968             "\t * Comment\n"
14969             "\t */\n"
14970             "\tint i;\n"
14971             "}",
14972             format("{\n"
14973                    "\t/*\n"
14974                    "\t * Comment\n"
14975                    "\t */\n"
14976                    "\t int i;\n"
14977                    "}",
14978                    Tab));
14979   Tab.TabWidth = 2;
14980   Tab.IndentWidth = 2;
14981   EXPECT_EQ("{\n"
14982             "\t/* aaaa\n"
14983             "\t   bbbb */\n"
14984             "}",
14985             format("{\n"
14986                    "/* aaaa\n"
14987                    "   bbbb */\n"
14988                    "}",
14989                    Tab));
14990   EXPECT_EQ("{\n"
14991             "\t/*\n"
14992             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
14993             "\t  bbbbbbbbbbbbb\n"
14994             "\t*/\n"
14995             "}",
14996             format("{\n"
14997                    "/*\n"
14998                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
14999                    "*/\n"
15000                    "}",
15001                    Tab));
15002   Tab.AlignConsecutiveAssignments.Enabled = true;
15003   Tab.AlignConsecutiveDeclarations.Enabled = true;
15004   Tab.TabWidth = 4;
15005   Tab.IndentWidth = 4;
15006   verifyFormat("class Assign {\n"
15007                "\tvoid f() {\n"
15008                "\t\tint         x      = 123;\n"
15009                "\t\tint         random = 4;\n"
15010                "\t\tstd::string alphabet =\n"
15011                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
15012                "\t}\n"
15013                "};",
15014                Tab);
15015   Tab.AlignOperands = FormatStyle::OAS_Align;
15016   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
15017                "                 cccccccccccccccccccc;",
15018                Tab);
15019   // no alignment
15020   verifyFormat("int aaaaaaaaaa =\n"
15021                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
15022                Tab);
15023   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
15024                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
15025                "                        : 333333333333333;",
15026                Tab);
15027   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15028   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
15029   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
15030                "               + cccccccccccccccccccc;",
15031                Tab);
15032 }
15033 
TEST_F(FormatTest,ZeroTabWidth)15034 TEST_F(FormatTest, ZeroTabWidth) {
15035   FormatStyle Tab = getLLVMStyleWithColumns(42);
15036   Tab.IndentWidth = 8;
15037   Tab.UseTab = FormatStyle::UT_Never;
15038   Tab.TabWidth = 0;
15039   EXPECT_EQ("void a(){\n"
15040             "    // line starts with '\t'\n"
15041             "};",
15042             format("void a(){\n"
15043                    "\t// line starts with '\t'\n"
15044                    "};",
15045                    Tab));
15046 
15047   EXPECT_EQ("void a(){\n"
15048             "    // line starts with '\t'\n"
15049             "};",
15050             format("void a(){\n"
15051                    "\t\t// line starts with '\t'\n"
15052                    "};",
15053                    Tab));
15054 
15055   Tab.UseTab = FormatStyle::UT_ForIndentation;
15056   EXPECT_EQ("void a(){\n"
15057             "    // line starts with '\t'\n"
15058             "};",
15059             format("void a(){\n"
15060                    "\t// line starts with '\t'\n"
15061                    "};",
15062                    Tab));
15063 
15064   EXPECT_EQ("void a(){\n"
15065             "    // line starts with '\t'\n"
15066             "};",
15067             format("void a(){\n"
15068                    "\t\t// line starts with '\t'\n"
15069                    "};",
15070                    Tab));
15071 
15072   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
15073   EXPECT_EQ("void a(){\n"
15074             "    // line starts with '\t'\n"
15075             "};",
15076             format("void a(){\n"
15077                    "\t// line starts with '\t'\n"
15078                    "};",
15079                    Tab));
15080 
15081   EXPECT_EQ("void a(){\n"
15082             "    // line starts with '\t'\n"
15083             "};",
15084             format("void a(){\n"
15085                    "\t\t// line starts with '\t'\n"
15086                    "};",
15087                    Tab));
15088 
15089   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
15090   EXPECT_EQ("void a(){\n"
15091             "    // line starts with '\t'\n"
15092             "};",
15093             format("void a(){\n"
15094                    "\t// line starts with '\t'\n"
15095                    "};",
15096                    Tab));
15097 
15098   EXPECT_EQ("void a(){\n"
15099             "    // line starts with '\t'\n"
15100             "};",
15101             format("void a(){\n"
15102                    "\t\t// line starts with '\t'\n"
15103                    "};",
15104                    Tab));
15105 
15106   Tab.UseTab = FormatStyle::UT_Always;
15107   EXPECT_EQ("void a(){\n"
15108             "// line starts with '\t'\n"
15109             "};",
15110             format("void a(){\n"
15111                    "\t// line starts with '\t'\n"
15112                    "};",
15113                    Tab));
15114 
15115   EXPECT_EQ("void a(){\n"
15116             "// line starts with '\t'\n"
15117             "};",
15118             format("void a(){\n"
15119                    "\t\t// line starts with '\t'\n"
15120                    "};",
15121                    Tab));
15122 }
15123 
TEST_F(FormatTest,CalculatesOriginalColumn)15124 TEST_F(FormatTest, CalculatesOriginalColumn) {
15125   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15126             "q\"; /* some\n"
15127             "       comment */",
15128             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15129                    "q\"; /* some\n"
15130                    "       comment */",
15131                    getLLVMStyle()));
15132   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
15133             "/* some\n"
15134             "   comment */",
15135             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
15136                    " /* some\n"
15137                    "    comment */",
15138                    getLLVMStyle()));
15139   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15140             "qqq\n"
15141             "/* some\n"
15142             "   comment */",
15143             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15144                    "qqq\n"
15145                    " /* some\n"
15146                    "    comment */",
15147                    getLLVMStyle()));
15148   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15149             "wwww; /* some\n"
15150             "         comment */",
15151             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
15152                    "wwww; /* some\n"
15153                    "         comment */",
15154                    getLLVMStyle()));
15155 }
15156 
TEST_F(FormatTest,ConfigurableSpaceBeforeParens)15157 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
15158   FormatStyle NoSpace = getLLVMStyle();
15159   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
15160 
15161   verifyFormat("while(true)\n"
15162                "  continue;",
15163                NoSpace);
15164   verifyFormat("for(;;)\n"
15165                "  continue;",
15166                NoSpace);
15167   verifyFormat("if(true)\n"
15168                "  f();\n"
15169                "else if(true)\n"
15170                "  f();",
15171                NoSpace);
15172   verifyFormat("do {\n"
15173                "  do_something();\n"
15174                "} while(something());",
15175                NoSpace);
15176   verifyFormat("switch(x) {\n"
15177                "default:\n"
15178                "  break;\n"
15179                "}",
15180                NoSpace);
15181   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
15182   verifyFormat("size_t x = sizeof(x);", NoSpace);
15183   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
15184   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
15185   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
15186   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
15187   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
15188   verifyFormat("alignas(128) char a[128];", NoSpace);
15189   verifyFormat("size_t x = alignof(MyType);", NoSpace);
15190   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
15191   verifyFormat("int f() throw(Deprecated);", NoSpace);
15192   verifyFormat("typedef void (*cb)(int);", NoSpace);
15193   verifyFormat("T A::operator()();", NoSpace);
15194   verifyFormat("X A::operator++(T);", NoSpace);
15195   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
15196 
15197   FormatStyle Space = getLLVMStyle();
15198   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
15199 
15200   verifyFormat("int f ();", Space);
15201   verifyFormat("void f (int a, T b) {\n"
15202                "  while (true)\n"
15203                "    continue;\n"
15204                "}",
15205                Space);
15206   verifyFormat("if (true)\n"
15207                "  f ();\n"
15208                "else if (true)\n"
15209                "  f ();",
15210                Space);
15211   verifyFormat("do {\n"
15212                "  do_something ();\n"
15213                "} while (something ());",
15214                Space);
15215   verifyFormat("switch (x) {\n"
15216                "default:\n"
15217                "  break;\n"
15218                "}",
15219                Space);
15220   verifyFormat("A::A () : a (1) {}", Space);
15221   verifyFormat("void f () __attribute__ ((asdf));", Space);
15222   verifyFormat("*(&a + 1);\n"
15223                "&((&a)[1]);\n"
15224                "a[(b + c) * d];\n"
15225                "(((a + 1) * 2) + 3) * 4;",
15226                Space);
15227   verifyFormat("#define A(x) x", Space);
15228   verifyFormat("#define A (x) x", Space);
15229   verifyFormat("#if defined(x)\n"
15230                "#endif",
15231                Space);
15232   verifyFormat("auto i = std::make_unique<int> (5);", Space);
15233   verifyFormat("size_t x = sizeof (x);", Space);
15234   verifyFormat("auto f (int x) -> decltype (x);", Space);
15235   verifyFormat("auto f (int x) -> typeof (x);", Space);
15236   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
15237   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
15238   verifyFormat("int f (T x) noexcept (x.create ());", Space);
15239   verifyFormat("alignas (128) char a[128];", Space);
15240   verifyFormat("size_t x = alignof (MyType);", Space);
15241   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
15242   verifyFormat("int f () throw (Deprecated);", Space);
15243   verifyFormat("typedef void (*cb) (int);", Space);
15244   // FIXME these tests regressed behaviour.
15245   // verifyFormat("T A::operator() ();", Space);
15246   // verifyFormat("X A::operator++ (T);", Space);
15247   verifyFormat("auto lambda = [] () { return 0; };", Space);
15248   verifyFormat("int x = int (y);", Space);
15249   verifyFormat("#define F(...) __VA_OPT__ (__VA_ARGS__)", Space);
15250   verifyFormat("__builtin_LINE ()", Space);
15251   verifyFormat("__builtin_UNKNOWN ()", Space);
15252 
15253   FormatStyle SomeSpace = getLLVMStyle();
15254   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
15255 
15256   verifyFormat("[]() -> float {}", SomeSpace);
15257   verifyFormat("[] (auto foo) {}", SomeSpace);
15258   verifyFormat("[foo]() -> int {}", SomeSpace);
15259   verifyFormat("int f();", SomeSpace);
15260   verifyFormat("void f (int a, T b) {\n"
15261                "  while (true)\n"
15262                "    continue;\n"
15263                "}",
15264                SomeSpace);
15265   verifyFormat("if (true)\n"
15266                "  f();\n"
15267                "else if (true)\n"
15268                "  f();",
15269                SomeSpace);
15270   verifyFormat("do {\n"
15271                "  do_something();\n"
15272                "} while (something());",
15273                SomeSpace);
15274   verifyFormat("switch (x) {\n"
15275                "default:\n"
15276                "  break;\n"
15277                "}",
15278                SomeSpace);
15279   verifyFormat("A::A() : a (1) {}", SomeSpace);
15280   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
15281   verifyFormat("*(&a + 1);\n"
15282                "&((&a)[1]);\n"
15283                "a[(b + c) * d];\n"
15284                "(((a + 1) * 2) + 3) * 4;",
15285                SomeSpace);
15286   verifyFormat("#define A(x) x", SomeSpace);
15287   verifyFormat("#define A (x) x", SomeSpace);
15288   verifyFormat("#if defined(x)\n"
15289                "#endif",
15290                SomeSpace);
15291   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
15292   verifyFormat("size_t x = sizeof (x);", SomeSpace);
15293   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
15294   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
15295   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
15296   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
15297   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
15298   verifyFormat("alignas (128) char a[128];", SomeSpace);
15299   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
15300   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15301                SomeSpace);
15302   verifyFormat("int f() throw (Deprecated);", SomeSpace);
15303   verifyFormat("typedef void (*cb) (int);", SomeSpace);
15304   verifyFormat("T A::operator()();", SomeSpace);
15305   // FIXME these tests regressed behaviour.
15306   // verifyFormat("X A::operator++ (T);", SomeSpace);
15307   verifyFormat("int x = int (y);", SomeSpace);
15308   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
15309 
15310   FormatStyle SpaceControlStatements = getLLVMStyle();
15311   SpaceControlStatements.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15312   SpaceControlStatements.SpaceBeforeParensOptions.AfterControlStatements = true;
15313 
15314   verifyFormat("while (true)\n"
15315                "  continue;",
15316                SpaceControlStatements);
15317   verifyFormat("if (true)\n"
15318                "  f();\n"
15319                "else if (true)\n"
15320                "  f();",
15321                SpaceControlStatements);
15322   verifyFormat("for (;;) {\n"
15323                "  do_something();\n"
15324                "}",
15325                SpaceControlStatements);
15326   verifyFormat("do {\n"
15327                "  do_something();\n"
15328                "} while (something());",
15329                SpaceControlStatements);
15330   verifyFormat("switch (x) {\n"
15331                "default:\n"
15332                "  break;\n"
15333                "}",
15334                SpaceControlStatements);
15335 
15336   FormatStyle SpaceFuncDecl = getLLVMStyle();
15337   SpaceFuncDecl.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15338   SpaceFuncDecl.SpaceBeforeParensOptions.AfterFunctionDeclarationName = true;
15339 
15340   verifyFormat("int f ();", SpaceFuncDecl);
15341   verifyFormat("void f(int a, T b) {}", SpaceFuncDecl);
15342   verifyFormat("A::A() : a(1) {}", SpaceFuncDecl);
15343   verifyFormat("void f () __attribute__((asdf));", SpaceFuncDecl);
15344   verifyFormat("#define A(x) x", SpaceFuncDecl);
15345   verifyFormat("#define A (x) x", SpaceFuncDecl);
15346   verifyFormat("#if defined(x)\n"
15347                "#endif",
15348                SpaceFuncDecl);
15349   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDecl);
15350   verifyFormat("size_t x = sizeof(x);", SpaceFuncDecl);
15351   verifyFormat("auto f (int x) -> decltype(x);", SpaceFuncDecl);
15352   verifyFormat("auto f (int x) -> typeof(x);", SpaceFuncDecl);
15353   verifyFormat("auto f (int x) -> _Atomic(x);", SpaceFuncDecl);
15354   verifyFormat("auto f (int x) -> __underlying_type(x);", SpaceFuncDecl);
15355   verifyFormat("int f (T x) noexcept(x.create());", SpaceFuncDecl);
15356   verifyFormat("alignas(128) char a[128];", SpaceFuncDecl);
15357   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDecl);
15358   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15359                SpaceFuncDecl);
15360   verifyFormat("int f () throw(Deprecated);", SpaceFuncDecl);
15361   verifyFormat("typedef void (*cb)(int);", SpaceFuncDecl);
15362   // FIXME these tests regressed behaviour.
15363   // verifyFormat("T A::operator() ();", SpaceFuncDecl);
15364   // verifyFormat("X A::operator++ (T);", SpaceFuncDecl);
15365   verifyFormat("T A::operator()() {}", SpaceFuncDecl);
15366   verifyFormat("auto lambda = []() { return 0; };", SpaceFuncDecl);
15367   verifyFormat("int x = int(y);", SpaceFuncDecl);
15368   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15369                SpaceFuncDecl);
15370 
15371   FormatStyle SpaceFuncDef = getLLVMStyle();
15372   SpaceFuncDef.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15373   SpaceFuncDef.SpaceBeforeParensOptions.AfterFunctionDefinitionName = true;
15374 
15375   verifyFormat("int f();", SpaceFuncDef);
15376   verifyFormat("void f (int a, T b) {}", SpaceFuncDef);
15377   verifyFormat("A::A() : a(1) {}", SpaceFuncDef);
15378   verifyFormat("void f() __attribute__((asdf));", SpaceFuncDef);
15379   verifyFormat("#define A(x) x", SpaceFuncDef);
15380   verifyFormat("#define A (x) x", SpaceFuncDef);
15381   verifyFormat("#if defined(x)\n"
15382                "#endif",
15383                SpaceFuncDef);
15384   verifyFormat("auto i = std::make_unique<int>(5);", SpaceFuncDef);
15385   verifyFormat("size_t x = sizeof(x);", SpaceFuncDef);
15386   verifyFormat("auto f(int x) -> decltype(x);", SpaceFuncDef);
15387   verifyFormat("auto f(int x) -> typeof(x);", SpaceFuncDef);
15388   verifyFormat("auto f(int x) -> _Atomic(x);", SpaceFuncDef);
15389   verifyFormat("auto f(int x) -> __underlying_type(x);", SpaceFuncDef);
15390   verifyFormat("int f(T x) noexcept(x.create());", SpaceFuncDef);
15391   verifyFormat("alignas(128) char a[128];", SpaceFuncDef);
15392   verifyFormat("size_t x = alignof(MyType);", SpaceFuncDef);
15393   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");",
15394                SpaceFuncDef);
15395   verifyFormat("int f() throw(Deprecated);", SpaceFuncDef);
15396   verifyFormat("typedef void (*cb)(int);", SpaceFuncDef);
15397   verifyFormat("T A::operator()();", SpaceFuncDef);
15398   verifyFormat("X A::operator++(T);", SpaceFuncDef);
15399   // verifyFormat("T A::operator() () {}", SpaceFuncDef);
15400   verifyFormat("auto lambda = [] () { return 0; };", SpaceFuncDef);
15401   verifyFormat("int x = int(y);", SpaceFuncDef);
15402   verifyFormat("M(std::size_t R, std::size_t C) : C(C), data(R) {}",
15403                SpaceFuncDef);
15404 
15405   FormatStyle SpaceIfMacros = getLLVMStyle();
15406   SpaceIfMacros.IfMacros.clear();
15407   SpaceIfMacros.IfMacros.push_back("MYIF");
15408   SpaceIfMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15409   SpaceIfMacros.SpaceBeforeParensOptions.AfterIfMacros = true;
15410   verifyFormat("MYIF (a)\n  return;", SpaceIfMacros);
15411   verifyFormat("MYIF (a)\n  return;\nelse MYIF (b)\n  return;", SpaceIfMacros);
15412   verifyFormat("MYIF (a)\n  return;\nelse\n  return;", SpaceIfMacros);
15413 
15414   FormatStyle SpaceForeachMacros = getLLVMStyle();
15415   EXPECT_EQ(SpaceForeachMacros.AllowShortBlocksOnASingleLine,
15416             FormatStyle::SBS_Never);
15417   EXPECT_EQ(SpaceForeachMacros.AllowShortLoopsOnASingleLine, false);
15418   SpaceForeachMacros.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15419   SpaceForeachMacros.SpaceBeforeParensOptions.AfterForeachMacros = true;
15420   verifyFormat("for (;;) {\n"
15421                "}",
15422                SpaceForeachMacros);
15423   verifyFormat("foreach (Item *item, itemlist) {\n"
15424                "}",
15425                SpaceForeachMacros);
15426   verifyFormat("Q_FOREACH (Item *item, itemlist) {\n"
15427                "}",
15428                SpaceForeachMacros);
15429   verifyFormat("BOOST_FOREACH (Item *item, itemlist) {\n"
15430                "}",
15431                SpaceForeachMacros);
15432   verifyFormat("UNKNOWN_FOREACH(Item *item, itemlist) {}", SpaceForeachMacros);
15433 
15434   FormatStyle SomeSpace2 = getLLVMStyle();
15435   SomeSpace2.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15436   SomeSpace2.SpaceBeforeParensOptions.BeforeNonEmptyParentheses = true;
15437   verifyFormat("[]() -> float {}", SomeSpace2);
15438   verifyFormat("[] (auto foo) {}", SomeSpace2);
15439   verifyFormat("[foo]() -> int {}", SomeSpace2);
15440   verifyFormat("int f();", SomeSpace2);
15441   verifyFormat("void f (int a, T b) {\n"
15442                "  while (true)\n"
15443                "    continue;\n"
15444                "}",
15445                SomeSpace2);
15446   verifyFormat("if (true)\n"
15447                "  f();\n"
15448                "else if (true)\n"
15449                "  f();",
15450                SomeSpace2);
15451   verifyFormat("do {\n"
15452                "  do_something();\n"
15453                "} while (something());",
15454                SomeSpace2);
15455   verifyFormat("switch (x) {\n"
15456                "default:\n"
15457                "  break;\n"
15458                "}",
15459                SomeSpace2);
15460   verifyFormat("A::A() : a (1) {}", SomeSpace2);
15461   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace2);
15462   verifyFormat("*(&a + 1);\n"
15463                "&((&a)[1]);\n"
15464                "a[(b + c) * d];\n"
15465                "(((a + 1) * 2) + 3) * 4;",
15466                SomeSpace2);
15467   verifyFormat("#define A(x) x", SomeSpace2);
15468   verifyFormat("#define A (x) x", SomeSpace2);
15469   verifyFormat("#if defined(x)\n"
15470                "#endif",
15471                SomeSpace2);
15472   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace2);
15473   verifyFormat("size_t x = sizeof (x);", SomeSpace2);
15474   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace2);
15475   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace2);
15476   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace2);
15477   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace2);
15478   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace2);
15479   verifyFormat("alignas (128) char a[128];", SomeSpace2);
15480   verifyFormat("size_t x = alignof (MyType);", SomeSpace2);
15481   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
15482                SomeSpace2);
15483   verifyFormat("int f() throw (Deprecated);", SomeSpace2);
15484   verifyFormat("typedef void (*cb) (int);", SomeSpace2);
15485   verifyFormat("T A::operator()();", SomeSpace2);
15486   // verifyFormat("X A::operator++ (T);", SomeSpace2);
15487   verifyFormat("int x = int (y);", SomeSpace2);
15488   verifyFormat("auto lambda = []() { return 0; };", SomeSpace2);
15489 
15490   FormatStyle SpaceAfterOverloadedOperator = getLLVMStyle();
15491   SpaceAfterOverloadedOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15492   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15493       .AfterOverloadedOperator = true;
15494 
15495   verifyFormat("auto operator++ () -> int;", SpaceAfterOverloadedOperator);
15496   verifyFormat("X A::operator++ ();", SpaceAfterOverloadedOperator);
15497   verifyFormat("some_object.operator++ ();", SpaceAfterOverloadedOperator);
15498   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15499 
15500   SpaceAfterOverloadedOperator.SpaceBeforeParensOptions
15501       .AfterOverloadedOperator = false;
15502 
15503   verifyFormat("auto operator++() -> int;", SpaceAfterOverloadedOperator);
15504   verifyFormat("X A::operator++();", SpaceAfterOverloadedOperator);
15505   verifyFormat("some_object.operator++();", SpaceAfterOverloadedOperator);
15506   verifyFormat("auto func() -> int;", SpaceAfterOverloadedOperator);
15507 
15508   auto SpaceAfterRequires = getLLVMStyle();
15509   SpaceAfterRequires.SpaceBeforeParens = FormatStyle::SBPO_Custom;
15510   EXPECT_FALSE(
15511       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause);
15512   EXPECT_FALSE(
15513       SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression);
15514   verifyFormat("void f(auto x)\n"
15515                "  requires requires(int i) { x + i; }\n"
15516                "{}",
15517                SpaceAfterRequires);
15518   verifyFormat("void f(auto x)\n"
15519                "  requires(requires(int i) { x + i; })\n"
15520                "{}",
15521                SpaceAfterRequires);
15522   verifyFormat("if (requires(int i) { x + i; })\n"
15523                "  return;",
15524                SpaceAfterRequires);
15525   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15526   verifyFormat("template <typename T>\n"
15527                "  requires(Foo<T>)\n"
15528                "class Bar;",
15529                SpaceAfterRequires);
15530 
15531   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15532   verifyFormat("void f(auto x)\n"
15533                "  requires requires(int i) { x + i; }\n"
15534                "{}",
15535                SpaceAfterRequires);
15536   verifyFormat("void f(auto x)\n"
15537                "  requires (requires(int i) { x + i; })\n"
15538                "{}",
15539                SpaceAfterRequires);
15540   verifyFormat("if (requires(int i) { x + i; })\n"
15541                "  return;",
15542                SpaceAfterRequires);
15543   verifyFormat("bool b = requires(int i) { x + i; };", SpaceAfterRequires);
15544   verifyFormat("template <typename T>\n"
15545                "  requires (Foo<T>)\n"
15546                "class Bar;",
15547                SpaceAfterRequires);
15548 
15549   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = false;
15550   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInExpression = true;
15551   verifyFormat("void f(auto x)\n"
15552                "  requires requires (int i) { x + i; }\n"
15553                "{}",
15554                SpaceAfterRequires);
15555   verifyFormat("void f(auto x)\n"
15556                "  requires(requires (int i) { x + i; })\n"
15557                "{}",
15558                SpaceAfterRequires);
15559   verifyFormat("if (requires (int i) { x + i; })\n"
15560                "  return;",
15561                SpaceAfterRequires);
15562   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15563   verifyFormat("template <typename T>\n"
15564                "  requires(Foo<T>)\n"
15565                "class Bar;",
15566                SpaceAfterRequires);
15567 
15568   SpaceAfterRequires.SpaceBeforeParensOptions.AfterRequiresInClause = true;
15569   verifyFormat("void f(auto x)\n"
15570                "  requires requires (int i) { x + i; }\n"
15571                "{}",
15572                SpaceAfterRequires);
15573   verifyFormat("void f(auto x)\n"
15574                "  requires (requires (int i) { x + i; })\n"
15575                "{}",
15576                SpaceAfterRequires);
15577   verifyFormat("if (requires (int i) { x + i; })\n"
15578                "  return;",
15579                SpaceAfterRequires);
15580   verifyFormat("bool b = requires (int i) { x + i; };", SpaceAfterRequires);
15581   verifyFormat("template <typename T>\n"
15582                "  requires (Foo<T>)\n"
15583                "class Bar;",
15584                SpaceAfterRequires);
15585 }
15586 
TEST_F(FormatTest,SpaceAfterLogicalNot)15587 TEST_F(FormatTest, SpaceAfterLogicalNot) {
15588   FormatStyle Spaces = getLLVMStyle();
15589   Spaces.SpaceAfterLogicalNot = true;
15590 
15591   verifyFormat("bool x = ! y", Spaces);
15592   verifyFormat("if (! isFailure())", Spaces);
15593   verifyFormat("if (! (a && b))", Spaces);
15594   verifyFormat("\"Error!\"", Spaces);
15595   verifyFormat("! ! x", Spaces);
15596 }
15597 
TEST_F(FormatTest,ConfigurableSpacesInParentheses)15598 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
15599   FormatStyle Spaces = getLLVMStyle();
15600 
15601   Spaces.SpacesInParentheses = true;
15602   verifyFormat("do_something( ::globalVar );", Spaces);
15603   verifyFormat("call( x, y, z );", Spaces);
15604   verifyFormat("call();", Spaces);
15605   verifyFormat("std::function<void( int, int )> callback;", Spaces);
15606   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
15607                Spaces);
15608   verifyFormat("while ( (bool)1 )\n"
15609                "  continue;",
15610                Spaces);
15611   verifyFormat("for ( ;; )\n"
15612                "  continue;",
15613                Spaces);
15614   verifyFormat("if ( true )\n"
15615                "  f();\n"
15616                "else if ( true )\n"
15617                "  f();",
15618                Spaces);
15619   verifyFormat("do {\n"
15620                "  do_something( (int)i );\n"
15621                "} while ( something() );",
15622                Spaces);
15623   verifyFormat("switch ( x ) {\n"
15624                "default:\n"
15625                "  break;\n"
15626                "}",
15627                Spaces);
15628 
15629   Spaces.SpacesInParentheses = false;
15630   Spaces.SpacesInCStyleCastParentheses = true;
15631   verifyFormat("Type *A = ( Type * )P;", Spaces);
15632   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
15633   verifyFormat("x = ( int32 )y;", Spaces);
15634   verifyFormat("int a = ( int )(2.0f);", Spaces);
15635   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
15636   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
15637   verifyFormat("#define x (( int )-1)", Spaces);
15638 
15639   // Run the first set of tests again with:
15640   Spaces.SpacesInParentheses = false;
15641   Spaces.SpaceInEmptyParentheses = true;
15642   Spaces.SpacesInCStyleCastParentheses = true;
15643   verifyFormat("call(x, y, z);", Spaces);
15644   verifyFormat("call( );", Spaces);
15645   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15646   verifyFormat("while (( bool )1)\n"
15647                "  continue;",
15648                Spaces);
15649   verifyFormat("for (;;)\n"
15650                "  continue;",
15651                Spaces);
15652   verifyFormat("if (true)\n"
15653                "  f( );\n"
15654                "else if (true)\n"
15655                "  f( );",
15656                Spaces);
15657   verifyFormat("do {\n"
15658                "  do_something(( int )i);\n"
15659                "} while (something( ));",
15660                Spaces);
15661   verifyFormat("switch (x) {\n"
15662                "default:\n"
15663                "  break;\n"
15664                "}",
15665                Spaces);
15666 
15667   // Run the first set of tests again with:
15668   Spaces.SpaceAfterCStyleCast = true;
15669   verifyFormat("call(x, y, z);", Spaces);
15670   verifyFormat("call( );", Spaces);
15671   verifyFormat("std::function<void(int, int)> callback;", Spaces);
15672   verifyFormat("while (( bool ) 1)\n"
15673                "  continue;",
15674                Spaces);
15675   verifyFormat("for (;;)\n"
15676                "  continue;",
15677                Spaces);
15678   verifyFormat("if (true)\n"
15679                "  f( );\n"
15680                "else if (true)\n"
15681                "  f( );",
15682                Spaces);
15683   verifyFormat("do {\n"
15684                "  do_something(( int ) i);\n"
15685                "} while (something( ));",
15686                Spaces);
15687   verifyFormat("switch (x) {\n"
15688                "default:\n"
15689                "  break;\n"
15690                "}",
15691                Spaces);
15692   verifyFormat("#define CONF_BOOL(x) ( bool * ) ( void * ) (x)", Spaces);
15693   verifyFormat("#define CONF_BOOL(x) ( bool * ) (x)", Spaces);
15694   verifyFormat("#define CONF_BOOL(x) ( bool ) (x)", Spaces);
15695   verifyFormat("bool *y = ( bool * ) ( void * ) (x);", Spaces);
15696   verifyFormat("bool *y = ( bool * ) (x);", Spaces);
15697 
15698   // Run subset of tests again with:
15699   Spaces.SpacesInCStyleCastParentheses = false;
15700   Spaces.SpaceAfterCStyleCast = true;
15701   verifyFormat("while ((bool) 1)\n"
15702                "  continue;",
15703                Spaces);
15704   verifyFormat("do {\n"
15705                "  do_something((int) i);\n"
15706                "} while (something( ));",
15707                Spaces);
15708 
15709   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
15710   verifyFormat("size_t idx = (size_t) a;", Spaces);
15711   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
15712   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15713   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15714   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15715   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15716   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (x)", Spaces);
15717   verifyFormat("#define CONF_BOOL(x) (bool *) (void *) (int) (x)", Spaces);
15718   verifyFormat("bool *y = (bool *) (void *) (x);", Spaces);
15719   verifyFormat("bool *y = (bool *) (void *) (int) (x);", Spaces);
15720   verifyFormat("bool *y = (bool *) (void *) (int) foo(x);", Spaces);
15721   Spaces.ColumnLimit = 80;
15722   Spaces.IndentWidth = 4;
15723   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15724   verifyFormat("void foo( ) {\n"
15725                "    size_t foo = (*(function))(\n"
15726                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15727                "BarrrrrrrrrrrrLong,\n"
15728                "        FoooooooooLooooong);\n"
15729                "}",
15730                Spaces);
15731   Spaces.SpaceAfterCStyleCast = false;
15732   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
15733   verifyFormat("size_t idx = (size_t)a;", Spaces);
15734   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
15735   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
15736   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
15737   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
15738   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
15739 
15740   verifyFormat("void foo( ) {\n"
15741                "    size_t foo = (*(function))(\n"
15742                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
15743                "BarrrrrrrrrrrrLong,\n"
15744                "        FoooooooooLooooong);\n"
15745                "}",
15746                Spaces);
15747 }
15748 
TEST_F(FormatTest,ConfigurableSpacesInSquareBrackets)15749 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
15750   verifyFormat("int a[5];");
15751   verifyFormat("a[3] += 42;");
15752 
15753   FormatStyle Spaces = getLLVMStyle();
15754   Spaces.SpacesInSquareBrackets = true;
15755   // Not lambdas.
15756   verifyFormat("int a[ 5 ];", Spaces);
15757   verifyFormat("a[ 3 ] += 42;", Spaces);
15758   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
15759   verifyFormat("double &operator[](int i) { return 0; }\n"
15760                "int i;",
15761                Spaces);
15762   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
15763   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
15764   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
15765   // Lambdas.
15766   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
15767   verifyFormat("return [ i, args... ] {};", Spaces);
15768   verifyFormat("int foo = [ &bar ]() {};", Spaces);
15769   verifyFormat("int foo = [ = ]() {};", Spaces);
15770   verifyFormat("int foo = [ & ]() {};", Spaces);
15771   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
15772   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
15773 }
15774 
TEST_F(FormatTest,ConfigurableSpaceBeforeBrackets)15775 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
15776   FormatStyle NoSpaceStyle = getLLVMStyle();
15777   verifyFormat("int a[5];", NoSpaceStyle);
15778   verifyFormat("a[3] += 42;", NoSpaceStyle);
15779 
15780   verifyFormat("int a[1];", NoSpaceStyle);
15781   verifyFormat("int 1 [a];", NoSpaceStyle);
15782   verifyFormat("int a[1][2];", NoSpaceStyle);
15783   verifyFormat("a[7] = 5;", NoSpaceStyle);
15784   verifyFormat("int a = (f())[23];", NoSpaceStyle);
15785   verifyFormat("f([] {})", NoSpaceStyle);
15786 
15787   FormatStyle Space = getLLVMStyle();
15788   Space.SpaceBeforeSquareBrackets = true;
15789   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
15790   verifyFormat("return [i, args...] {};", Space);
15791 
15792   verifyFormat("int a [5];", Space);
15793   verifyFormat("a [3] += 42;", Space);
15794   verifyFormat("constexpr char hello []{\"hello\"};", Space);
15795   verifyFormat("double &operator[](int i) { return 0; }\n"
15796                "int i;",
15797                Space);
15798   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
15799   verifyFormat("int i = a [a][a]->f();", Space);
15800   verifyFormat("int i = (*b) [a]->f();", Space);
15801 
15802   verifyFormat("int a [1];", Space);
15803   verifyFormat("int 1 [a];", Space);
15804   verifyFormat("int a [1][2];", Space);
15805   verifyFormat("a [7] = 5;", Space);
15806   verifyFormat("int a = (f()) [23];", Space);
15807   verifyFormat("f([] {})", Space);
15808 }
15809 
TEST_F(FormatTest,ConfigurableSpaceBeforeAssignmentOperators)15810 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
15811   verifyFormat("int a = 5;");
15812   verifyFormat("a += 42;");
15813   verifyFormat("a or_eq 8;");
15814 
15815   FormatStyle Spaces = getLLVMStyle();
15816   Spaces.SpaceBeforeAssignmentOperators = false;
15817   verifyFormat("int a= 5;", Spaces);
15818   verifyFormat("a+= 42;", Spaces);
15819   verifyFormat("a or_eq 8;", Spaces);
15820 }
15821 
TEST_F(FormatTest,ConfigurableSpaceBeforeColon)15822 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
15823   verifyFormat("class Foo : public Bar {};");
15824   verifyFormat("Foo::Foo() : foo(1) {}");
15825   verifyFormat("for (auto a : b) {\n}");
15826   verifyFormat("int x = a ? b : c;");
15827   verifyFormat("{\n"
15828                "label0:\n"
15829                "  int x = 0;\n"
15830                "}");
15831   verifyFormat("switch (x) {\n"
15832                "case 1:\n"
15833                "default:\n"
15834                "}");
15835   verifyFormat("switch (allBraces) {\n"
15836                "case 1: {\n"
15837                "  break;\n"
15838                "}\n"
15839                "case 2: {\n"
15840                "  [[fallthrough]];\n"
15841                "}\n"
15842                "default: {\n"
15843                "  break;\n"
15844                "}\n"
15845                "}");
15846 
15847   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
15848   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
15849   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
15850   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
15851   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
15852   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
15853   verifyFormat("{\n"
15854                "label1:\n"
15855                "  int x = 0;\n"
15856                "}",
15857                CtorInitializerStyle);
15858   verifyFormat("switch (x) {\n"
15859                "case 1:\n"
15860                "default:\n"
15861                "}",
15862                CtorInitializerStyle);
15863   verifyFormat("switch (allBraces) {\n"
15864                "case 1: {\n"
15865                "  break;\n"
15866                "}\n"
15867                "case 2: {\n"
15868                "  [[fallthrough]];\n"
15869                "}\n"
15870                "default: {\n"
15871                "  break;\n"
15872                "}\n"
15873                "}",
15874                CtorInitializerStyle);
15875   CtorInitializerStyle.BreakConstructorInitializers =
15876       FormatStyle::BCIS_AfterColon;
15877   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
15878                "    aaaaaaaaaaaaaaaa(1),\n"
15879                "    bbbbbbbbbbbbbbbb(2) {}",
15880                CtorInitializerStyle);
15881   CtorInitializerStyle.BreakConstructorInitializers =
15882       FormatStyle::BCIS_BeforeComma;
15883   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15884                "    : aaaaaaaaaaaaaaaa(1)\n"
15885                "    , bbbbbbbbbbbbbbbb(2) {}",
15886                CtorInitializerStyle);
15887   CtorInitializerStyle.BreakConstructorInitializers =
15888       FormatStyle::BCIS_BeforeColon;
15889   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15890                "    : aaaaaaaaaaaaaaaa(1),\n"
15891                "      bbbbbbbbbbbbbbbb(2) {}",
15892                CtorInitializerStyle);
15893   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
15894   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
15895                ": aaaaaaaaaaaaaaaa(1),\n"
15896                "  bbbbbbbbbbbbbbbb(2) {}",
15897                CtorInitializerStyle);
15898 
15899   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
15900   InheritanceStyle.SpaceBeforeInheritanceColon = false;
15901   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
15902   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
15903   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
15904   verifyFormat("int x = a ? b : c;", InheritanceStyle);
15905   verifyFormat("{\n"
15906                "label2:\n"
15907                "  int x = 0;\n"
15908                "}",
15909                InheritanceStyle);
15910   verifyFormat("switch (x) {\n"
15911                "case 1:\n"
15912                "default:\n"
15913                "}",
15914                InheritanceStyle);
15915   verifyFormat("switch (allBraces) {\n"
15916                "case 1: {\n"
15917                "  break;\n"
15918                "}\n"
15919                "case 2: {\n"
15920                "  [[fallthrough]];\n"
15921                "}\n"
15922                "default: {\n"
15923                "  break;\n"
15924                "}\n"
15925                "}",
15926                InheritanceStyle);
15927   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
15928   verifyFormat("class Foooooooooooooooooooooo\n"
15929                "    : public aaaaaaaaaaaaaaaaaa,\n"
15930                "      public bbbbbbbbbbbbbbbbbb {\n"
15931                "}",
15932                InheritanceStyle);
15933   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
15934   verifyFormat("class Foooooooooooooooooooooo:\n"
15935                "    public aaaaaaaaaaaaaaaaaa,\n"
15936                "    public bbbbbbbbbbbbbbbbbb {\n"
15937                "}",
15938                InheritanceStyle);
15939   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
15940   verifyFormat("class Foooooooooooooooooooooo\n"
15941                "    : public aaaaaaaaaaaaaaaaaa\n"
15942                "    , public bbbbbbbbbbbbbbbbbb {\n"
15943                "}",
15944                InheritanceStyle);
15945   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15946   verifyFormat("class Foooooooooooooooooooooo\n"
15947                "    : public aaaaaaaaaaaaaaaaaa,\n"
15948                "      public bbbbbbbbbbbbbbbbbb {\n"
15949                "}",
15950                InheritanceStyle);
15951   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
15952   verifyFormat("class Foooooooooooooooooooooo\n"
15953                ": public aaaaaaaaaaaaaaaaaa,\n"
15954                "  public bbbbbbbbbbbbbbbbbb {}",
15955                InheritanceStyle);
15956 
15957   FormatStyle ForLoopStyle = getLLVMStyle();
15958   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
15959   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
15960   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
15961   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
15962   verifyFormat("int x = a ? b : c;", ForLoopStyle);
15963   verifyFormat("{\n"
15964                "label2:\n"
15965                "  int x = 0;\n"
15966                "}",
15967                ForLoopStyle);
15968   verifyFormat("switch (x) {\n"
15969                "case 1:\n"
15970                "default:\n"
15971                "}",
15972                ForLoopStyle);
15973   verifyFormat("switch (allBraces) {\n"
15974                "case 1: {\n"
15975                "  break;\n"
15976                "}\n"
15977                "case 2: {\n"
15978                "  [[fallthrough]];\n"
15979                "}\n"
15980                "default: {\n"
15981                "  break;\n"
15982                "}\n"
15983                "}",
15984                ForLoopStyle);
15985 
15986   FormatStyle CaseStyle = getLLVMStyle();
15987   CaseStyle.SpaceBeforeCaseColon = true;
15988   verifyFormat("class Foo : public Bar {};", CaseStyle);
15989   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
15990   verifyFormat("for (auto a : b) {\n}", CaseStyle);
15991   verifyFormat("int x = a ? b : c;", CaseStyle);
15992   verifyFormat("switch (x) {\n"
15993                "case 1 :\n"
15994                "default :\n"
15995                "}",
15996                CaseStyle);
15997   verifyFormat("switch (allBraces) {\n"
15998                "case 1 : {\n"
15999                "  break;\n"
16000                "}\n"
16001                "case 2 : {\n"
16002                "  [[fallthrough]];\n"
16003                "}\n"
16004                "default : {\n"
16005                "  break;\n"
16006                "}\n"
16007                "}",
16008                CaseStyle);
16009 
16010   FormatStyle NoSpaceStyle = getLLVMStyle();
16011   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
16012   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
16013   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
16014   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
16015   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
16016   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
16017   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
16018   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
16019   verifyFormat("{\n"
16020                "label3:\n"
16021                "  int x = 0;\n"
16022                "}",
16023                NoSpaceStyle);
16024   verifyFormat("switch (x) {\n"
16025                "case 1:\n"
16026                "default:\n"
16027                "}",
16028                NoSpaceStyle);
16029   verifyFormat("switch (allBraces) {\n"
16030                "case 1: {\n"
16031                "  break;\n"
16032                "}\n"
16033                "case 2: {\n"
16034                "  [[fallthrough]];\n"
16035                "}\n"
16036                "default: {\n"
16037                "  break;\n"
16038                "}\n"
16039                "}",
16040                NoSpaceStyle);
16041 
16042   FormatStyle InvertedSpaceStyle = getLLVMStyle();
16043   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
16044   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
16045   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
16046   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
16047   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
16048   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
16049   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
16050   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
16051   verifyFormat("{\n"
16052                "label3:\n"
16053                "  int x = 0;\n"
16054                "}",
16055                InvertedSpaceStyle);
16056   verifyFormat("switch (x) {\n"
16057                "case 1 :\n"
16058                "case 2 : {\n"
16059                "  break;\n"
16060                "}\n"
16061                "default :\n"
16062                "  break;\n"
16063                "}",
16064                InvertedSpaceStyle);
16065   verifyFormat("switch (allBraces) {\n"
16066                "case 1 : {\n"
16067                "  break;\n"
16068                "}\n"
16069                "case 2 : {\n"
16070                "  [[fallthrough]];\n"
16071                "}\n"
16072                "default : {\n"
16073                "  break;\n"
16074                "}\n"
16075                "}",
16076                InvertedSpaceStyle);
16077 }
16078 
TEST_F(FormatTest,ConfigurableSpaceAroundPointerQualifiers)16079 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
16080   FormatStyle Style = getLLVMStyle();
16081 
16082   Style.PointerAlignment = FormatStyle::PAS_Left;
16083   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
16084   verifyFormat("void* const* x = NULL;", Style);
16085 
16086 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
16087   do {                                                                         \
16088     Style.PointerAlignment = FormatStyle::Pointers;                            \
16089     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
16090     verifyFormat(Code, Style);                                                 \
16091   } while (false)
16092 
16093   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
16094   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
16095   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
16096 
16097   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
16098   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
16099   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
16100 
16101   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
16102   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
16103   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
16104 
16105   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
16106   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
16107   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
16108 
16109   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
16110   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
16111                         SAPQ_Default);
16112   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
16113                         SAPQ_Default);
16114 
16115   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
16116   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
16117                         SAPQ_Before);
16118   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
16119                         SAPQ_Before);
16120 
16121   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
16122   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
16123   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
16124                         SAPQ_After);
16125 
16126   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
16127   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
16128   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
16129 
16130 #undef verifyQualifierSpaces
16131 
16132   FormatStyle Spaces = getLLVMStyle();
16133   Spaces.AttributeMacros.push_back("qualified");
16134   Spaces.PointerAlignment = FormatStyle::PAS_Right;
16135   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
16136   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
16137   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
16138   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
16139   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
16140   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16141   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
16142   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
16143   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
16144   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
16145   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
16146   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16147 
16148   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
16149   Spaces.PointerAlignment = FormatStyle::PAS_Left;
16150   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
16151   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
16152   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
16153   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
16154   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
16155   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16156   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
16157   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
16158   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
16159   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
16160   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
16161   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
16162   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16163 
16164   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
16165   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
16166   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
16167   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
16168   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
16169   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
16170   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
16171   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
16172 }
16173 
TEST_F(FormatTest,AlignConsecutiveMacros)16174 TEST_F(FormatTest, AlignConsecutiveMacros) {
16175   FormatStyle Style = getLLVMStyle();
16176   Style.AlignConsecutiveAssignments.Enabled = true;
16177   Style.AlignConsecutiveDeclarations.Enabled = true;
16178 
16179   verifyFormat("#define a 3\n"
16180                "#define bbbb 4\n"
16181                "#define ccc (5)",
16182                Style);
16183 
16184   verifyFormat("#define f(x) (x * x)\n"
16185                "#define fff(x, y, z) (x * y + z)\n"
16186                "#define ffff(x, y) (x - y)",
16187                Style);
16188 
16189   verifyFormat("#define foo(x, y) (x + y)\n"
16190                "#define bar (5, 6)(2 + 2)",
16191                Style);
16192 
16193   verifyFormat("#define a 3\n"
16194                "#define bbbb 4\n"
16195                "#define ccc (5)\n"
16196                "#define f(x) (x * x)\n"
16197                "#define fff(x, y, z) (x * y + z)\n"
16198                "#define ffff(x, y) (x - y)",
16199                Style);
16200 
16201   Style.AlignConsecutiveMacros.Enabled = true;
16202   verifyFormat("#define a    3\n"
16203                "#define bbbb 4\n"
16204                "#define ccc  (5)",
16205                Style);
16206 
16207   verifyFormat("#define true  1\n"
16208                "#define false 0",
16209                Style);
16210 
16211   verifyFormat("#define f(x)         (x * x)\n"
16212                "#define fff(x, y, z) (x * y + z)\n"
16213                "#define ffff(x, y)   (x - y)",
16214                Style);
16215 
16216   verifyFormat("#define foo(x, y) (x + y)\n"
16217                "#define bar       (5, 6)(2 + 2)",
16218                Style);
16219 
16220   verifyFormat("#define a            3\n"
16221                "#define bbbb         4\n"
16222                "#define ccc          (5)\n"
16223                "#define f(x)         (x * x)\n"
16224                "#define fff(x, y, z) (x * y + z)\n"
16225                "#define ffff(x, y)   (x - y)",
16226                Style);
16227 
16228   verifyFormat("#define a         5\n"
16229                "#define foo(x, y) (x + y)\n"
16230                "#define CCC       (6)\n"
16231                "auto lambda = []() {\n"
16232                "  auto  ii = 0;\n"
16233                "  float j  = 0;\n"
16234                "  return 0;\n"
16235                "};\n"
16236                "int   i  = 0;\n"
16237                "float i2 = 0;\n"
16238                "auto  v  = type{\n"
16239                "    i = 1,   //\n"
16240                "    (i = 2), //\n"
16241                "    i = 3    //\n"
16242                "};",
16243                Style);
16244 
16245   Style.AlignConsecutiveMacros.Enabled = false;
16246   Style.ColumnLimit = 20;
16247 
16248   verifyFormat("#define a          \\\n"
16249                "  \"aabbbbbbbbbbbb\"\n"
16250                "#define D          \\\n"
16251                "  \"aabbbbbbbbbbbb\" \\\n"
16252                "  \"ccddeeeeeeeee\"\n"
16253                "#define B          \\\n"
16254                "  \"QQQQQQQQQQQQQ\"  \\\n"
16255                "  \"FFFFFFFFFFFFF\"  \\\n"
16256                "  \"LLLLLLLL\"\n",
16257                Style);
16258 
16259   Style.AlignConsecutiveMacros.Enabled = true;
16260   verifyFormat("#define a          \\\n"
16261                "  \"aabbbbbbbbbbbb\"\n"
16262                "#define D          \\\n"
16263                "  \"aabbbbbbbbbbbb\" \\\n"
16264                "  \"ccddeeeeeeeee\"\n"
16265                "#define B          \\\n"
16266                "  \"QQQQQQQQQQQQQ\"  \\\n"
16267                "  \"FFFFFFFFFFFFF\"  \\\n"
16268                "  \"LLLLLLLL\"\n",
16269                Style);
16270 
16271   // Test across comments
16272   Style.MaxEmptyLinesToKeep = 10;
16273   Style.ReflowComments = false;
16274   Style.AlignConsecutiveMacros.AcrossComments = true;
16275   EXPECT_EQ("#define a    3\n"
16276             "// line comment\n"
16277             "#define bbbb 4\n"
16278             "#define ccc  (5)",
16279             format("#define a 3\n"
16280                    "// line comment\n"
16281                    "#define bbbb 4\n"
16282                    "#define ccc (5)",
16283                    Style));
16284 
16285   EXPECT_EQ("#define a    3\n"
16286             "/* block comment */\n"
16287             "#define bbbb 4\n"
16288             "#define ccc  (5)",
16289             format("#define a  3\n"
16290                    "/* block comment */\n"
16291                    "#define bbbb 4\n"
16292                    "#define ccc (5)",
16293                    Style));
16294 
16295   EXPECT_EQ("#define a    3\n"
16296             "/* multi-line *\n"
16297             " * block comment */\n"
16298             "#define bbbb 4\n"
16299             "#define ccc  (5)",
16300             format("#define a 3\n"
16301                    "/* multi-line *\n"
16302                    " * block comment */\n"
16303                    "#define bbbb 4\n"
16304                    "#define ccc (5)",
16305                    Style));
16306 
16307   EXPECT_EQ("#define a    3\n"
16308             "// multi-line line comment\n"
16309             "//\n"
16310             "#define bbbb 4\n"
16311             "#define ccc  (5)",
16312             format("#define a  3\n"
16313                    "// multi-line line comment\n"
16314                    "//\n"
16315                    "#define bbbb 4\n"
16316                    "#define ccc (5)",
16317                    Style));
16318 
16319   EXPECT_EQ("#define a 3\n"
16320             "// empty lines still break.\n"
16321             "\n"
16322             "#define bbbb 4\n"
16323             "#define ccc  (5)",
16324             format("#define a     3\n"
16325                    "// empty lines still break.\n"
16326                    "\n"
16327                    "#define bbbb     4\n"
16328                    "#define ccc  (5)",
16329                    Style));
16330 
16331   // Test across empty lines
16332   Style.AlignConsecutiveMacros.AcrossComments = false;
16333   Style.AlignConsecutiveMacros.AcrossEmptyLines = true;
16334   EXPECT_EQ("#define a    3\n"
16335             "\n"
16336             "#define bbbb 4\n"
16337             "#define ccc  (5)",
16338             format("#define a 3\n"
16339                    "\n"
16340                    "#define bbbb 4\n"
16341                    "#define ccc (5)",
16342                    Style));
16343 
16344   EXPECT_EQ("#define a    3\n"
16345             "\n"
16346             "\n"
16347             "\n"
16348             "#define bbbb 4\n"
16349             "#define ccc  (5)",
16350             format("#define a        3\n"
16351                    "\n"
16352                    "\n"
16353                    "\n"
16354                    "#define bbbb 4\n"
16355                    "#define ccc (5)",
16356                    Style));
16357 
16358   EXPECT_EQ("#define a 3\n"
16359             "// comments should break alignment\n"
16360             "//\n"
16361             "#define bbbb 4\n"
16362             "#define ccc  (5)",
16363             format("#define a        3\n"
16364                    "// comments should break alignment\n"
16365                    "//\n"
16366                    "#define bbbb 4\n"
16367                    "#define ccc (5)",
16368                    Style));
16369 
16370   // Test across empty lines and comments
16371   Style.AlignConsecutiveMacros.AcrossComments = true;
16372   verifyFormat("#define a    3\n"
16373                "\n"
16374                "// line comment\n"
16375                "#define bbbb 4\n"
16376                "#define ccc  (5)",
16377                Style);
16378 
16379   EXPECT_EQ("#define a    3\n"
16380             "\n"
16381             "\n"
16382             "/* multi-line *\n"
16383             " * block comment */\n"
16384             "\n"
16385             "\n"
16386             "#define bbbb 4\n"
16387             "#define ccc  (5)",
16388             format("#define a 3\n"
16389                    "\n"
16390                    "\n"
16391                    "/* multi-line *\n"
16392                    " * block comment */\n"
16393                    "\n"
16394                    "\n"
16395                    "#define bbbb 4\n"
16396                    "#define ccc (5)",
16397                    Style));
16398 
16399   EXPECT_EQ("#define a    3\n"
16400             "\n"
16401             "\n"
16402             "/* multi-line *\n"
16403             " * block comment */\n"
16404             "\n"
16405             "\n"
16406             "#define bbbb 4\n"
16407             "#define ccc  (5)",
16408             format("#define a 3\n"
16409                    "\n"
16410                    "\n"
16411                    "/* multi-line *\n"
16412                    " * block comment */\n"
16413                    "\n"
16414                    "\n"
16415                    "#define bbbb 4\n"
16416                    "#define ccc       (5)",
16417                    Style));
16418 }
16419 
TEST_F(FormatTest,AlignConsecutiveAssignmentsAcrossEmptyLines)16420 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
16421   FormatStyle Alignment = getLLVMStyle();
16422   Alignment.AlignConsecutiveMacros.Enabled = true;
16423   Alignment.AlignConsecutiveAssignments.Enabled = true;
16424   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16425 
16426   Alignment.MaxEmptyLinesToKeep = 10;
16427   /* Test alignment across empty lines */
16428   EXPECT_EQ("int a           = 5;\n"
16429             "\n"
16430             "int oneTwoThree = 123;",
16431             format("int a       = 5;\n"
16432                    "\n"
16433                    "int oneTwoThree= 123;",
16434                    Alignment));
16435   EXPECT_EQ("int a           = 5;\n"
16436             "int one         = 1;\n"
16437             "\n"
16438             "int oneTwoThree = 123;",
16439             format("int a = 5;\n"
16440                    "int one = 1;\n"
16441                    "\n"
16442                    "int oneTwoThree = 123;",
16443                    Alignment));
16444   EXPECT_EQ("int a           = 5;\n"
16445             "int one         = 1;\n"
16446             "\n"
16447             "int oneTwoThree = 123;\n"
16448             "int oneTwo      = 12;",
16449             format("int a = 5;\n"
16450                    "int one = 1;\n"
16451                    "\n"
16452                    "int oneTwoThree = 123;\n"
16453                    "int oneTwo = 12;",
16454                    Alignment));
16455 
16456   /* Test across comments */
16457   EXPECT_EQ("int a = 5;\n"
16458             "/* block comment */\n"
16459             "int oneTwoThree = 123;",
16460             format("int a = 5;\n"
16461                    "/* block comment */\n"
16462                    "int oneTwoThree=123;",
16463                    Alignment));
16464 
16465   EXPECT_EQ("int a = 5;\n"
16466             "// line comment\n"
16467             "int oneTwoThree = 123;",
16468             format("int a = 5;\n"
16469                    "// line comment\n"
16470                    "int oneTwoThree=123;",
16471                    Alignment));
16472 
16473   /* Test across comments and newlines */
16474   EXPECT_EQ("int a = 5;\n"
16475             "\n"
16476             "/* block comment */\n"
16477             "int oneTwoThree = 123;",
16478             format("int a = 5;\n"
16479                    "\n"
16480                    "/* block comment */\n"
16481                    "int oneTwoThree=123;",
16482                    Alignment));
16483 
16484   EXPECT_EQ("int a = 5;\n"
16485             "\n"
16486             "// line comment\n"
16487             "int oneTwoThree = 123;",
16488             format("int a = 5;\n"
16489                    "\n"
16490                    "// line comment\n"
16491                    "int oneTwoThree=123;",
16492                    Alignment));
16493 }
16494 
TEST_F(FormatTest,AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments)16495 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
16496   FormatStyle Alignment = getLLVMStyle();
16497   Alignment.AlignConsecutiveDeclarations.Enabled = true;
16498   Alignment.AlignConsecutiveDeclarations.AcrossEmptyLines = true;
16499   Alignment.AlignConsecutiveDeclarations.AcrossComments = true;
16500 
16501   Alignment.MaxEmptyLinesToKeep = 10;
16502   /* Test alignment across empty lines */
16503   EXPECT_EQ("int         a = 5;\n"
16504             "\n"
16505             "float const oneTwoThree = 123;",
16506             format("int a = 5;\n"
16507                    "\n"
16508                    "float const oneTwoThree = 123;",
16509                    Alignment));
16510   EXPECT_EQ("int         a = 5;\n"
16511             "float const one = 1;\n"
16512             "\n"
16513             "int         oneTwoThree = 123;",
16514             format("int a = 5;\n"
16515                    "float const one = 1;\n"
16516                    "\n"
16517                    "int oneTwoThree = 123;",
16518                    Alignment));
16519 
16520   /* Test across comments */
16521   EXPECT_EQ("float const a = 5;\n"
16522             "/* block comment */\n"
16523             "int         oneTwoThree = 123;",
16524             format("float const a = 5;\n"
16525                    "/* block comment */\n"
16526                    "int oneTwoThree=123;",
16527                    Alignment));
16528 
16529   EXPECT_EQ("float const a = 5;\n"
16530             "// line comment\n"
16531             "int         oneTwoThree = 123;",
16532             format("float const a = 5;\n"
16533                    "// line comment\n"
16534                    "int oneTwoThree=123;",
16535                    Alignment));
16536 
16537   /* Test across comments and newlines */
16538   EXPECT_EQ("float const a = 5;\n"
16539             "\n"
16540             "/* block comment */\n"
16541             "int         oneTwoThree = 123;",
16542             format("float const a = 5;\n"
16543                    "\n"
16544                    "/* block comment */\n"
16545                    "int         oneTwoThree=123;",
16546                    Alignment));
16547 
16548   EXPECT_EQ("float const a = 5;\n"
16549             "\n"
16550             "// line comment\n"
16551             "int         oneTwoThree = 123;",
16552             format("float const a = 5;\n"
16553                    "\n"
16554                    "// line comment\n"
16555                    "int oneTwoThree=123;",
16556                    Alignment));
16557 }
16558 
TEST_F(FormatTest,AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments)16559 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
16560   FormatStyle Alignment = getLLVMStyle();
16561   Alignment.AlignConsecutiveBitFields.Enabled = true;
16562   Alignment.AlignConsecutiveBitFields.AcrossEmptyLines = true;
16563   Alignment.AlignConsecutiveBitFields.AcrossComments = true;
16564 
16565   Alignment.MaxEmptyLinesToKeep = 10;
16566   /* Test alignment across empty lines */
16567   EXPECT_EQ("int a            : 5;\n"
16568             "\n"
16569             "int longbitfield : 6;",
16570             format("int a : 5;\n"
16571                    "\n"
16572                    "int longbitfield : 6;",
16573                    Alignment));
16574   EXPECT_EQ("int a            : 5;\n"
16575             "int one          : 1;\n"
16576             "\n"
16577             "int longbitfield : 6;",
16578             format("int a : 5;\n"
16579                    "int one : 1;\n"
16580                    "\n"
16581                    "int longbitfield : 6;",
16582                    Alignment));
16583 
16584   /* Test across comments */
16585   EXPECT_EQ("int a            : 5;\n"
16586             "/* block comment */\n"
16587             "int longbitfield : 6;",
16588             format("int a : 5;\n"
16589                    "/* block comment */\n"
16590                    "int longbitfield : 6;",
16591                    Alignment));
16592   EXPECT_EQ("int a            : 5;\n"
16593             "int one          : 1;\n"
16594             "// line comment\n"
16595             "int longbitfield : 6;",
16596             format("int a : 5;\n"
16597                    "int one : 1;\n"
16598                    "// line comment\n"
16599                    "int longbitfield : 6;",
16600                    Alignment));
16601 
16602   /* Test across comments and newlines */
16603   EXPECT_EQ("int a            : 5;\n"
16604             "/* block comment */\n"
16605             "\n"
16606             "int longbitfield : 6;",
16607             format("int a : 5;\n"
16608                    "/* block comment */\n"
16609                    "\n"
16610                    "int longbitfield : 6;",
16611                    Alignment));
16612   EXPECT_EQ("int a            : 5;\n"
16613             "int one          : 1;\n"
16614             "\n"
16615             "// line comment\n"
16616             "\n"
16617             "int longbitfield : 6;",
16618             format("int a : 5;\n"
16619                    "int one : 1;\n"
16620                    "\n"
16621                    "// line comment \n"
16622                    "\n"
16623                    "int longbitfield : 6;",
16624                    Alignment));
16625 }
16626 
TEST_F(FormatTest,AlignConsecutiveAssignmentsAcrossComments)16627 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
16628   FormatStyle Alignment = getLLVMStyle();
16629   Alignment.AlignConsecutiveMacros.Enabled = true;
16630   Alignment.AlignConsecutiveAssignments.Enabled = true;
16631   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16632 
16633   Alignment.MaxEmptyLinesToKeep = 10;
16634   /* Test alignment across empty lines */
16635   EXPECT_EQ("int a = 5;\n"
16636             "\n"
16637             "int oneTwoThree = 123;",
16638             format("int a       = 5;\n"
16639                    "\n"
16640                    "int oneTwoThree= 123;",
16641                    Alignment));
16642   EXPECT_EQ("int a   = 5;\n"
16643             "int one = 1;\n"
16644             "\n"
16645             "int oneTwoThree = 123;",
16646             format("int a = 5;\n"
16647                    "int one = 1;\n"
16648                    "\n"
16649                    "int oneTwoThree = 123;",
16650                    Alignment));
16651 
16652   /* Test across comments */
16653   EXPECT_EQ("int a           = 5;\n"
16654             "/* block comment */\n"
16655             "int oneTwoThree = 123;",
16656             format("int a = 5;\n"
16657                    "/* block comment */\n"
16658                    "int oneTwoThree=123;",
16659                    Alignment));
16660 
16661   EXPECT_EQ("int a           = 5;\n"
16662             "// line comment\n"
16663             "int oneTwoThree = 123;",
16664             format("int a = 5;\n"
16665                    "// line comment\n"
16666                    "int oneTwoThree=123;",
16667                    Alignment));
16668 
16669   EXPECT_EQ("int a           = 5;\n"
16670             "/*\n"
16671             " * multi-line block comment\n"
16672             " */\n"
16673             "int oneTwoThree = 123;",
16674             format("int a = 5;\n"
16675                    "/*\n"
16676                    " * multi-line block comment\n"
16677                    " */\n"
16678                    "int oneTwoThree=123;",
16679                    Alignment));
16680 
16681   EXPECT_EQ("int a           = 5;\n"
16682             "//\n"
16683             "// multi-line line comment\n"
16684             "//\n"
16685             "int oneTwoThree = 123;",
16686             format("int a = 5;\n"
16687                    "//\n"
16688                    "// multi-line line comment\n"
16689                    "//\n"
16690                    "int oneTwoThree=123;",
16691                    Alignment));
16692 
16693   /* Test across comments and newlines */
16694   EXPECT_EQ("int a = 5;\n"
16695             "\n"
16696             "/* block comment */\n"
16697             "int oneTwoThree = 123;",
16698             format("int a = 5;\n"
16699                    "\n"
16700                    "/* block comment */\n"
16701                    "int oneTwoThree=123;",
16702                    Alignment));
16703 
16704   EXPECT_EQ("int a = 5;\n"
16705             "\n"
16706             "// line comment\n"
16707             "int oneTwoThree = 123;",
16708             format("int a = 5;\n"
16709                    "\n"
16710                    "// line comment\n"
16711                    "int oneTwoThree=123;",
16712                    Alignment));
16713 }
16714 
TEST_F(FormatTest,AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments)16715 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
16716   FormatStyle Alignment = getLLVMStyle();
16717   Alignment.AlignConsecutiveMacros.Enabled = true;
16718   Alignment.AlignConsecutiveAssignments.Enabled = true;
16719   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
16720   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
16721   verifyFormat("int a           = 5;\n"
16722                "int oneTwoThree = 123;",
16723                Alignment);
16724   verifyFormat("int a           = method();\n"
16725                "int oneTwoThree = 133;",
16726                Alignment);
16727   verifyFormat("a &= 5;\n"
16728                "bcd *= 5;\n"
16729                "ghtyf += 5;\n"
16730                "dvfvdb -= 5;\n"
16731                "a /= 5;\n"
16732                "vdsvsv %= 5;\n"
16733                "sfdbddfbdfbb ^= 5;\n"
16734                "dvsdsv |= 5;\n"
16735                "int dsvvdvsdvvv = 123;",
16736                Alignment);
16737   verifyFormat("int i = 1, j = 10;\n"
16738                "something = 2000;",
16739                Alignment);
16740   verifyFormat("something = 2000;\n"
16741                "int i = 1, j = 10;\n",
16742                Alignment);
16743   verifyFormat("something = 2000;\n"
16744                "another   = 911;\n"
16745                "int i = 1, j = 10;\n"
16746                "oneMore = 1;\n"
16747                "i       = 2;",
16748                Alignment);
16749   verifyFormat("int a   = 5;\n"
16750                "int one = 1;\n"
16751                "method();\n"
16752                "int oneTwoThree = 123;\n"
16753                "int oneTwo      = 12;",
16754                Alignment);
16755   verifyFormat("int oneTwoThree = 123;\n"
16756                "int oneTwo      = 12;\n"
16757                "method();\n",
16758                Alignment);
16759   verifyFormat("int oneTwoThree = 123; // comment\n"
16760                "int oneTwo      = 12;  // comment",
16761                Alignment);
16762 
16763   // Bug 25167
16764   /* Uncomment when fixed
16765     verifyFormat("#if A\n"
16766                  "#else\n"
16767                  "int aaaaaaaa = 12;\n"
16768                  "#endif\n"
16769                  "#if B\n"
16770                  "#else\n"
16771                  "int a = 12;\n"
16772                  "#endif\n",
16773                  Alignment);
16774     verifyFormat("enum foo {\n"
16775                  "#if A\n"
16776                  "#else\n"
16777                  "  aaaaaaaa = 12;\n"
16778                  "#endif\n"
16779                  "#if B\n"
16780                  "#else\n"
16781                  "  a = 12;\n"
16782                  "#endif\n"
16783                  "};\n",
16784                  Alignment);
16785   */
16786 
16787   Alignment.MaxEmptyLinesToKeep = 10;
16788   /* Test alignment across empty lines */
16789   EXPECT_EQ("int a           = 5;\n"
16790             "\n"
16791             "int oneTwoThree = 123;",
16792             format("int a       = 5;\n"
16793                    "\n"
16794                    "int oneTwoThree= 123;",
16795                    Alignment));
16796   EXPECT_EQ("int a           = 5;\n"
16797             "int one         = 1;\n"
16798             "\n"
16799             "int oneTwoThree = 123;",
16800             format("int a = 5;\n"
16801                    "int one = 1;\n"
16802                    "\n"
16803                    "int oneTwoThree = 123;",
16804                    Alignment));
16805   EXPECT_EQ("int a           = 5;\n"
16806             "int one         = 1;\n"
16807             "\n"
16808             "int oneTwoThree = 123;\n"
16809             "int oneTwo      = 12;",
16810             format("int a = 5;\n"
16811                    "int one = 1;\n"
16812                    "\n"
16813                    "int oneTwoThree = 123;\n"
16814                    "int oneTwo = 12;",
16815                    Alignment));
16816 
16817   /* Test across comments */
16818   EXPECT_EQ("int a           = 5;\n"
16819             "/* block comment */\n"
16820             "int oneTwoThree = 123;",
16821             format("int a = 5;\n"
16822                    "/* block comment */\n"
16823                    "int oneTwoThree=123;",
16824                    Alignment));
16825 
16826   EXPECT_EQ("int a           = 5;\n"
16827             "// line comment\n"
16828             "int oneTwoThree = 123;",
16829             format("int a = 5;\n"
16830                    "// line comment\n"
16831                    "int oneTwoThree=123;",
16832                    Alignment));
16833 
16834   /* Test across comments and newlines */
16835   EXPECT_EQ("int a           = 5;\n"
16836             "\n"
16837             "/* block comment */\n"
16838             "int oneTwoThree = 123;",
16839             format("int a = 5;\n"
16840                    "\n"
16841                    "/* block comment */\n"
16842                    "int oneTwoThree=123;",
16843                    Alignment));
16844 
16845   EXPECT_EQ("int a           = 5;\n"
16846             "\n"
16847             "// line comment\n"
16848             "int oneTwoThree = 123;",
16849             format("int a = 5;\n"
16850                    "\n"
16851                    "// line comment\n"
16852                    "int oneTwoThree=123;",
16853                    Alignment));
16854 
16855   EXPECT_EQ("int a           = 5;\n"
16856             "//\n"
16857             "// multi-line line comment\n"
16858             "//\n"
16859             "int oneTwoThree = 123;",
16860             format("int a = 5;\n"
16861                    "//\n"
16862                    "// multi-line line comment\n"
16863                    "//\n"
16864                    "int oneTwoThree=123;",
16865                    Alignment));
16866 
16867   EXPECT_EQ("int a           = 5;\n"
16868             "/*\n"
16869             " *  multi-line block comment\n"
16870             " */\n"
16871             "int oneTwoThree = 123;",
16872             format("int a = 5;\n"
16873                    "/*\n"
16874                    " *  multi-line block comment\n"
16875                    " */\n"
16876                    "int oneTwoThree=123;",
16877                    Alignment));
16878 
16879   EXPECT_EQ("int a           = 5;\n"
16880             "\n"
16881             "/* block comment */\n"
16882             "\n"
16883             "\n"
16884             "\n"
16885             "int oneTwoThree = 123;",
16886             format("int a = 5;\n"
16887                    "\n"
16888                    "/* block comment */\n"
16889                    "\n"
16890                    "\n"
16891                    "\n"
16892                    "int oneTwoThree=123;",
16893                    Alignment));
16894 
16895   EXPECT_EQ("int a           = 5;\n"
16896             "\n"
16897             "// line comment\n"
16898             "\n"
16899             "\n"
16900             "\n"
16901             "int oneTwoThree = 123;",
16902             format("int a = 5;\n"
16903                    "\n"
16904                    "// line comment\n"
16905                    "\n"
16906                    "\n"
16907                    "\n"
16908                    "int oneTwoThree=123;",
16909                    Alignment));
16910 
16911   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16912   verifyFormat("#define A \\\n"
16913                "  int aaaa       = 12; \\\n"
16914                "  int b          = 23; \\\n"
16915                "  int ccc        = 234; \\\n"
16916                "  int dddddddddd = 2345;",
16917                Alignment);
16918   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16919   verifyFormat("#define A               \\\n"
16920                "  int aaaa       = 12;  \\\n"
16921                "  int b          = 23;  \\\n"
16922                "  int ccc        = 234; \\\n"
16923                "  int dddddddddd = 2345;",
16924                Alignment);
16925   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16926   verifyFormat("#define A                                                      "
16927                "                \\\n"
16928                "  int aaaa       = 12;                                         "
16929                "                \\\n"
16930                "  int b          = 23;                                         "
16931                "                \\\n"
16932                "  int ccc        = 234;                                        "
16933                "                \\\n"
16934                "  int dddddddddd = 2345;",
16935                Alignment);
16936   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16937                "k = 4, int l = 5,\n"
16938                "                  int m = 6) {\n"
16939                "  int j      = 10;\n"
16940                "  otherThing = 1;\n"
16941                "}",
16942                Alignment);
16943   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16944                "  int i   = 1;\n"
16945                "  int j   = 2;\n"
16946                "  int big = 10000;\n"
16947                "}",
16948                Alignment);
16949   verifyFormat("class C {\n"
16950                "public:\n"
16951                "  int i            = 1;\n"
16952                "  virtual void f() = 0;\n"
16953                "};",
16954                Alignment);
16955   verifyFormat("int i = 1;\n"
16956                "if (SomeType t = getSomething()) {\n"
16957                "}\n"
16958                "int j   = 2;\n"
16959                "int big = 10000;",
16960                Alignment);
16961   verifyFormat("int j = 7;\n"
16962                "for (int k = 0; k < N; ++k) {\n"
16963                "}\n"
16964                "int j   = 2;\n"
16965                "int big = 10000;\n"
16966                "}",
16967                Alignment);
16968   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16969   verifyFormat("int i = 1;\n"
16970                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16971                "    = someLooooooooooooooooongFunction();\n"
16972                "int j = 2;",
16973                Alignment);
16974   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16975   verifyFormat("int i = 1;\n"
16976                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16977                "    someLooooooooooooooooongFunction();\n"
16978                "int j = 2;",
16979                Alignment);
16980 
16981   verifyFormat("auto lambda = []() {\n"
16982                "  auto i = 0;\n"
16983                "  return 0;\n"
16984                "};\n"
16985                "int i  = 0;\n"
16986                "auto v = type{\n"
16987                "    i = 1,   //\n"
16988                "    (i = 2), //\n"
16989                "    i = 3    //\n"
16990                "};",
16991                Alignment);
16992 
16993   verifyFormat(
16994       "int i      = 1;\n"
16995       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16996       "                          loooooooooooooooooooooongParameterB);\n"
16997       "int j      = 2;",
16998       Alignment);
16999 
17000   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
17001                "          typename B   = very_long_type_name_1,\n"
17002                "          typename T_2 = very_long_type_name_2>\n"
17003                "auto foo() {}\n",
17004                Alignment);
17005   verifyFormat("int a, b = 1;\n"
17006                "int c  = 2;\n"
17007                "int dd = 3;\n",
17008                Alignment);
17009   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17010                "float b[1][] = {{3.f}};\n",
17011                Alignment);
17012   verifyFormat("for (int i = 0; i < 1; i++)\n"
17013                "  int x = 1;\n",
17014                Alignment);
17015   verifyFormat("for (i = 0; i < 1; i++)\n"
17016                "  x = 1;\n"
17017                "y = 1;\n",
17018                Alignment);
17019 
17020   Alignment.ReflowComments = true;
17021   Alignment.ColumnLimit = 50;
17022   EXPECT_EQ("int x   = 0;\n"
17023             "int yy  = 1; /// specificlennospace\n"
17024             "int zzz = 2;\n",
17025             format("int x   = 0;\n"
17026                    "int yy  = 1; ///specificlennospace\n"
17027                    "int zzz = 2;\n",
17028                    Alignment));
17029 }
17030 
TEST_F(FormatTest,AlignCompoundAssignments)17031 TEST_F(FormatTest, AlignCompoundAssignments) {
17032   FormatStyle Alignment = getLLVMStyle();
17033   Alignment.AlignConsecutiveAssignments.Enabled = true;
17034   Alignment.AlignConsecutiveAssignments.AlignCompound = true;
17035   Alignment.AlignConsecutiveAssignments.PadOperators = false;
17036   verifyFormat("sfdbddfbdfbb    = 5;\n"
17037                "dvsdsv          = 5;\n"
17038                "int dsvvdvsdvvv = 123;",
17039                Alignment);
17040   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
17041                "dvsdsv         |= 5;\n"
17042                "int dsvvdvsdvvv = 123;",
17043                Alignment);
17044   verifyFormat("sfdbddfbdfbb   ^= 5;\n"
17045                "dvsdsv        <<= 5;\n"
17046                "int dsvvdvsdvvv = 123;",
17047                Alignment);
17048   // Test that `<=` is not treated as a compound assignment.
17049   verifyFormat("aa &= 5;\n"
17050                "b <= 10;\n"
17051                "c = 15;",
17052                Alignment);
17053   Alignment.AlignConsecutiveAssignments.PadOperators = true;
17054   verifyFormat("sfdbddfbdfbb    = 5;\n"
17055                "dvsdsv          = 5;\n"
17056                "int dsvvdvsdvvv = 123;",
17057                Alignment);
17058   verifyFormat("sfdbddfbdfbb    ^= 5;\n"
17059                "dvsdsv          |= 5;\n"
17060                "int dsvvdvsdvvv  = 123;",
17061                Alignment);
17062   verifyFormat("sfdbddfbdfbb     ^= 5;\n"
17063                "dvsdsv          <<= 5;\n"
17064                "int dsvvdvsdvvv   = 123;",
17065                Alignment);
17066   EXPECT_EQ("a   += 5;\n"
17067             "one  = 1;\n"
17068             "\n"
17069             "oneTwoThree = 123;\n",
17070             format("a += 5;\n"
17071                    "one = 1;\n"
17072                    "\n"
17073                    "oneTwoThree = 123;\n",
17074                    Alignment));
17075   EXPECT_EQ("a   += 5;\n"
17076             "one  = 1;\n"
17077             "//\n"
17078             "oneTwoThree = 123;\n",
17079             format("a += 5;\n"
17080                    "one = 1;\n"
17081                    "//\n"
17082                    "oneTwoThree = 123;\n",
17083                    Alignment));
17084   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
17085   EXPECT_EQ("a           += 5;\n"
17086             "one          = 1;\n"
17087             "\n"
17088             "oneTwoThree  = 123;\n",
17089             format("a += 5;\n"
17090                    "one = 1;\n"
17091                    "\n"
17092                    "oneTwoThree = 123;\n",
17093                    Alignment));
17094   EXPECT_EQ("a   += 5;\n"
17095             "one  = 1;\n"
17096             "//\n"
17097             "oneTwoThree = 123;\n",
17098             format("a += 5;\n"
17099                    "one = 1;\n"
17100                    "//\n"
17101                    "oneTwoThree = 123;\n",
17102                    Alignment));
17103   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = false;
17104   Alignment.AlignConsecutiveAssignments.AcrossComments = true;
17105   EXPECT_EQ("a   += 5;\n"
17106             "one  = 1;\n"
17107             "\n"
17108             "oneTwoThree = 123;\n",
17109             format("a += 5;\n"
17110                    "one = 1;\n"
17111                    "\n"
17112                    "oneTwoThree = 123;\n",
17113                    Alignment));
17114   EXPECT_EQ("a           += 5;\n"
17115             "one          = 1;\n"
17116             "//\n"
17117             "oneTwoThree  = 123;\n",
17118             format("a += 5;\n"
17119                    "one = 1;\n"
17120                    "//\n"
17121                    "oneTwoThree = 123;\n",
17122                    Alignment));
17123   Alignment.AlignConsecutiveAssignments.AcrossEmptyLines = true;
17124   EXPECT_EQ("a            += 5;\n"
17125             "one         >>= 1;\n"
17126             "\n"
17127             "oneTwoThree   = 123;\n",
17128             format("a += 5;\n"
17129                    "one >>= 1;\n"
17130                    "\n"
17131                    "oneTwoThree = 123;\n",
17132                    Alignment));
17133   EXPECT_EQ("a            += 5;\n"
17134             "one           = 1;\n"
17135             "//\n"
17136             "oneTwoThree <<= 123;\n",
17137             format("a += 5;\n"
17138                    "one = 1;\n"
17139                    "//\n"
17140                    "oneTwoThree <<= 123;\n",
17141                    Alignment));
17142 }
17143 
TEST_F(FormatTest,AlignConsecutiveAssignments)17144 TEST_F(FormatTest, AlignConsecutiveAssignments) {
17145   FormatStyle Alignment = getLLVMStyle();
17146   Alignment.AlignConsecutiveMacros.Enabled = true;
17147   verifyFormat("int a = 5;\n"
17148                "int oneTwoThree = 123;",
17149                Alignment);
17150   verifyFormat("int a = 5;\n"
17151                "int oneTwoThree = 123;",
17152                Alignment);
17153 
17154   Alignment.AlignConsecutiveAssignments.Enabled = true;
17155   verifyFormat("int a           = 5;\n"
17156                "int oneTwoThree = 123;",
17157                Alignment);
17158   verifyFormat("int a           = method();\n"
17159                "int oneTwoThree = 133;",
17160                Alignment);
17161   verifyFormat("aa <= 5;\n"
17162                "a &= 5;\n"
17163                "bcd *= 5;\n"
17164                "ghtyf += 5;\n"
17165                "dvfvdb -= 5;\n"
17166                "a /= 5;\n"
17167                "vdsvsv %= 5;\n"
17168                "sfdbddfbdfbb ^= 5;\n"
17169                "dvsdsv |= 5;\n"
17170                "int dsvvdvsdvvv = 123;",
17171                Alignment);
17172   verifyFormat("int i = 1, j = 10;\n"
17173                "something = 2000;",
17174                Alignment);
17175   verifyFormat("something = 2000;\n"
17176                "int i = 1, j = 10;\n",
17177                Alignment);
17178   verifyFormat("something = 2000;\n"
17179                "another   = 911;\n"
17180                "int i = 1, j = 10;\n"
17181                "oneMore = 1;\n"
17182                "i       = 2;",
17183                Alignment);
17184   verifyFormat("int a   = 5;\n"
17185                "int one = 1;\n"
17186                "method();\n"
17187                "int oneTwoThree = 123;\n"
17188                "int oneTwo      = 12;",
17189                Alignment);
17190   verifyFormat("int oneTwoThree = 123;\n"
17191                "int oneTwo      = 12;\n"
17192                "method();\n",
17193                Alignment);
17194   verifyFormat("int oneTwoThree = 123; // comment\n"
17195                "int oneTwo      = 12;  // comment",
17196                Alignment);
17197   verifyFormat("int f()         = default;\n"
17198                "int &operator() = default;\n"
17199                "int &operator=() {",
17200                Alignment);
17201   verifyFormat("int f()         = delete;\n"
17202                "int &operator() = delete;\n"
17203                "int &operator=() {",
17204                Alignment);
17205   verifyFormat("int f()         = default; // comment\n"
17206                "int &operator() = default; // comment\n"
17207                "int &operator=() {",
17208                Alignment);
17209   verifyFormat("int f()         = default;\n"
17210                "int &operator() = default;\n"
17211                "int &operator==() {",
17212                Alignment);
17213   verifyFormat("int f()         = default;\n"
17214                "int &operator() = default;\n"
17215                "int &operator<=() {",
17216                Alignment);
17217   verifyFormat("int f()         = default;\n"
17218                "int &operator() = default;\n"
17219                "int &operator!=() {",
17220                Alignment);
17221   verifyFormat("int f()         = default;\n"
17222                "int &operator() = default;\n"
17223                "int &operator=();",
17224                Alignment);
17225   verifyFormat("int f()         = delete;\n"
17226                "int &operator() = delete;\n"
17227                "int &operator=();",
17228                Alignment);
17229   verifyFormat("/* long long padding */ int f() = default;\n"
17230                "int &operator()                 = default;\n"
17231                "int &operator/**/ =();",
17232                Alignment);
17233   // https://llvm.org/PR33697
17234   FormatStyle AlignmentWithPenalty = getLLVMStyle();
17235   AlignmentWithPenalty.AlignConsecutiveAssignments.Enabled = true;
17236   AlignmentWithPenalty.PenaltyReturnTypeOnItsOwnLine = 5000;
17237   verifyFormat("class SSSSSSSSSSSSSSSSSSSSSSSSSSSS {\n"
17238                "  void f() = delete;\n"
17239                "  SSSSSSSSSSSSSSSSSSSSSSSSSSSS &operator=(\n"
17240                "      const SSSSSSSSSSSSSSSSSSSSSSSSSSSS &other) = delete;\n"
17241                "};\n",
17242                AlignmentWithPenalty);
17243 
17244   // Bug 25167
17245   /* Uncomment when fixed
17246     verifyFormat("#if A\n"
17247                  "#else\n"
17248                  "int aaaaaaaa = 12;\n"
17249                  "#endif\n"
17250                  "#if B\n"
17251                  "#else\n"
17252                  "int a = 12;\n"
17253                  "#endif\n",
17254                  Alignment);
17255     verifyFormat("enum foo {\n"
17256                  "#if A\n"
17257                  "#else\n"
17258                  "  aaaaaaaa = 12;\n"
17259                  "#endif\n"
17260                  "#if B\n"
17261                  "#else\n"
17262                  "  a = 12;\n"
17263                  "#endif\n"
17264                  "};\n",
17265                  Alignment);
17266   */
17267 
17268   EXPECT_EQ("int a = 5;\n"
17269             "\n"
17270             "int oneTwoThree = 123;",
17271             format("int a       = 5;\n"
17272                    "\n"
17273                    "int oneTwoThree= 123;",
17274                    Alignment));
17275   EXPECT_EQ("int a   = 5;\n"
17276             "int one = 1;\n"
17277             "\n"
17278             "int oneTwoThree = 123;",
17279             format("int a = 5;\n"
17280                    "int one = 1;\n"
17281                    "\n"
17282                    "int oneTwoThree = 123;",
17283                    Alignment));
17284   EXPECT_EQ("int a   = 5;\n"
17285             "int one = 1;\n"
17286             "\n"
17287             "int oneTwoThree = 123;\n"
17288             "int oneTwo      = 12;",
17289             format("int a = 5;\n"
17290                    "int one = 1;\n"
17291                    "\n"
17292                    "int oneTwoThree = 123;\n"
17293                    "int oneTwo = 12;",
17294                    Alignment));
17295   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17296   verifyFormat("#define A \\\n"
17297                "  int aaaa       = 12; \\\n"
17298                "  int b          = 23; \\\n"
17299                "  int ccc        = 234; \\\n"
17300                "  int dddddddddd = 2345;",
17301                Alignment);
17302   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17303   verifyFormat("#define A               \\\n"
17304                "  int aaaa       = 12;  \\\n"
17305                "  int b          = 23;  \\\n"
17306                "  int ccc        = 234; \\\n"
17307                "  int dddddddddd = 2345;",
17308                Alignment);
17309   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17310   verifyFormat("#define A                                                      "
17311                "                \\\n"
17312                "  int aaaa       = 12;                                         "
17313                "                \\\n"
17314                "  int b          = 23;                                         "
17315                "                \\\n"
17316                "  int ccc        = 234;                                        "
17317                "                \\\n"
17318                "  int dddddddddd = 2345;",
17319                Alignment);
17320   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17321                "k = 4, int l = 5,\n"
17322                "                  int m = 6) {\n"
17323                "  int j      = 10;\n"
17324                "  otherThing = 1;\n"
17325                "}",
17326                Alignment);
17327   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17328                "  int i   = 1;\n"
17329                "  int j   = 2;\n"
17330                "  int big = 10000;\n"
17331                "}",
17332                Alignment);
17333   verifyFormat("class C {\n"
17334                "public:\n"
17335                "  int i            = 1;\n"
17336                "  virtual void f() = 0;\n"
17337                "};",
17338                Alignment);
17339   verifyFormat("int i = 1;\n"
17340                "if (SomeType t = getSomething()) {\n"
17341                "}\n"
17342                "int j   = 2;\n"
17343                "int big = 10000;",
17344                Alignment);
17345   verifyFormat("int j = 7;\n"
17346                "for (int k = 0; k < N; ++k) {\n"
17347                "}\n"
17348                "int j   = 2;\n"
17349                "int big = 10000;\n"
17350                "}",
17351                Alignment);
17352   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17353   verifyFormat("int i = 1;\n"
17354                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17355                "    = someLooooooooooooooooongFunction();\n"
17356                "int j = 2;",
17357                Alignment);
17358   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17359   verifyFormat("int i = 1;\n"
17360                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17361                "    someLooooooooooooooooongFunction();\n"
17362                "int j = 2;",
17363                Alignment);
17364 
17365   verifyFormat("auto lambda = []() {\n"
17366                "  auto i = 0;\n"
17367                "  return 0;\n"
17368                "};\n"
17369                "int i  = 0;\n"
17370                "auto v = type{\n"
17371                "    i = 1,   //\n"
17372                "    (i = 2), //\n"
17373                "    i = 3    //\n"
17374                "};",
17375                Alignment);
17376 
17377   verifyFormat(
17378       "int i      = 1;\n"
17379       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17380       "                          loooooooooooooooooooooongParameterB);\n"
17381       "int j      = 2;",
17382       Alignment);
17383 
17384   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
17385                "          typename B   = very_long_type_name_1,\n"
17386                "          typename T_2 = very_long_type_name_2>\n"
17387                "auto foo() {}\n",
17388                Alignment);
17389   verifyFormat("int a, b = 1;\n"
17390                "int c  = 2;\n"
17391                "int dd = 3;\n",
17392                Alignment);
17393   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
17394                "float b[1][] = {{3.f}};\n",
17395                Alignment);
17396   verifyFormat("for (int i = 0; i < 1; i++)\n"
17397                "  int x = 1;\n",
17398                Alignment);
17399   verifyFormat("for (i = 0; i < 1; i++)\n"
17400                "  x = 1;\n"
17401                "y = 1;\n",
17402                Alignment);
17403 
17404   EXPECT_EQ(Alignment.ReflowComments, true);
17405   Alignment.ColumnLimit = 50;
17406   EXPECT_EQ("int x   = 0;\n"
17407             "int yy  = 1; /// specificlennospace\n"
17408             "int zzz = 2;\n",
17409             format("int x   = 0;\n"
17410                    "int yy  = 1; ///specificlennospace\n"
17411                    "int zzz = 2;\n",
17412                    Alignment));
17413 
17414   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17415                "auto b                     = [] {\n"
17416                "  f();\n"
17417                "  return;\n"
17418                "};",
17419                Alignment);
17420   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17421                "auto b                     = g([] {\n"
17422                "  f();\n"
17423                "  return;\n"
17424                "});",
17425                Alignment);
17426   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17427                "auto b                     = g(param, [] {\n"
17428                "  f();\n"
17429                "  return;\n"
17430                "});",
17431                Alignment);
17432   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaa = {};\n"
17433                "auto b                     = [] {\n"
17434                "  if (condition) {\n"
17435                "    return;\n"
17436                "  }\n"
17437                "};",
17438                Alignment);
17439 
17440   verifyFormat("auto b = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17441                "           ccc ? aaaaa : bbbbb,\n"
17442                "           dddddddddddddddddddddddddd);",
17443                Alignment);
17444   // FIXME: https://llvm.org/PR53497
17445   // verifyFormat("auto aaaaaaaaaaaa = f();\n"
17446   //              "auto b            = f(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
17447   //              "    ccc ? aaaaa : bbbbb,\n"
17448   //              "    dddddddddddddddddddddddddd);",
17449   //              Alignment);
17450 
17451   // Confirm proper handling of AlignConsecutiveAssignments with
17452   // BinPackArguments.
17453   // See https://llvm.org/PR55360
17454   Alignment = getLLVMStyleWithColumns(50);
17455   Alignment.AlignConsecutiveAssignments.Enabled = true;
17456   Alignment.BinPackArguments = false;
17457   verifyFormat("int a_long_name = 1;\n"
17458                "auto b          = B({a_long_name, a_long_name},\n"
17459                "                    {a_longer_name_for_wrap,\n"
17460                "                     a_longer_name_for_wrap});",
17461                Alignment);
17462   verifyFormat("int a_long_name = 1;\n"
17463                "auto b          = B{{a_long_name, a_long_name},\n"
17464                "                    {a_longer_name_for_wrap,\n"
17465                "                     a_longer_name_for_wrap}};",
17466                Alignment);
17467 }
17468 
TEST_F(FormatTest,AlignConsecutiveBitFields)17469 TEST_F(FormatTest, AlignConsecutiveBitFields) {
17470   FormatStyle Alignment = getLLVMStyle();
17471   Alignment.AlignConsecutiveBitFields.Enabled = true;
17472   verifyFormat("int const a     : 5;\n"
17473                "int oneTwoThree : 23;",
17474                Alignment);
17475 
17476   // Initializers are allowed starting with c++2a
17477   verifyFormat("int const a     : 5 = 1;\n"
17478                "int oneTwoThree : 23 = 0;",
17479                Alignment);
17480 
17481   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17482   verifyFormat("int const a           : 5;\n"
17483                "int       oneTwoThree : 23;",
17484                Alignment);
17485 
17486   verifyFormat("int const a           : 5;  // comment\n"
17487                "int       oneTwoThree : 23; // comment",
17488                Alignment);
17489 
17490   verifyFormat("int const a           : 5 = 1;\n"
17491                "int       oneTwoThree : 23 = 0;",
17492                Alignment);
17493 
17494   Alignment.AlignConsecutiveAssignments.Enabled = true;
17495   verifyFormat("int const a           : 5  = 1;\n"
17496                "int       oneTwoThree : 23 = 0;",
17497                Alignment);
17498   verifyFormat("int const a           : 5  = {1};\n"
17499                "int       oneTwoThree : 23 = 0;",
17500                Alignment);
17501 
17502   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
17503   verifyFormat("int const a          :5;\n"
17504                "int       oneTwoThree:23;",
17505                Alignment);
17506 
17507   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
17508   verifyFormat("int const a           :5;\n"
17509                "int       oneTwoThree :23;",
17510                Alignment);
17511 
17512   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
17513   verifyFormat("int const a          : 5;\n"
17514                "int       oneTwoThree: 23;",
17515                Alignment);
17516 
17517   // Known limitations: ':' is only recognized as a bitfield colon when
17518   // followed by a number.
17519   /*
17520   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
17521                "int a           : 5;",
17522                Alignment);
17523   */
17524 }
17525 
TEST_F(FormatTest,AlignConsecutiveDeclarations)17526 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
17527   FormatStyle Alignment = getLLVMStyle();
17528   Alignment.AlignConsecutiveMacros.Enabled = true;
17529   Alignment.PointerAlignment = FormatStyle::PAS_Right;
17530   verifyFormat("float const a = 5;\n"
17531                "int oneTwoThree = 123;",
17532                Alignment);
17533   verifyFormat("int a = 5;\n"
17534                "float const oneTwoThree = 123;",
17535                Alignment);
17536 
17537   Alignment.AlignConsecutiveDeclarations.Enabled = true;
17538   verifyFormat("float const a = 5;\n"
17539                "int         oneTwoThree = 123;",
17540                Alignment);
17541   verifyFormat("int         a = method();\n"
17542                "float const oneTwoThree = 133;",
17543                Alignment);
17544   verifyFormat("int i = 1, j = 10;\n"
17545                "something = 2000;",
17546                Alignment);
17547   verifyFormat("something = 2000;\n"
17548                "int i = 1, j = 10;\n",
17549                Alignment);
17550   verifyFormat("float      something = 2000;\n"
17551                "double     another = 911;\n"
17552                "int        i = 1, j = 10;\n"
17553                "const int *oneMore = 1;\n"
17554                "unsigned   i = 2;",
17555                Alignment);
17556   verifyFormat("float a = 5;\n"
17557                "int   one = 1;\n"
17558                "method();\n"
17559                "const double       oneTwoThree = 123;\n"
17560                "const unsigned int oneTwo = 12;",
17561                Alignment);
17562   verifyFormat("int      oneTwoThree{0}; // comment\n"
17563                "unsigned oneTwo;         // comment",
17564                Alignment);
17565   verifyFormat("unsigned int       *a;\n"
17566                "int                *b;\n"
17567                "unsigned int Const *c;\n"
17568                "unsigned int const *d;\n"
17569                "unsigned int Const &e;\n"
17570                "unsigned int const &f;",
17571                Alignment);
17572   verifyFormat("Const unsigned int *c;\n"
17573                "const unsigned int *d;\n"
17574                "Const unsigned int &e;\n"
17575                "const unsigned int &f;\n"
17576                "const unsigned      g;\n"
17577                "Const unsigned      h;",
17578                Alignment);
17579   EXPECT_EQ("float const a = 5;\n"
17580             "\n"
17581             "int oneTwoThree = 123;",
17582             format("float const   a = 5;\n"
17583                    "\n"
17584                    "int           oneTwoThree= 123;",
17585                    Alignment));
17586   EXPECT_EQ("float a = 5;\n"
17587             "int   one = 1;\n"
17588             "\n"
17589             "unsigned oneTwoThree = 123;",
17590             format("float    a = 5;\n"
17591                    "int      one = 1;\n"
17592                    "\n"
17593                    "unsigned oneTwoThree = 123;",
17594                    Alignment));
17595   EXPECT_EQ("float a = 5;\n"
17596             "int   one = 1;\n"
17597             "\n"
17598             "unsigned oneTwoThree = 123;\n"
17599             "int      oneTwo = 12;",
17600             format("float    a = 5;\n"
17601                    "int one = 1;\n"
17602                    "\n"
17603                    "unsigned oneTwoThree = 123;\n"
17604                    "int oneTwo = 12;",
17605                    Alignment));
17606   // Function prototype alignment
17607   verifyFormat("int    a();\n"
17608                "double b();",
17609                Alignment);
17610   verifyFormat("int    a(int x);\n"
17611                "double b();",
17612                Alignment);
17613   unsigned OldColumnLimit = Alignment.ColumnLimit;
17614   // We need to set ColumnLimit to zero, in order to stress nested alignments,
17615   // otherwise the function parameters will be re-flowed onto a single line.
17616   Alignment.ColumnLimit = 0;
17617   EXPECT_EQ("int    a(int   x,\n"
17618             "         float y);\n"
17619             "double b(int    x,\n"
17620             "         double y);",
17621             format("int a(int x,\n"
17622                    " float y);\n"
17623                    "double b(int x,\n"
17624                    " double y);",
17625                    Alignment));
17626   // This ensures that function parameters of function declarations are
17627   // correctly indented when their owning functions are indented.
17628   // The failure case here is for 'double y' to not be indented enough.
17629   EXPECT_EQ("double a(int x);\n"
17630             "int    b(int    y,\n"
17631             "         double z);",
17632             format("double a(int x);\n"
17633                    "int b(int y,\n"
17634                    " double z);",
17635                    Alignment));
17636   // Set ColumnLimit low so that we induce wrapping immediately after
17637   // the function name and opening paren.
17638   Alignment.ColumnLimit = 13;
17639   verifyFormat("int function(\n"
17640                "    int  x,\n"
17641                "    bool y);",
17642                Alignment);
17643   Alignment.ColumnLimit = OldColumnLimit;
17644   // Ensure function pointers don't screw up recursive alignment
17645   verifyFormat("int    a(int x, void (*fp)(int y));\n"
17646                "double b();",
17647                Alignment);
17648   Alignment.AlignConsecutiveAssignments.Enabled = true;
17649   // Ensure recursive alignment is broken by function braces, so that the
17650   // "a = 1" does not align with subsequent assignments inside the function
17651   // body.
17652   verifyFormat("int func(int a = 1) {\n"
17653                "  int b  = 2;\n"
17654                "  int cc = 3;\n"
17655                "}",
17656                Alignment);
17657   verifyFormat("float      something = 2000;\n"
17658                "double     another   = 911;\n"
17659                "int        i = 1, j = 10;\n"
17660                "const int *oneMore = 1;\n"
17661                "unsigned   i       = 2;",
17662                Alignment);
17663   verifyFormat("int      oneTwoThree = {0}; // comment\n"
17664                "unsigned oneTwo      = 0;   // comment",
17665                Alignment);
17666   // Make sure that scope is correctly tracked, in the absence of braces
17667   verifyFormat("for (int i = 0; i < n; i++)\n"
17668                "  j = i;\n"
17669                "double x = 1;\n",
17670                Alignment);
17671   verifyFormat("if (int i = 0)\n"
17672                "  j = i;\n"
17673                "double x = 1;\n",
17674                Alignment);
17675   // Ensure operator[] and operator() are comprehended
17676   verifyFormat("struct test {\n"
17677                "  long long int foo();\n"
17678                "  int           operator[](int a);\n"
17679                "  double        bar();\n"
17680                "};\n",
17681                Alignment);
17682   verifyFormat("struct test {\n"
17683                "  long long int foo();\n"
17684                "  int           operator()(int a);\n"
17685                "  double        bar();\n"
17686                "};\n",
17687                Alignment);
17688   // http://llvm.org/PR52914
17689   verifyFormat("char *a[]     = {\"a\", // comment\n"
17690                "                 \"bb\"};\n"
17691                "int   bbbbbbb = 0;",
17692                Alignment);
17693 
17694   // PAS_Right
17695   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17696             "  int const i   = 1;\n"
17697             "  int      *j   = 2;\n"
17698             "  int       big = 10000;\n"
17699             "\n"
17700             "  unsigned oneTwoThree = 123;\n"
17701             "  int      oneTwo      = 12;\n"
17702             "  method();\n"
17703             "  float k  = 2;\n"
17704             "  int   ll = 10000;\n"
17705             "}",
17706             format("void SomeFunction(int parameter= 0) {\n"
17707                    " int const  i= 1;\n"
17708                    "  int *j=2;\n"
17709                    " int big  =  10000;\n"
17710                    "\n"
17711                    "unsigned oneTwoThree  =123;\n"
17712                    "int oneTwo = 12;\n"
17713                    "  method();\n"
17714                    "float k= 2;\n"
17715                    "int ll=10000;\n"
17716                    "}",
17717                    Alignment));
17718   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17719             "  int const i   = 1;\n"
17720             "  int     **j   = 2, ***k;\n"
17721             "  int      &k   = i;\n"
17722             "  int     &&l   = i + j;\n"
17723             "  int       big = 10000;\n"
17724             "\n"
17725             "  unsigned oneTwoThree = 123;\n"
17726             "  int      oneTwo      = 12;\n"
17727             "  method();\n"
17728             "  float k  = 2;\n"
17729             "  int   ll = 10000;\n"
17730             "}",
17731             format("void SomeFunction(int parameter= 0) {\n"
17732                    " int const  i= 1;\n"
17733                    "  int **j=2,***k;\n"
17734                    "int &k=i;\n"
17735                    "int &&l=i+j;\n"
17736                    " int big  =  10000;\n"
17737                    "\n"
17738                    "unsigned oneTwoThree  =123;\n"
17739                    "int oneTwo = 12;\n"
17740                    "  method();\n"
17741                    "float k= 2;\n"
17742                    "int ll=10000;\n"
17743                    "}",
17744                    Alignment));
17745   // variables are aligned at their name, pointers are at the right most
17746   // position
17747   verifyFormat("int   *a;\n"
17748                "int  **b;\n"
17749                "int ***c;\n"
17750                "int    foobar;\n",
17751                Alignment);
17752 
17753   // PAS_Left
17754   FormatStyle AlignmentLeft = Alignment;
17755   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
17756   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17757             "  int const i   = 1;\n"
17758             "  int*      j   = 2;\n"
17759             "  int       big = 10000;\n"
17760             "\n"
17761             "  unsigned oneTwoThree = 123;\n"
17762             "  int      oneTwo      = 12;\n"
17763             "  method();\n"
17764             "  float k  = 2;\n"
17765             "  int   ll = 10000;\n"
17766             "}",
17767             format("void SomeFunction(int parameter= 0) {\n"
17768                    " int const  i= 1;\n"
17769                    "  int *j=2;\n"
17770                    " int big  =  10000;\n"
17771                    "\n"
17772                    "unsigned oneTwoThree  =123;\n"
17773                    "int oneTwo = 12;\n"
17774                    "  method();\n"
17775                    "float k= 2;\n"
17776                    "int ll=10000;\n"
17777                    "}",
17778                    AlignmentLeft));
17779   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17780             "  int const i   = 1;\n"
17781             "  int**     j   = 2;\n"
17782             "  int&      k   = i;\n"
17783             "  int&&     l   = i + j;\n"
17784             "  int       big = 10000;\n"
17785             "\n"
17786             "  unsigned oneTwoThree = 123;\n"
17787             "  int      oneTwo      = 12;\n"
17788             "  method();\n"
17789             "  float k  = 2;\n"
17790             "  int   ll = 10000;\n"
17791             "}",
17792             format("void SomeFunction(int parameter= 0) {\n"
17793                    " int const  i= 1;\n"
17794                    "  int **j=2;\n"
17795                    "int &k=i;\n"
17796                    "int &&l=i+j;\n"
17797                    " int big  =  10000;\n"
17798                    "\n"
17799                    "unsigned oneTwoThree  =123;\n"
17800                    "int oneTwo = 12;\n"
17801                    "  method();\n"
17802                    "float k= 2;\n"
17803                    "int ll=10000;\n"
17804                    "}",
17805                    AlignmentLeft));
17806   // variables are aligned at their name, pointers are at the left most position
17807   verifyFormat("int*   a;\n"
17808                "int**  b;\n"
17809                "int*** c;\n"
17810                "int    foobar;\n",
17811                AlignmentLeft);
17812 
17813   // PAS_Middle
17814   FormatStyle AlignmentMiddle = Alignment;
17815   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
17816   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17817             "  int const i   = 1;\n"
17818             "  int *     j   = 2;\n"
17819             "  int       big = 10000;\n"
17820             "\n"
17821             "  unsigned oneTwoThree = 123;\n"
17822             "  int      oneTwo      = 12;\n"
17823             "  method();\n"
17824             "  float k  = 2;\n"
17825             "  int   ll = 10000;\n"
17826             "}",
17827             format("void SomeFunction(int parameter= 0) {\n"
17828                    " int const  i= 1;\n"
17829                    "  int *j=2;\n"
17830                    " int big  =  10000;\n"
17831                    "\n"
17832                    "unsigned oneTwoThree  =123;\n"
17833                    "int oneTwo = 12;\n"
17834                    "  method();\n"
17835                    "float k= 2;\n"
17836                    "int ll=10000;\n"
17837                    "}",
17838                    AlignmentMiddle));
17839   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
17840             "  int const i   = 1;\n"
17841             "  int **    j   = 2, ***k;\n"
17842             "  int &     k   = i;\n"
17843             "  int &&    l   = i + j;\n"
17844             "  int       big = 10000;\n"
17845             "\n"
17846             "  unsigned oneTwoThree = 123;\n"
17847             "  int      oneTwo      = 12;\n"
17848             "  method();\n"
17849             "  float k  = 2;\n"
17850             "  int   ll = 10000;\n"
17851             "}",
17852             format("void SomeFunction(int parameter= 0) {\n"
17853                    " int const  i= 1;\n"
17854                    "  int **j=2,***k;\n"
17855                    "int &k=i;\n"
17856                    "int &&l=i+j;\n"
17857                    " int big  =  10000;\n"
17858                    "\n"
17859                    "unsigned oneTwoThree  =123;\n"
17860                    "int oneTwo = 12;\n"
17861                    "  method();\n"
17862                    "float k= 2;\n"
17863                    "int ll=10000;\n"
17864                    "}",
17865                    AlignmentMiddle));
17866   // variables are aligned at their name, pointers are in the middle
17867   verifyFormat("int *   a;\n"
17868                "int *   b;\n"
17869                "int *** c;\n"
17870                "int     foobar;\n",
17871                AlignmentMiddle);
17872 
17873   Alignment.AlignConsecutiveAssignments.Enabled = false;
17874   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
17875   verifyFormat("#define A \\\n"
17876                "  int       aaaa = 12; \\\n"
17877                "  float     b = 23; \\\n"
17878                "  const int ccc = 234; \\\n"
17879                "  unsigned  dddddddddd = 2345;",
17880                Alignment);
17881   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
17882   verifyFormat("#define A              \\\n"
17883                "  int       aaaa = 12; \\\n"
17884                "  float     b = 23;    \\\n"
17885                "  const int ccc = 234; \\\n"
17886                "  unsigned  dddddddddd = 2345;",
17887                Alignment);
17888   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
17889   Alignment.ColumnLimit = 30;
17890   verifyFormat("#define A                    \\\n"
17891                "  int       aaaa = 12;       \\\n"
17892                "  float     b = 23;          \\\n"
17893                "  const int ccc = 234;       \\\n"
17894                "  int       dddddddddd = 2345;",
17895                Alignment);
17896   Alignment.ColumnLimit = 80;
17897   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
17898                "k = 4, int l = 5,\n"
17899                "                  int m = 6) {\n"
17900                "  const int j = 10;\n"
17901                "  otherThing = 1;\n"
17902                "}",
17903                Alignment);
17904   verifyFormat("void SomeFunction(int parameter = 0) {\n"
17905                "  int const i = 1;\n"
17906                "  int      *j = 2;\n"
17907                "  int       big = 10000;\n"
17908                "}",
17909                Alignment);
17910   verifyFormat("class C {\n"
17911                "public:\n"
17912                "  int          i = 1;\n"
17913                "  virtual void f() = 0;\n"
17914                "};",
17915                Alignment);
17916   verifyFormat("float i = 1;\n"
17917                "if (SomeType t = getSomething()) {\n"
17918                "}\n"
17919                "const unsigned j = 2;\n"
17920                "int            big = 10000;",
17921                Alignment);
17922   verifyFormat("float j = 7;\n"
17923                "for (int k = 0; k < N; ++k) {\n"
17924                "}\n"
17925                "unsigned j = 2;\n"
17926                "int      big = 10000;\n"
17927                "}",
17928                Alignment);
17929   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
17930   verifyFormat("float              i = 1;\n"
17931                "LooooooooooongType loooooooooooooooooooooongVariable\n"
17932                "    = someLooooooooooooooooongFunction();\n"
17933                "int j = 2;",
17934                Alignment);
17935   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
17936   verifyFormat("int                i = 1;\n"
17937                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
17938                "    someLooooooooooooooooongFunction();\n"
17939                "int j = 2;",
17940                Alignment);
17941 
17942   Alignment.AlignConsecutiveAssignments.Enabled = true;
17943   verifyFormat("auto lambda = []() {\n"
17944                "  auto  ii = 0;\n"
17945                "  float j  = 0;\n"
17946                "  return 0;\n"
17947                "};\n"
17948                "int   i  = 0;\n"
17949                "float i2 = 0;\n"
17950                "auto  v  = type{\n"
17951                "    i = 1,   //\n"
17952                "    (i = 2), //\n"
17953                "    i = 3    //\n"
17954                "};",
17955                Alignment);
17956   Alignment.AlignConsecutiveAssignments.Enabled = false;
17957 
17958   verifyFormat(
17959       "int      i = 1;\n"
17960       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
17961       "                          loooooooooooooooooooooongParameterB);\n"
17962       "int      j = 2;",
17963       Alignment);
17964 
17965   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
17966   // We expect declarations and assignments to align, as long as it doesn't
17967   // exceed the column limit, starting a new alignment sequence whenever it
17968   // happens.
17969   Alignment.AlignConsecutiveAssignments.Enabled = true;
17970   Alignment.ColumnLimit = 30;
17971   verifyFormat("float    ii              = 1;\n"
17972                "unsigned j               = 2;\n"
17973                "int someVerylongVariable = 1;\n"
17974                "AnotherLongType  ll = 123456;\n"
17975                "VeryVeryLongType k  = 2;\n"
17976                "int              myvar = 1;",
17977                Alignment);
17978   Alignment.ColumnLimit = 80;
17979   Alignment.AlignConsecutiveAssignments.Enabled = false;
17980 
17981   verifyFormat(
17982       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
17983       "          typename LongType, typename B>\n"
17984       "auto foo() {}\n",
17985       Alignment);
17986   verifyFormat("float a, b = 1;\n"
17987                "int   c = 2;\n"
17988                "int   dd = 3;\n",
17989                Alignment);
17990   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
17991                "float b[1][] = {{3.f}};\n",
17992                Alignment);
17993   Alignment.AlignConsecutiveAssignments.Enabled = true;
17994   verifyFormat("float a, b = 1;\n"
17995                "int   c  = 2;\n"
17996                "int   dd = 3;\n",
17997                Alignment);
17998   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
17999                "float b[1][] = {{3.f}};\n",
18000                Alignment);
18001   Alignment.AlignConsecutiveAssignments.Enabled = false;
18002 
18003   Alignment.ColumnLimit = 30;
18004   Alignment.BinPackParameters = false;
18005   verifyFormat("void foo(float     a,\n"
18006                "         float     b,\n"
18007                "         int       c,\n"
18008                "         uint32_t *d) {\n"
18009                "  int   *e = 0;\n"
18010                "  float  f = 0;\n"
18011                "  double g = 0;\n"
18012                "}\n"
18013                "void bar(ino_t     a,\n"
18014                "         int       b,\n"
18015                "         uint32_t *c,\n"
18016                "         bool      d) {}\n",
18017                Alignment);
18018   Alignment.BinPackParameters = true;
18019   Alignment.ColumnLimit = 80;
18020 
18021   // Bug 33507
18022   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
18023   verifyFormat(
18024       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
18025       "  static const Version verVs2017;\n"
18026       "  return true;\n"
18027       "});\n",
18028       Alignment);
18029   Alignment.PointerAlignment = FormatStyle::PAS_Right;
18030 
18031   // See llvm.org/PR35641
18032   Alignment.AlignConsecutiveDeclarations.Enabled = true;
18033   verifyFormat("int func() { //\n"
18034                "  int      b;\n"
18035                "  unsigned c;\n"
18036                "}",
18037                Alignment);
18038 
18039   // See PR37175
18040   FormatStyle Style = getMozillaStyle();
18041   Style.AlignConsecutiveDeclarations.Enabled = true;
18042   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
18043             "foo(int a);",
18044             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
18045 
18046   Alignment.PointerAlignment = FormatStyle::PAS_Left;
18047   verifyFormat("unsigned int*       a;\n"
18048                "int*                b;\n"
18049                "unsigned int Const* c;\n"
18050                "unsigned int const* d;\n"
18051                "unsigned int Const& e;\n"
18052                "unsigned int const& f;",
18053                Alignment);
18054   verifyFormat("Const unsigned int* c;\n"
18055                "const unsigned int* d;\n"
18056                "Const unsigned int& e;\n"
18057                "const unsigned int& f;\n"
18058                "const unsigned      g;\n"
18059                "Const unsigned      h;",
18060                Alignment);
18061 
18062   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
18063   verifyFormat("unsigned int *       a;\n"
18064                "int *                b;\n"
18065                "unsigned int Const * c;\n"
18066                "unsigned int const * d;\n"
18067                "unsigned int Const & e;\n"
18068                "unsigned int const & f;",
18069                Alignment);
18070   verifyFormat("Const unsigned int * c;\n"
18071                "const unsigned int * d;\n"
18072                "Const unsigned int & e;\n"
18073                "const unsigned int & f;\n"
18074                "const unsigned       g;\n"
18075                "Const unsigned       h;",
18076                Alignment);
18077 
18078   // See PR46529
18079   FormatStyle BracedAlign = getLLVMStyle();
18080   BracedAlign.AlignConsecutiveDeclarations.Enabled = true;
18081   verifyFormat("const auto result{[]() {\n"
18082                "  const auto something = 1;\n"
18083                "  return 2;\n"
18084                "}};",
18085                BracedAlign);
18086   verifyFormat("int foo{[]() {\n"
18087                "  int bar{0};\n"
18088                "  return 0;\n"
18089                "}()};",
18090                BracedAlign);
18091   BracedAlign.Cpp11BracedListStyle = false;
18092   verifyFormat("const auto result{ []() {\n"
18093                "  const auto something = 1;\n"
18094                "  return 2;\n"
18095                "} };",
18096                BracedAlign);
18097   verifyFormat("int foo{ []() {\n"
18098                "  int bar{ 0 };\n"
18099                "  return 0;\n"
18100                "}() };",
18101                BracedAlign);
18102 }
18103 
TEST_F(FormatTest,AlignWithLineBreaks)18104 TEST_F(FormatTest, AlignWithLineBreaks) {
18105   auto Style = getLLVMStyleWithColumns(120);
18106 
18107   EXPECT_EQ(Style.AlignConsecutiveAssignments,
18108             FormatStyle::AlignConsecutiveStyle(
18109                 {/*Enabled=*/false, /*AcrossEmptyLines=*/false,
18110                  /*AcrossComments=*/false, /*AlignCompound=*/false,
18111                  /*PadOperators=*/true}));
18112   EXPECT_EQ(Style.AlignConsecutiveDeclarations,
18113             FormatStyle::AlignConsecutiveStyle({}));
18114   verifyFormat("void foo() {\n"
18115                "  int myVar = 5;\n"
18116                "  double x = 3.14;\n"
18117                "  auto str = \"Hello \"\n"
18118                "             \"World\";\n"
18119                "  auto s = \"Hello \"\n"
18120                "           \"Again\";\n"
18121                "}",
18122                Style);
18123 
18124   // clang-format off
18125   verifyFormat("void foo() {\n"
18126                "  const int capacityBefore = Entries.capacity();\n"
18127                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18128                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18129                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18130                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18131                "}",
18132                Style);
18133   // clang-format on
18134 
18135   Style.AlignConsecutiveAssignments.Enabled = true;
18136   verifyFormat("void foo() {\n"
18137                "  int myVar = 5;\n"
18138                "  double x  = 3.14;\n"
18139                "  auto str  = \"Hello \"\n"
18140                "              \"World\";\n"
18141                "  auto s    = \"Hello \"\n"
18142                "              \"Again\";\n"
18143                "}",
18144                Style);
18145 
18146   // clang-format off
18147   verifyFormat("void foo() {\n"
18148                "  const int capacityBefore = Entries.capacity();\n"
18149                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18150                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18151                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18152                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18153                "}",
18154                Style);
18155   // clang-format on
18156 
18157   Style.AlignConsecutiveAssignments.Enabled = false;
18158   Style.AlignConsecutiveDeclarations.Enabled = true;
18159   verifyFormat("void foo() {\n"
18160                "  int    myVar = 5;\n"
18161                "  double x = 3.14;\n"
18162                "  auto   str = \"Hello \"\n"
18163                "               \"World\";\n"
18164                "  auto   s = \"Hello \"\n"
18165                "             \"Again\";\n"
18166                "}",
18167                Style);
18168 
18169   // clang-format off
18170   verifyFormat("void foo() {\n"
18171                "  const int  capacityBefore = Entries.capacity();\n"
18172                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18173                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18174                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18175                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18176                "}",
18177                Style);
18178   // clang-format on
18179 
18180   Style.AlignConsecutiveAssignments.Enabled = true;
18181   Style.AlignConsecutiveDeclarations.Enabled = true;
18182 
18183   verifyFormat("void foo() {\n"
18184                "  int    myVar = 5;\n"
18185                "  double x     = 3.14;\n"
18186                "  auto   str   = \"Hello \"\n"
18187                "                 \"World\";\n"
18188                "  auto   s     = \"Hello \"\n"
18189                "                 \"Again\";\n"
18190                "}",
18191                Style);
18192 
18193   // clang-format off
18194   verifyFormat("void foo() {\n"
18195                "  const int  capacityBefore = Entries.capacity();\n"
18196                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18197                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18198                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
18199                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
18200                "}",
18201                Style);
18202   // clang-format on
18203 
18204   Style = getLLVMStyleWithColumns(20);
18205   Style.AlignConsecutiveAssignments.Enabled = true;
18206   Style.IndentWidth = 4;
18207 
18208   verifyFormat("void foo() {\n"
18209                "    int i1 = 1;\n"
18210                "    int j  = 0;\n"
18211                "    int k  = bar(\n"
18212                "        argument1,\n"
18213                "        argument2);\n"
18214                "}",
18215                Style);
18216 
18217   verifyFormat("unsigned i = 0;\n"
18218                "int a[]    = {\n"
18219                "    1234567890,\n"
18220                "    -1234567890};",
18221                Style);
18222 
18223   Style.ColumnLimit = 120;
18224 
18225   // clang-format off
18226   verifyFormat("void SomeFunc() {\n"
18227                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18228                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18229                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18230                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18231                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
18232                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18233                "}",
18234                Style);
18235   // clang-format on
18236 
18237   Style.BinPackArguments = false;
18238 
18239   // clang-format off
18240   verifyFormat("void SomeFunc() {\n"
18241                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
18242                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18243                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
18244                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18245                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
18246                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
18247                "}",
18248                Style);
18249   // clang-format on
18250 }
18251 
TEST_F(FormatTest,AlignWithInitializerPeriods)18252 TEST_F(FormatTest, AlignWithInitializerPeriods) {
18253   auto Style = getLLVMStyleWithColumns(60);
18254 
18255   verifyFormat("void foo1(void) {\n"
18256                "  BYTE p[1] = 1;\n"
18257                "  A B = {.one_foooooooooooooooo = 2,\n"
18258                "         .two_fooooooooooooo = 3,\n"
18259                "         .three_fooooooooooooo = 4};\n"
18260                "  BYTE payload = 2;\n"
18261                "}",
18262                Style);
18263 
18264   Style.AlignConsecutiveAssignments.Enabled = true;
18265   Style.AlignConsecutiveDeclarations.Enabled = false;
18266   verifyFormat("void foo2(void) {\n"
18267                "  BYTE p[1]    = 1;\n"
18268                "  A B          = {.one_foooooooooooooooo = 2,\n"
18269                "                  .two_fooooooooooooo    = 3,\n"
18270                "                  .three_fooooooooooooo  = 4};\n"
18271                "  BYTE payload = 2;\n"
18272                "}",
18273                Style);
18274 
18275   Style.AlignConsecutiveAssignments.Enabled = false;
18276   Style.AlignConsecutiveDeclarations.Enabled = true;
18277   verifyFormat("void foo3(void) {\n"
18278                "  BYTE p[1] = 1;\n"
18279                "  A    B = {.one_foooooooooooooooo = 2,\n"
18280                "            .two_fooooooooooooo = 3,\n"
18281                "            .three_fooooooooooooo = 4};\n"
18282                "  BYTE payload = 2;\n"
18283                "}",
18284                Style);
18285 
18286   Style.AlignConsecutiveAssignments.Enabled = true;
18287   Style.AlignConsecutiveDeclarations.Enabled = true;
18288   verifyFormat("void foo4(void) {\n"
18289                "  BYTE p[1]    = 1;\n"
18290                "  A    B       = {.one_foooooooooooooooo = 2,\n"
18291                "                  .two_fooooooooooooo    = 3,\n"
18292                "                  .three_fooooooooooooo  = 4};\n"
18293                "  BYTE payload = 2;\n"
18294                "}",
18295                Style);
18296 }
18297 
TEST_F(FormatTest,LinuxBraceBreaking)18298 TEST_F(FormatTest, LinuxBraceBreaking) {
18299   FormatStyle LinuxBraceStyle = getLLVMStyle();
18300   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
18301   verifyFormat("namespace a\n"
18302                "{\n"
18303                "class A\n"
18304                "{\n"
18305                "  void f()\n"
18306                "  {\n"
18307                "    if (true) {\n"
18308                "      a();\n"
18309                "      b();\n"
18310                "    } else {\n"
18311                "      a();\n"
18312                "    }\n"
18313                "  }\n"
18314                "  void g() { return; }\n"
18315                "};\n"
18316                "struct B {\n"
18317                "  int x;\n"
18318                "};\n"
18319                "} // namespace a\n",
18320                LinuxBraceStyle);
18321   verifyFormat("enum X {\n"
18322                "  Y = 0,\n"
18323                "}\n",
18324                LinuxBraceStyle);
18325   verifyFormat("struct S {\n"
18326                "  int Type;\n"
18327                "  union {\n"
18328                "    int x;\n"
18329                "    double y;\n"
18330                "  } Value;\n"
18331                "  class C\n"
18332                "  {\n"
18333                "    MyFavoriteType Value;\n"
18334                "  } Class;\n"
18335                "}\n",
18336                LinuxBraceStyle);
18337 }
18338 
TEST_F(FormatTest,MozillaBraceBreaking)18339 TEST_F(FormatTest, MozillaBraceBreaking) {
18340   FormatStyle MozillaBraceStyle = getLLVMStyle();
18341   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
18342   MozillaBraceStyle.FixNamespaceComments = false;
18343   verifyFormat("namespace a {\n"
18344                "class A\n"
18345                "{\n"
18346                "  void f()\n"
18347                "  {\n"
18348                "    if (true) {\n"
18349                "      a();\n"
18350                "      b();\n"
18351                "    }\n"
18352                "  }\n"
18353                "  void g() { return; }\n"
18354                "};\n"
18355                "enum E\n"
18356                "{\n"
18357                "  A,\n"
18358                "  // foo\n"
18359                "  B,\n"
18360                "  C\n"
18361                "};\n"
18362                "struct B\n"
18363                "{\n"
18364                "  int x;\n"
18365                "};\n"
18366                "}\n",
18367                MozillaBraceStyle);
18368   verifyFormat("struct S\n"
18369                "{\n"
18370                "  int Type;\n"
18371                "  union\n"
18372                "  {\n"
18373                "    int x;\n"
18374                "    double y;\n"
18375                "  } Value;\n"
18376                "  class C\n"
18377                "  {\n"
18378                "    MyFavoriteType Value;\n"
18379                "  } Class;\n"
18380                "}\n",
18381                MozillaBraceStyle);
18382 }
18383 
TEST_F(FormatTest,StroustrupBraceBreaking)18384 TEST_F(FormatTest, StroustrupBraceBreaking) {
18385   FormatStyle StroustrupBraceStyle = getLLVMStyle();
18386   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18387   verifyFormat("namespace a {\n"
18388                "class A {\n"
18389                "  void f()\n"
18390                "  {\n"
18391                "    if (true) {\n"
18392                "      a();\n"
18393                "      b();\n"
18394                "    }\n"
18395                "  }\n"
18396                "  void g() { return; }\n"
18397                "};\n"
18398                "struct B {\n"
18399                "  int x;\n"
18400                "};\n"
18401                "} // namespace a\n",
18402                StroustrupBraceStyle);
18403 
18404   verifyFormat("void foo()\n"
18405                "{\n"
18406                "  if (a) {\n"
18407                "    a();\n"
18408                "  }\n"
18409                "  else {\n"
18410                "    b();\n"
18411                "  }\n"
18412                "}\n",
18413                StroustrupBraceStyle);
18414 
18415   verifyFormat("#ifdef _DEBUG\n"
18416                "int foo(int i = 0)\n"
18417                "#else\n"
18418                "int foo(int i = 5)\n"
18419                "#endif\n"
18420                "{\n"
18421                "  return i;\n"
18422                "}",
18423                StroustrupBraceStyle);
18424 
18425   verifyFormat("void foo() {}\n"
18426                "void bar()\n"
18427                "#ifdef _DEBUG\n"
18428                "{\n"
18429                "  foo();\n"
18430                "}\n"
18431                "#else\n"
18432                "{\n"
18433                "}\n"
18434                "#endif",
18435                StroustrupBraceStyle);
18436 
18437   verifyFormat("void foobar() { int i = 5; }\n"
18438                "#ifdef _DEBUG\n"
18439                "void bar() {}\n"
18440                "#else\n"
18441                "void bar() { foobar(); }\n"
18442                "#endif",
18443                StroustrupBraceStyle);
18444 }
18445 
TEST_F(FormatTest,AllmanBraceBreaking)18446 TEST_F(FormatTest, AllmanBraceBreaking) {
18447   FormatStyle AllmanBraceStyle = getLLVMStyle();
18448   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
18449 
18450   EXPECT_EQ("namespace a\n"
18451             "{\n"
18452             "void f();\n"
18453             "void g();\n"
18454             "} // namespace a\n",
18455             format("namespace a\n"
18456                    "{\n"
18457                    "void f();\n"
18458                    "void g();\n"
18459                    "}\n",
18460                    AllmanBraceStyle));
18461 
18462   verifyFormat("namespace a\n"
18463                "{\n"
18464                "class A\n"
18465                "{\n"
18466                "  void f()\n"
18467                "  {\n"
18468                "    if (true)\n"
18469                "    {\n"
18470                "      a();\n"
18471                "      b();\n"
18472                "    }\n"
18473                "  }\n"
18474                "  void g() { return; }\n"
18475                "};\n"
18476                "struct B\n"
18477                "{\n"
18478                "  int x;\n"
18479                "};\n"
18480                "union C\n"
18481                "{\n"
18482                "};\n"
18483                "} // namespace a",
18484                AllmanBraceStyle);
18485 
18486   verifyFormat("void f()\n"
18487                "{\n"
18488                "  if (true)\n"
18489                "  {\n"
18490                "    a();\n"
18491                "  }\n"
18492                "  else if (false)\n"
18493                "  {\n"
18494                "    b();\n"
18495                "  }\n"
18496                "  else\n"
18497                "  {\n"
18498                "    c();\n"
18499                "  }\n"
18500                "}\n",
18501                AllmanBraceStyle);
18502 
18503   verifyFormat("void f()\n"
18504                "{\n"
18505                "  for (int i = 0; i < 10; ++i)\n"
18506                "  {\n"
18507                "    a();\n"
18508                "  }\n"
18509                "  while (false)\n"
18510                "  {\n"
18511                "    b();\n"
18512                "  }\n"
18513                "  do\n"
18514                "  {\n"
18515                "    c();\n"
18516                "  } while (false)\n"
18517                "}\n",
18518                AllmanBraceStyle);
18519 
18520   verifyFormat("void f(int a)\n"
18521                "{\n"
18522                "  switch (a)\n"
18523                "  {\n"
18524                "  case 0:\n"
18525                "    break;\n"
18526                "  case 1:\n"
18527                "  {\n"
18528                "    break;\n"
18529                "  }\n"
18530                "  case 2:\n"
18531                "  {\n"
18532                "  }\n"
18533                "  break;\n"
18534                "  default:\n"
18535                "    break;\n"
18536                "  }\n"
18537                "}\n",
18538                AllmanBraceStyle);
18539 
18540   verifyFormat("enum X\n"
18541                "{\n"
18542                "  Y = 0,\n"
18543                "}\n",
18544                AllmanBraceStyle);
18545   verifyFormat("enum X\n"
18546                "{\n"
18547                "  Y = 0\n"
18548                "}\n",
18549                AllmanBraceStyle);
18550 
18551   verifyFormat("@interface BSApplicationController ()\n"
18552                "{\n"
18553                "@private\n"
18554                "  id _extraIvar;\n"
18555                "}\n"
18556                "@end\n",
18557                AllmanBraceStyle);
18558 
18559   verifyFormat("#ifdef _DEBUG\n"
18560                "int foo(int i = 0)\n"
18561                "#else\n"
18562                "int foo(int i = 5)\n"
18563                "#endif\n"
18564                "{\n"
18565                "  return i;\n"
18566                "}",
18567                AllmanBraceStyle);
18568 
18569   verifyFormat("void foo() {}\n"
18570                "void bar()\n"
18571                "#ifdef _DEBUG\n"
18572                "{\n"
18573                "  foo();\n"
18574                "}\n"
18575                "#else\n"
18576                "{\n"
18577                "}\n"
18578                "#endif",
18579                AllmanBraceStyle);
18580 
18581   verifyFormat("void foobar() { int i = 5; }\n"
18582                "#ifdef _DEBUG\n"
18583                "void bar() {}\n"
18584                "#else\n"
18585                "void bar() { foobar(); }\n"
18586                "#endif",
18587                AllmanBraceStyle);
18588 
18589   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
18590             FormatStyle::SLS_All);
18591 
18592   verifyFormat("[](int i) { return i + 2; };\n"
18593                "[](int i, int j)\n"
18594                "{\n"
18595                "  auto x = i + j;\n"
18596                "  auto y = i * j;\n"
18597                "  return x ^ y;\n"
18598                "};\n"
18599                "void foo()\n"
18600                "{\n"
18601                "  auto shortLambda = [](int i) { return i + 2; };\n"
18602                "  auto longLambda = [](int i, int j)\n"
18603                "  {\n"
18604                "    auto x = i + j;\n"
18605                "    auto y = i * j;\n"
18606                "    return x ^ y;\n"
18607                "  };\n"
18608                "}",
18609                AllmanBraceStyle);
18610 
18611   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18612 
18613   verifyFormat("[](int i)\n"
18614                "{\n"
18615                "  return i + 2;\n"
18616                "};\n"
18617                "[](int i, int j)\n"
18618                "{\n"
18619                "  auto x = i + j;\n"
18620                "  auto y = i * j;\n"
18621                "  return x ^ y;\n"
18622                "};\n"
18623                "void foo()\n"
18624                "{\n"
18625                "  auto shortLambda = [](int i)\n"
18626                "  {\n"
18627                "    return i + 2;\n"
18628                "  };\n"
18629                "  auto longLambda = [](int i, int j)\n"
18630                "  {\n"
18631                "    auto x = i + j;\n"
18632                "    auto y = i * j;\n"
18633                "    return x ^ y;\n"
18634                "  };\n"
18635                "}",
18636                AllmanBraceStyle);
18637 
18638   // Reset
18639   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
18640 
18641   // This shouldn't affect ObjC blocks..
18642   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
18643                "  // ...\n"
18644                "  int i;\n"
18645                "}];",
18646                AllmanBraceStyle);
18647   verifyFormat("void (^block)(void) = ^{\n"
18648                "  // ...\n"
18649                "  int i;\n"
18650                "};",
18651                AllmanBraceStyle);
18652   // .. or dict literals.
18653   verifyFormat("void f()\n"
18654                "{\n"
18655                "  // ...\n"
18656                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
18657                "}",
18658                AllmanBraceStyle);
18659   verifyFormat("void f()\n"
18660                "{\n"
18661                "  // ...\n"
18662                "  [object someMethod:@{a : @\"b\"}];\n"
18663                "}",
18664                AllmanBraceStyle);
18665   verifyFormat("int f()\n"
18666                "{ // comment\n"
18667                "  return 42;\n"
18668                "}",
18669                AllmanBraceStyle);
18670 
18671   AllmanBraceStyle.ColumnLimit = 19;
18672   verifyFormat("void f() { int i; }", AllmanBraceStyle);
18673   AllmanBraceStyle.ColumnLimit = 18;
18674   verifyFormat("void f()\n"
18675                "{\n"
18676                "  int i;\n"
18677                "}",
18678                AllmanBraceStyle);
18679   AllmanBraceStyle.ColumnLimit = 80;
18680 
18681   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
18682   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
18683       FormatStyle::SIS_WithoutElse;
18684   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
18685   verifyFormat("void f(bool b)\n"
18686                "{\n"
18687                "  if (b)\n"
18688                "  {\n"
18689                "    return;\n"
18690                "  }\n"
18691                "}\n",
18692                BreakBeforeBraceShortIfs);
18693   verifyFormat("void f(bool b)\n"
18694                "{\n"
18695                "  if constexpr (b)\n"
18696                "  {\n"
18697                "    return;\n"
18698                "  }\n"
18699                "}\n",
18700                BreakBeforeBraceShortIfs);
18701   verifyFormat("void f(bool b)\n"
18702                "{\n"
18703                "  if CONSTEXPR (b)\n"
18704                "  {\n"
18705                "    return;\n"
18706                "  }\n"
18707                "}\n",
18708                BreakBeforeBraceShortIfs);
18709   verifyFormat("void f(bool b)\n"
18710                "{\n"
18711                "  if (b) return;\n"
18712                "}\n",
18713                BreakBeforeBraceShortIfs);
18714   verifyFormat("void f(bool b)\n"
18715                "{\n"
18716                "  if constexpr (b) return;\n"
18717                "}\n",
18718                BreakBeforeBraceShortIfs);
18719   verifyFormat("void f(bool b)\n"
18720                "{\n"
18721                "  if CONSTEXPR (b) return;\n"
18722                "}\n",
18723                BreakBeforeBraceShortIfs);
18724   verifyFormat("void f(bool b)\n"
18725                "{\n"
18726                "  while (b)\n"
18727                "  {\n"
18728                "    return;\n"
18729                "  }\n"
18730                "}\n",
18731                BreakBeforeBraceShortIfs);
18732 }
18733 
TEST_F(FormatTest,WhitesmithsBraceBreaking)18734 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
18735   FormatStyle WhitesmithsBraceStyle = getLLVMStyleWithColumns(0);
18736   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
18737 
18738   // Make a few changes to the style for testing purposes
18739   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
18740       FormatStyle::SFS_Empty;
18741   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
18742 
18743   // FIXME: this test case can't decide whether there should be a blank line
18744   // after the ~D() line or not. It adds one if one doesn't exist in the test
18745   // and it removes the line if one exists.
18746   /*
18747   verifyFormat("class A;\n"
18748                "namespace B\n"
18749                "  {\n"
18750                "class C;\n"
18751                "// Comment\n"
18752                "class D\n"
18753                "  {\n"
18754                "public:\n"
18755                "  D();\n"
18756                "  ~D() {}\n"
18757                "private:\n"
18758                "  enum E\n"
18759                "    {\n"
18760                "    F\n"
18761                "    }\n"
18762                "  };\n"
18763                "  } // namespace B\n",
18764                WhitesmithsBraceStyle);
18765   */
18766 
18767   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
18768   verifyFormat("namespace a\n"
18769                "  {\n"
18770                "class A\n"
18771                "  {\n"
18772                "  void f()\n"
18773                "    {\n"
18774                "    if (true)\n"
18775                "      {\n"
18776                "      a();\n"
18777                "      b();\n"
18778                "      }\n"
18779                "    }\n"
18780                "  void g()\n"
18781                "    {\n"
18782                "    return;\n"
18783                "    }\n"
18784                "  };\n"
18785                "struct B\n"
18786                "  {\n"
18787                "  int x;\n"
18788                "  };\n"
18789                "  } // namespace a",
18790                WhitesmithsBraceStyle);
18791 
18792   verifyFormat("namespace a\n"
18793                "  {\n"
18794                "namespace b\n"
18795                "  {\n"
18796                "class A\n"
18797                "  {\n"
18798                "  void f()\n"
18799                "    {\n"
18800                "    if (true)\n"
18801                "      {\n"
18802                "      a();\n"
18803                "      b();\n"
18804                "      }\n"
18805                "    }\n"
18806                "  void g()\n"
18807                "    {\n"
18808                "    return;\n"
18809                "    }\n"
18810                "  };\n"
18811                "struct B\n"
18812                "  {\n"
18813                "  int x;\n"
18814                "  };\n"
18815                "  } // namespace b\n"
18816                "  } // namespace a",
18817                WhitesmithsBraceStyle);
18818 
18819   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
18820   verifyFormat("namespace a\n"
18821                "  {\n"
18822                "namespace b\n"
18823                "  {\n"
18824                "  class A\n"
18825                "    {\n"
18826                "    void f()\n"
18827                "      {\n"
18828                "      if (true)\n"
18829                "        {\n"
18830                "        a();\n"
18831                "        b();\n"
18832                "        }\n"
18833                "      }\n"
18834                "    void g()\n"
18835                "      {\n"
18836                "      return;\n"
18837                "      }\n"
18838                "    };\n"
18839                "  struct B\n"
18840                "    {\n"
18841                "    int x;\n"
18842                "    };\n"
18843                "  } // namespace b\n"
18844                "  } // namespace a",
18845                WhitesmithsBraceStyle);
18846 
18847   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
18848   verifyFormat("namespace a\n"
18849                "  {\n"
18850                "  namespace b\n"
18851                "    {\n"
18852                "    class A\n"
18853                "      {\n"
18854                "      void f()\n"
18855                "        {\n"
18856                "        if (true)\n"
18857                "          {\n"
18858                "          a();\n"
18859                "          b();\n"
18860                "          }\n"
18861                "        }\n"
18862                "      void g()\n"
18863                "        {\n"
18864                "        return;\n"
18865                "        }\n"
18866                "      };\n"
18867                "    struct B\n"
18868                "      {\n"
18869                "      int x;\n"
18870                "      };\n"
18871                "    } // namespace b\n"
18872                "  }   // namespace a",
18873                WhitesmithsBraceStyle);
18874 
18875   verifyFormat("void f()\n"
18876                "  {\n"
18877                "  if (true)\n"
18878                "    {\n"
18879                "    a();\n"
18880                "    }\n"
18881                "  else if (false)\n"
18882                "    {\n"
18883                "    b();\n"
18884                "    }\n"
18885                "  else\n"
18886                "    {\n"
18887                "    c();\n"
18888                "    }\n"
18889                "  }\n",
18890                WhitesmithsBraceStyle);
18891 
18892   verifyFormat("void f()\n"
18893                "  {\n"
18894                "  for (int i = 0; i < 10; ++i)\n"
18895                "    {\n"
18896                "    a();\n"
18897                "    }\n"
18898                "  while (false)\n"
18899                "    {\n"
18900                "    b();\n"
18901                "    }\n"
18902                "  do\n"
18903                "    {\n"
18904                "    c();\n"
18905                "    } while (false)\n"
18906                "  }\n",
18907                WhitesmithsBraceStyle);
18908 
18909   WhitesmithsBraceStyle.IndentCaseLabels = true;
18910   verifyFormat("void switchTest1(int a)\n"
18911                "  {\n"
18912                "  switch (a)\n"
18913                "    {\n"
18914                "    case 2:\n"
18915                "      {\n"
18916                "      }\n"
18917                "      break;\n"
18918                "    }\n"
18919                "  }\n",
18920                WhitesmithsBraceStyle);
18921 
18922   verifyFormat("void switchTest2(int a)\n"
18923                "  {\n"
18924                "  switch (a)\n"
18925                "    {\n"
18926                "    case 0:\n"
18927                "      break;\n"
18928                "    case 1:\n"
18929                "      {\n"
18930                "      break;\n"
18931                "      }\n"
18932                "    case 2:\n"
18933                "      {\n"
18934                "      }\n"
18935                "      break;\n"
18936                "    default:\n"
18937                "      break;\n"
18938                "    }\n"
18939                "  }\n",
18940                WhitesmithsBraceStyle);
18941 
18942   verifyFormat("void switchTest3(int a)\n"
18943                "  {\n"
18944                "  switch (a)\n"
18945                "    {\n"
18946                "    case 0:\n"
18947                "      {\n"
18948                "      foo(x);\n"
18949                "      }\n"
18950                "      break;\n"
18951                "    default:\n"
18952                "      {\n"
18953                "      foo(1);\n"
18954                "      }\n"
18955                "      break;\n"
18956                "    }\n"
18957                "  }\n",
18958                WhitesmithsBraceStyle);
18959 
18960   WhitesmithsBraceStyle.IndentCaseLabels = false;
18961 
18962   verifyFormat("void switchTest4(int a)\n"
18963                "  {\n"
18964                "  switch (a)\n"
18965                "    {\n"
18966                "  case 2:\n"
18967                "    {\n"
18968                "    }\n"
18969                "    break;\n"
18970                "    }\n"
18971                "  }\n",
18972                WhitesmithsBraceStyle);
18973 
18974   verifyFormat("void switchTest5(int a)\n"
18975                "  {\n"
18976                "  switch (a)\n"
18977                "    {\n"
18978                "  case 0:\n"
18979                "    break;\n"
18980                "  case 1:\n"
18981                "    {\n"
18982                "    foo();\n"
18983                "    break;\n"
18984                "    }\n"
18985                "  case 2:\n"
18986                "    {\n"
18987                "    }\n"
18988                "    break;\n"
18989                "  default:\n"
18990                "    break;\n"
18991                "    }\n"
18992                "  }\n",
18993                WhitesmithsBraceStyle);
18994 
18995   verifyFormat("void switchTest6(int a)\n"
18996                "  {\n"
18997                "  switch (a)\n"
18998                "    {\n"
18999                "  case 0:\n"
19000                "    {\n"
19001                "    foo(x);\n"
19002                "    }\n"
19003                "    break;\n"
19004                "  default:\n"
19005                "    {\n"
19006                "    foo(1);\n"
19007                "    }\n"
19008                "    break;\n"
19009                "    }\n"
19010                "  }\n",
19011                WhitesmithsBraceStyle);
19012 
19013   verifyFormat("enum X\n"
19014                "  {\n"
19015                "  Y = 0, // testing\n"
19016                "  }\n",
19017                WhitesmithsBraceStyle);
19018 
19019   verifyFormat("enum X\n"
19020                "  {\n"
19021                "  Y = 0\n"
19022                "  }\n",
19023                WhitesmithsBraceStyle);
19024   verifyFormat("enum X\n"
19025                "  {\n"
19026                "  Y = 0,\n"
19027                "  Z = 1\n"
19028                "  };\n",
19029                WhitesmithsBraceStyle);
19030 
19031   verifyFormat("@interface BSApplicationController ()\n"
19032                "  {\n"
19033                "@private\n"
19034                "  id _extraIvar;\n"
19035                "  }\n"
19036                "@end\n",
19037                WhitesmithsBraceStyle);
19038 
19039   verifyFormat("#ifdef _DEBUG\n"
19040                "int foo(int i = 0)\n"
19041                "#else\n"
19042                "int foo(int i = 5)\n"
19043                "#endif\n"
19044                "  {\n"
19045                "  return i;\n"
19046                "  }",
19047                WhitesmithsBraceStyle);
19048 
19049   verifyFormat("void foo() {}\n"
19050                "void bar()\n"
19051                "#ifdef _DEBUG\n"
19052                "  {\n"
19053                "  foo();\n"
19054                "  }\n"
19055                "#else\n"
19056                "  {\n"
19057                "  }\n"
19058                "#endif",
19059                WhitesmithsBraceStyle);
19060 
19061   verifyFormat("void foobar()\n"
19062                "  {\n"
19063                "  int i = 5;\n"
19064                "  }\n"
19065                "#ifdef _DEBUG\n"
19066                "void bar()\n"
19067                "  {\n"
19068                "  }\n"
19069                "#else\n"
19070                "void bar()\n"
19071                "  {\n"
19072                "  foobar();\n"
19073                "  }\n"
19074                "#endif",
19075                WhitesmithsBraceStyle);
19076 
19077   // This shouldn't affect ObjC blocks..
19078   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
19079                "  // ...\n"
19080                "  int i;\n"
19081                "}];",
19082                WhitesmithsBraceStyle);
19083   verifyFormat("void (^block)(void) = ^{\n"
19084                "  // ...\n"
19085                "  int i;\n"
19086                "};",
19087                WhitesmithsBraceStyle);
19088   // .. or dict literals.
19089   verifyFormat("void f()\n"
19090                "  {\n"
19091                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
19092                "  }",
19093                WhitesmithsBraceStyle);
19094 
19095   verifyFormat("int f()\n"
19096                "  { // comment\n"
19097                "  return 42;\n"
19098                "  }",
19099                WhitesmithsBraceStyle);
19100 
19101   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
19102   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
19103       FormatStyle::SIS_OnlyFirstIf;
19104   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
19105   verifyFormat("void f(bool b)\n"
19106                "  {\n"
19107                "  if (b)\n"
19108                "    {\n"
19109                "    return;\n"
19110                "    }\n"
19111                "  }\n",
19112                BreakBeforeBraceShortIfs);
19113   verifyFormat("void f(bool b)\n"
19114                "  {\n"
19115                "  if (b) return;\n"
19116                "  }\n",
19117                BreakBeforeBraceShortIfs);
19118   verifyFormat("void f(bool b)\n"
19119                "  {\n"
19120                "  while (b)\n"
19121                "    {\n"
19122                "    return;\n"
19123                "    }\n"
19124                "  }\n",
19125                BreakBeforeBraceShortIfs);
19126 }
19127 
TEST_F(FormatTest,GNUBraceBreaking)19128 TEST_F(FormatTest, GNUBraceBreaking) {
19129   FormatStyle GNUBraceStyle = getLLVMStyle();
19130   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
19131   verifyFormat("namespace a\n"
19132                "{\n"
19133                "class A\n"
19134                "{\n"
19135                "  void f()\n"
19136                "  {\n"
19137                "    int a;\n"
19138                "    {\n"
19139                "      int b;\n"
19140                "    }\n"
19141                "    if (true)\n"
19142                "      {\n"
19143                "        a();\n"
19144                "        b();\n"
19145                "      }\n"
19146                "  }\n"
19147                "  void g() { return; }\n"
19148                "}\n"
19149                "} // namespace a",
19150                GNUBraceStyle);
19151 
19152   verifyFormat("void f()\n"
19153                "{\n"
19154                "  if (true)\n"
19155                "    {\n"
19156                "      a();\n"
19157                "    }\n"
19158                "  else if (false)\n"
19159                "    {\n"
19160                "      b();\n"
19161                "    }\n"
19162                "  else\n"
19163                "    {\n"
19164                "      c();\n"
19165                "    }\n"
19166                "}\n",
19167                GNUBraceStyle);
19168 
19169   verifyFormat("void f()\n"
19170                "{\n"
19171                "  for (int i = 0; i < 10; ++i)\n"
19172                "    {\n"
19173                "      a();\n"
19174                "    }\n"
19175                "  while (false)\n"
19176                "    {\n"
19177                "      b();\n"
19178                "    }\n"
19179                "  do\n"
19180                "    {\n"
19181                "      c();\n"
19182                "    }\n"
19183                "  while (false);\n"
19184                "}\n",
19185                GNUBraceStyle);
19186 
19187   verifyFormat("void f(int a)\n"
19188                "{\n"
19189                "  switch (a)\n"
19190                "    {\n"
19191                "    case 0:\n"
19192                "      break;\n"
19193                "    case 1:\n"
19194                "      {\n"
19195                "        break;\n"
19196                "      }\n"
19197                "    case 2:\n"
19198                "      {\n"
19199                "      }\n"
19200                "      break;\n"
19201                "    default:\n"
19202                "      break;\n"
19203                "    }\n"
19204                "}\n",
19205                GNUBraceStyle);
19206 
19207   verifyFormat("enum X\n"
19208                "{\n"
19209                "  Y = 0,\n"
19210                "}\n",
19211                GNUBraceStyle);
19212 
19213   verifyFormat("@interface BSApplicationController ()\n"
19214                "{\n"
19215                "@private\n"
19216                "  id _extraIvar;\n"
19217                "}\n"
19218                "@end\n",
19219                GNUBraceStyle);
19220 
19221   verifyFormat("#ifdef _DEBUG\n"
19222                "int foo(int i = 0)\n"
19223                "#else\n"
19224                "int foo(int i = 5)\n"
19225                "#endif\n"
19226                "{\n"
19227                "  return i;\n"
19228                "}",
19229                GNUBraceStyle);
19230 
19231   verifyFormat("void foo() {}\n"
19232                "void bar()\n"
19233                "#ifdef _DEBUG\n"
19234                "{\n"
19235                "  foo();\n"
19236                "}\n"
19237                "#else\n"
19238                "{\n"
19239                "}\n"
19240                "#endif",
19241                GNUBraceStyle);
19242 
19243   verifyFormat("void foobar() { int i = 5; }\n"
19244                "#ifdef _DEBUG\n"
19245                "void bar() {}\n"
19246                "#else\n"
19247                "void bar() { foobar(); }\n"
19248                "#endif",
19249                GNUBraceStyle);
19250 }
19251 
TEST_F(FormatTest,WebKitBraceBreaking)19252 TEST_F(FormatTest, WebKitBraceBreaking) {
19253   FormatStyle WebKitBraceStyle = getLLVMStyle();
19254   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
19255   WebKitBraceStyle.FixNamespaceComments = false;
19256   verifyFormat("namespace a {\n"
19257                "class A {\n"
19258                "  void f()\n"
19259                "  {\n"
19260                "    if (true) {\n"
19261                "      a();\n"
19262                "      b();\n"
19263                "    }\n"
19264                "  }\n"
19265                "  void g() { return; }\n"
19266                "};\n"
19267                "enum E {\n"
19268                "  A,\n"
19269                "  // foo\n"
19270                "  B,\n"
19271                "  C\n"
19272                "};\n"
19273                "struct B {\n"
19274                "  int x;\n"
19275                "};\n"
19276                "}\n",
19277                WebKitBraceStyle);
19278   verifyFormat("struct S {\n"
19279                "  int Type;\n"
19280                "  union {\n"
19281                "    int x;\n"
19282                "    double y;\n"
19283                "  } Value;\n"
19284                "  class C {\n"
19285                "    MyFavoriteType Value;\n"
19286                "  } Class;\n"
19287                "};\n",
19288                WebKitBraceStyle);
19289 }
19290 
TEST_F(FormatTest,CatchExceptionReferenceBinding)19291 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
19292   verifyFormat("void f() {\n"
19293                "  try {\n"
19294                "  } catch (const Exception &e) {\n"
19295                "  }\n"
19296                "}\n",
19297                getLLVMStyle());
19298 }
19299 
TEST_F(FormatTest,CatchAlignArrayOfStructuresRightAlignment)19300 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
19301   auto Style = getLLVMStyle();
19302   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19303   Style.AlignConsecutiveAssignments.Enabled = true;
19304   Style.AlignConsecutiveDeclarations.Enabled = true;
19305   verifyFormat("struct test demo[] = {\n"
19306                "    {56,    23, \"hello\"},\n"
19307                "    {-1, 93463, \"world\"},\n"
19308                "    { 7,     5,    \"!!\"}\n"
19309                "};\n",
19310                Style);
19311 
19312   verifyFormat("struct test demo[] = {\n"
19313                "    {56,    23, \"hello\"}, // first line\n"
19314                "    {-1, 93463, \"world\"}, // second line\n"
19315                "    { 7,     5,    \"!!\"}  // third line\n"
19316                "};\n",
19317                Style);
19318 
19319   verifyFormat("struct test demo[4] = {\n"
19320                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19321                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19322                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19323                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19324                "};\n",
19325                Style);
19326 
19327   verifyFormat("struct test demo[3] = {\n"
19328                "    {56,    23, \"hello\"},\n"
19329                "    {-1, 93463, \"world\"},\n"
19330                "    { 7,     5,    \"!!\"}\n"
19331                "};\n",
19332                Style);
19333 
19334   verifyFormat("struct test demo[3] = {\n"
19335                "    {int{56},    23, \"hello\"},\n"
19336                "    {int{-1}, 93463, \"world\"},\n"
19337                "    { int{7},     5,    \"!!\"}\n"
19338                "};\n",
19339                Style);
19340 
19341   verifyFormat("struct test demo[] = {\n"
19342                "    {56,    23, \"hello\"},\n"
19343                "    {-1, 93463, \"world\"},\n"
19344                "    { 7,     5,    \"!!\"},\n"
19345                "};\n",
19346                Style);
19347 
19348   verifyFormat("test demo[] = {\n"
19349                "    {56,    23, \"hello\"},\n"
19350                "    {-1, 93463, \"world\"},\n"
19351                "    { 7,     5,    \"!!\"},\n"
19352                "};\n",
19353                Style);
19354 
19355   verifyFormat("demo = std::array<struct test, 3>{\n"
19356                "    test{56,    23, \"hello\"},\n"
19357                "    test{-1, 93463, \"world\"},\n"
19358                "    test{ 7,     5,    \"!!\"},\n"
19359                "};\n",
19360                Style);
19361 
19362   verifyFormat("test demo[] = {\n"
19363                "    {56,    23, \"hello\"},\n"
19364                "#if X\n"
19365                "    {-1, 93463, \"world\"},\n"
19366                "#endif\n"
19367                "    { 7,     5,    \"!!\"}\n"
19368                "};\n",
19369                Style);
19370 
19371   verifyFormat(
19372       "test demo[] = {\n"
19373       "    { 7,    23,\n"
19374       "     \"hello world i am a very long line that really, in any\"\n"
19375       "     \"just world, ought to be split over multiple lines\"},\n"
19376       "    {-1, 93463,                                  \"world\"},\n"
19377       "    {56,     5,                                     \"!!\"}\n"
19378       "};\n",
19379       Style);
19380 
19381   verifyFormat("return GradForUnaryCwise(g, {\n"
19382                "                                {{\"sign\"}, \"Sign\",  "
19383                "  {\"x\", \"dy\"}},\n"
19384                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
19385                ", \"sign\"}},\n"
19386                "});\n",
19387                Style);
19388 
19389   Style.ColumnLimit = 0;
19390   EXPECT_EQ(
19391       "test demo[] = {\n"
19392       "    {56,    23, \"hello world i am a very long line that really, "
19393       "in any just world, ought to be split over multiple lines\"},\n"
19394       "    {-1, 93463,                                                  "
19395       "                                                 \"world\"},\n"
19396       "    { 7,     5,                                                  "
19397       "                                                    \"!!\"},\n"
19398       "};",
19399       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19400              "that really, in any just world, ought to be split over multiple "
19401              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19402              Style));
19403 
19404   Style.ColumnLimit = 80;
19405   verifyFormat("test demo[] = {\n"
19406                "    {56,    23, /* a comment */ \"hello\"},\n"
19407                "    {-1, 93463,                 \"world\"},\n"
19408                "    { 7,     5,                    \"!!\"}\n"
19409                "};\n",
19410                Style);
19411 
19412   verifyFormat("test demo[] = {\n"
19413                "    {56,    23,                    \"hello\"},\n"
19414                "    {-1, 93463, \"world\" /* comment here */},\n"
19415                "    { 7,     5,                       \"!!\"}\n"
19416                "};\n",
19417                Style);
19418 
19419   verifyFormat("test demo[] = {\n"
19420                "    {56, /* a comment */ 23, \"hello\"},\n"
19421                "    {-1,              93463, \"world\"},\n"
19422                "    { 7,                  5,    \"!!\"}\n"
19423                "};\n",
19424                Style);
19425 
19426   Style.ColumnLimit = 20;
19427   EXPECT_EQ(
19428       "demo = std::array<\n"
19429       "    struct test, 3>{\n"
19430       "    test{\n"
19431       "         56,    23,\n"
19432       "         \"hello \"\n"
19433       "         \"world i \"\n"
19434       "         \"am a very \"\n"
19435       "         \"long line \"\n"
19436       "         \"that \"\n"
19437       "         \"really, \"\n"
19438       "         \"in any \"\n"
19439       "         \"just \"\n"
19440       "         \"world, \"\n"
19441       "         \"ought to \"\n"
19442       "         \"be split \"\n"
19443       "         \"over \"\n"
19444       "         \"multiple \"\n"
19445       "         \"lines\"},\n"
19446       "    test{-1, 93463,\n"
19447       "         \"world\"},\n"
19448       "    test{ 7,     5,\n"
19449       "         \"!!\"   },\n"
19450       "};",
19451       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19452              "i am a very long line that really, in any just world, ought "
19453              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19454              "test{7, 5, \"!!\"},};",
19455              Style));
19456   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19457   Style = getLLVMStyleWithColumns(50);
19458   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19459   verifyFormat("static A x = {\n"
19460                "    {{init1, init2, init3, init4},\n"
19461                "     {init1, init2, init3, init4}}\n"
19462                "};",
19463                Style);
19464   // TODO: Fix the indentations below when this option is fully functional.
19465   verifyFormat("int a[][] = {\n"
19466                "    {\n"
19467                "     {0, 2}, //\n"
19468                " {1, 2}  //\n"
19469                "    }\n"
19470                "};",
19471                Style);
19472   Style.ColumnLimit = 100;
19473   EXPECT_EQ(
19474       "test demo[] = {\n"
19475       "    {56,    23,\n"
19476       "     \"hello world i am a very long line that really, in any just world"
19477       ", ought to be split over \"\n"
19478       "     \"multiple lines\"  },\n"
19479       "    {-1, 93463, \"world\"},\n"
19480       "    { 7,     5,    \"!!\"},\n"
19481       "};",
19482       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19483              "that really, in any just world, ought to be split over multiple "
19484              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19485              Style));
19486 
19487   Style = getLLVMStyleWithColumns(50);
19488   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
19489   verifyFormat("struct test demo[] = {\n"
19490                "    {56,    23, \"hello\"},\n"
19491                "    {-1, 93463, \"world\"},\n"
19492                "    { 7,     5,    \"!!\"}\n"
19493                "};\n"
19494                "static A x = {\n"
19495                "    {{init1, init2, init3, init4},\n"
19496                "     {init1, init2, init3, init4}}\n"
19497                "};",
19498                Style);
19499   Style.ColumnLimit = 100;
19500   Style.AlignConsecutiveAssignments.AcrossComments = true;
19501   Style.AlignConsecutiveDeclarations.AcrossComments = true;
19502   verifyFormat("struct test demo[] = {\n"
19503                "    {56,    23, \"hello\"},\n"
19504                "    {-1, 93463, \"world\"},\n"
19505                "    { 7,     5,    \"!!\"}\n"
19506                "};\n"
19507                "struct test demo[4] = {\n"
19508                "    { 56,    23, 21,       \"oh\"}, // first line\n"
19509                "    { -1, 93463, 22,       \"my\"}, // second line\n"
19510                "    {  7,     5,  1, \"goodness\"}  // third line\n"
19511                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
19512                "};\n",
19513                Style);
19514   EXPECT_EQ(
19515       "test demo[] = {\n"
19516       "    {56,\n"
19517       "     \"hello world i am a very long line that really, in any just world"
19518       ", ought to be split over \"\n"
19519       "     \"multiple lines\",    23},\n"
19520       "    {-1,      \"world\", 93463},\n"
19521       "    { 7,         \"!!\",     5},\n"
19522       "};",
19523       format("test demo[] = {{56, \"hello world i am a very long line "
19524              "that really, in any just world, ought to be split over multiple "
19525              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
19526              Style));
19527 }
19528 
TEST_F(FormatTest,CatchAlignArrayOfStructuresLeftAlignment)19529 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
19530   auto Style = getLLVMStyle();
19531   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19532   /* FIXME: This case gets misformatted.
19533   verifyFormat("auto foo = Items{\n"
19534                "    Section{0, bar(), },\n"
19535                "    Section{1, boo()  }\n"
19536                "};\n",
19537                Style);
19538   */
19539   verifyFormat("auto foo = Items{\n"
19540                "    Section{\n"
19541                "            0, bar(),\n"
19542                "            }\n"
19543                "};\n",
19544                Style);
19545   verifyFormat("struct test demo[] = {\n"
19546                "    {56, 23,    \"hello\"},\n"
19547                "    {-1, 93463, \"world\"},\n"
19548                "    {7,  5,     \"!!\"   }\n"
19549                "};\n",
19550                Style);
19551   verifyFormat("struct test demo[] = {\n"
19552                "    {56, 23,    \"hello\"}, // first line\n"
19553                "    {-1, 93463, \"world\"}, // second line\n"
19554                "    {7,  5,     \"!!\"   }  // third line\n"
19555                "};\n",
19556                Style);
19557   verifyFormat("struct test demo[4] = {\n"
19558                "    {56,  23,    21, \"oh\"      }, // first line\n"
19559                "    {-1,  93463, 22, \"my\"      }, // second line\n"
19560                "    {7,   5,     1,  \"goodness\"}  // third line\n"
19561                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
19562                "};\n",
19563                Style);
19564   verifyFormat("struct test demo[3] = {\n"
19565                "    {56, 23,    \"hello\"},\n"
19566                "    {-1, 93463, \"world\"},\n"
19567                "    {7,  5,     \"!!\"   }\n"
19568                "};\n",
19569                Style);
19570 
19571   verifyFormat("struct test demo[3] = {\n"
19572                "    {int{56}, 23,    \"hello\"},\n"
19573                "    {int{-1}, 93463, \"world\"},\n"
19574                "    {int{7},  5,     \"!!\"   }\n"
19575                "};\n",
19576                Style);
19577   verifyFormat("struct test demo[] = {\n"
19578                "    {56, 23,    \"hello\"},\n"
19579                "    {-1, 93463, \"world\"},\n"
19580                "    {7,  5,     \"!!\"   },\n"
19581                "};\n",
19582                Style);
19583   verifyFormat("test demo[] = {\n"
19584                "    {56, 23,    \"hello\"},\n"
19585                "    {-1, 93463, \"world\"},\n"
19586                "    {7,  5,     \"!!\"   },\n"
19587                "};\n",
19588                Style);
19589   verifyFormat("demo = std::array<struct test, 3>{\n"
19590                "    test{56, 23,    \"hello\"},\n"
19591                "    test{-1, 93463, \"world\"},\n"
19592                "    test{7,  5,     \"!!\"   },\n"
19593                "};\n",
19594                Style);
19595   verifyFormat("test demo[] = {\n"
19596                "    {56, 23,    \"hello\"},\n"
19597                "#if X\n"
19598                "    {-1, 93463, \"world\"},\n"
19599                "#endif\n"
19600                "    {7,  5,     \"!!\"   }\n"
19601                "};\n",
19602                Style);
19603   verifyFormat(
19604       "test demo[] = {\n"
19605       "    {7,  23,\n"
19606       "     \"hello world i am a very long line that really, in any\"\n"
19607       "     \"just world, ought to be split over multiple lines\"},\n"
19608       "    {-1, 93463, \"world\"                                 },\n"
19609       "    {56, 5,     \"!!\"                                    }\n"
19610       "};\n",
19611       Style);
19612 
19613   verifyFormat("return GradForUnaryCwise(g, {\n"
19614                "                                {{\"sign\"}, \"Sign\", {\"x\", "
19615                "\"dy\"}   },\n"
19616                "                                {{\"dx\"},   \"Mul\",  "
19617                "{\"dy\", \"sign\"}},\n"
19618                "});\n",
19619                Style);
19620 
19621   Style.ColumnLimit = 0;
19622   EXPECT_EQ(
19623       "test demo[] = {\n"
19624       "    {56, 23,    \"hello world i am a very long line that really, in any "
19625       "just world, ought to be split over multiple lines\"},\n"
19626       "    {-1, 93463, \"world\"                                               "
19627       "                                                   },\n"
19628       "    {7,  5,     \"!!\"                                                  "
19629       "                                                   },\n"
19630       "};",
19631       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19632              "that really, in any just world, ought to be split over multiple "
19633              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19634              Style));
19635 
19636   Style.ColumnLimit = 80;
19637   verifyFormat("test demo[] = {\n"
19638                "    {56, 23,    /* a comment */ \"hello\"},\n"
19639                "    {-1, 93463, \"world\"                },\n"
19640                "    {7,  5,     \"!!\"                   }\n"
19641                "};\n",
19642                Style);
19643 
19644   verifyFormat("test demo[] = {\n"
19645                "    {56, 23,    \"hello\"                   },\n"
19646                "    {-1, 93463, \"world\" /* comment here */},\n"
19647                "    {7,  5,     \"!!\"                      }\n"
19648                "};\n",
19649                Style);
19650 
19651   verifyFormat("test demo[] = {\n"
19652                "    {56, /* a comment */ 23, \"hello\"},\n"
19653                "    {-1, 93463,              \"world\"},\n"
19654                "    {7,  5,                  \"!!\"   }\n"
19655                "};\n",
19656                Style);
19657 
19658   Style.ColumnLimit = 20;
19659   EXPECT_EQ(
19660       "demo = std::array<\n"
19661       "    struct test, 3>{\n"
19662       "    test{\n"
19663       "         56, 23,\n"
19664       "         \"hello \"\n"
19665       "         \"world i \"\n"
19666       "         \"am a very \"\n"
19667       "         \"long line \"\n"
19668       "         \"that \"\n"
19669       "         \"really, \"\n"
19670       "         \"in any \"\n"
19671       "         \"just \"\n"
19672       "         \"world, \"\n"
19673       "         \"ought to \"\n"
19674       "         \"be split \"\n"
19675       "         \"over \"\n"
19676       "         \"multiple \"\n"
19677       "         \"lines\"},\n"
19678       "    test{-1, 93463,\n"
19679       "         \"world\"},\n"
19680       "    test{7,  5,\n"
19681       "         \"!!\"   },\n"
19682       "};",
19683       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
19684              "i am a very long line that really, in any just world, ought "
19685              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
19686              "test{7, 5, \"!!\"},};",
19687              Style));
19688 
19689   // This caused a core dump by enabling Alignment in the LLVMStyle globally
19690   Style = getLLVMStyleWithColumns(50);
19691   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
19692   verifyFormat("static A x = {\n"
19693                "    {{init1, init2, init3, init4},\n"
19694                "     {init1, init2, init3, init4}}\n"
19695                "};",
19696                Style);
19697   Style.ColumnLimit = 100;
19698   EXPECT_EQ(
19699       "test demo[] = {\n"
19700       "    {56, 23,\n"
19701       "     \"hello world i am a very long line that really, in any just world"
19702       ", ought to be split over \"\n"
19703       "     \"multiple lines\"  },\n"
19704       "    {-1, 93463, \"world\"},\n"
19705       "    {7,  5,     \"!!\"   },\n"
19706       "};",
19707       format("test demo[] = {{56, 23, \"hello world i am a very long line "
19708              "that really, in any just world, ought to be split over multiple "
19709              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
19710              Style));
19711 }
19712 
TEST_F(FormatTest,UnderstandsPragmas)19713 TEST_F(FormatTest, UnderstandsPragmas) {
19714   verifyFormat("#pragma omp reduction(| : var)");
19715   verifyFormat("#pragma omp reduction(+ : var)");
19716 
19717   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
19718             "(including parentheses).",
19719             format("#pragma    mark   Any non-hyphenated or hyphenated string "
19720                    "(including parentheses)."));
19721 }
19722 
TEST_F(FormatTest,UnderstandPragmaOption)19723 TEST_F(FormatTest, UnderstandPragmaOption) {
19724   verifyFormat("#pragma option -C -A");
19725 
19726   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
19727 }
19728 
TEST_F(FormatTest,UnderstandPragmaRegion)19729 TEST_F(FormatTest, UnderstandPragmaRegion) {
19730   auto Style = getLLVMStyleWithColumns(0);
19731   verifyFormat("#pragma region TEST(FOO : BAR)", Style);
19732 
19733   EXPECT_EQ("#pragma region TEST(FOO : BAR)",
19734             format("#pragma region TEST(FOO : BAR)", Style));
19735 }
19736 
TEST_F(FormatTest,OptimizeBreakPenaltyVsExcess)19737 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
19738   FormatStyle Style = getLLVMStyleWithColumns(20);
19739 
19740   // See PR41213
19741   EXPECT_EQ("/*\n"
19742             " *\t9012345\n"
19743             " * /8901\n"
19744             " */",
19745             format("/*\n"
19746                    " *\t9012345 /8901\n"
19747                    " */",
19748                    Style));
19749   EXPECT_EQ("/*\n"
19750             " *345678\n"
19751             " *\t/8901\n"
19752             " */",
19753             format("/*\n"
19754                    " *345678\t/8901\n"
19755                    " */",
19756                    Style));
19757 
19758   verifyFormat("int a; // the\n"
19759                "       // comment",
19760                Style);
19761   EXPECT_EQ("int a; /* first line\n"
19762             "        * second\n"
19763             "        * line third\n"
19764             "        * line\n"
19765             "        */",
19766             format("int a; /* first line\n"
19767                    "        * second\n"
19768                    "        * line third\n"
19769                    "        * line\n"
19770                    "        */",
19771                    Style));
19772   EXPECT_EQ("int a; // first line\n"
19773             "       // second\n"
19774             "       // line third\n"
19775             "       // line",
19776             format("int a; // first line\n"
19777                    "       // second line\n"
19778                    "       // third line",
19779                    Style));
19780 
19781   Style.PenaltyExcessCharacter = 90;
19782   verifyFormat("int a; // the comment", Style);
19783   EXPECT_EQ("int a; // the comment\n"
19784             "       // aaa",
19785             format("int a; // the comment aaa", Style));
19786   EXPECT_EQ("int a; /* first line\n"
19787             "        * second line\n"
19788             "        * third line\n"
19789             "        */",
19790             format("int a; /* first line\n"
19791                    "        * second line\n"
19792                    "        * third line\n"
19793                    "        */",
19794                    Style));
19795   EXPECT_EQ("int a; // first line\n"
19796             "       // second line\n"
19797             "       // third line",
19798             format("int a; // first line\n"
19799                    "       // second line\n"
19800                    "       // third line",
19801                    Style));
19802   // FIXME: Investigate why this is not getting the same layout as the test
19803   // above.
19804   EXPECT_EQ("int a; /* first line\n"
19805             "        * second line\n"
19806             "        * third line\n"
19807             "        */",
19808             format("int a; /* first line second line third line"
19809                    "\n*/",
19810                    Style));
19811 
19812   EXPECT_EQ("// foo bar baz bazfoo\n"
19813             "// foo bar foo bar\n",
19814             format("// foo bar baz bazfoo\n"
19815                    "// foo bar foo           bar\n",
19816                    Style));
19817   EXPECT_EQ("// foo bar baz bazfoo\n"
19818             "// foo bar foo bar\n",
19819             format("// foo bar baz      bazfoo\n"
19820                    "// foo            bar foo bar\n",
19821                    Style));
19822 
19823   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
19824   // next one.
19825   EXPECT_EQ("// foo bar baz bazfoo\n"
19826             "// bar foo bar\n",
19827             format("// foo bar baz      bazfoo bar\n"
19828                    "// foo            bar\n",
19829                    Style));
19830 
19831   EXPECT_EQ("// foo bar baz bazfoo\n"
19832             "// foo bar baz bazfoo\n"
19833             "// bar foo bar\n",
19834             format("// foo bar baz      bazfoo\n"
19835                    "// foo bar baz      bazfoo bar\n"
19836                    "// foo bar\n",
19837                    Style));
19838 
19839   EXPECT_EQ("// foo bar baz bazfoo\n"
19840             "// foo bar baz bazfoo\n"
19841             "// bar foo bar\n",
19842             format("// foo bar baz      bazfoo\n"
19843                    "// foo bar baz      bazfoo bar\n"
19844                    "// foo           bar\n",
19845                    Style));
19846 
19847   // Make sure we do not keep protruding characters if strict mode reflow is
19848   // cheaper than keeping protruding characters.
19849   Style.ColumnLimit = 21;
19850   EXPECT_EQ(
19851       "// foo foo foo foo\n"
19852       "// foo foo foo foo\n"
19853       "// foo foo foo foo\n",
19854       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
19855 
19856   EXPECT_EQ("int a = /* long block\n"
19857             "           comment */\n"
19858             "    42;",
19859             format("int a = /* long block comment */ 42;", Style));
19860 }
19861 
TEST_F(FormatTest,BreakPenaltyAfterLParen)19862 TEST_F(FormatTest, BreakPenaltyAfterLParen) {
19863   FormatStyle Style = getLLVMStyle();
19864   Style.ColumnLimit = 8;
19865   Style.PenaltyExcessCharacter = 15;
19866   verifyFormat("int foo(\n"
19867                "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19868                Style);
19869   Style.PenaltyBreakOpenParenthesis = 200;
19870   EXPECT_EQ("int foo(int aaaaaaaaaaaaaaaaaaaaaaaa);",
19871             format("int foo(\n"
19872                    "    int aaaaaaaaaaaaaaaaaaaaaaaa);",
19873                    Style));
19874 }
19875 
TEST_F(FormatTest,BreakPenaltyAfterCastLParen)19876 TEST_F(FormatTest, BreakPenaltyAfterCastLParen) {
19877   FormatStyle Style = getLLVMStyle();
19878   Style.ColumnLimit = 5;
19879   Style.PenaltyExcessCharacter = 150;
19880   verifyFormat("foo((\n"
19881                "    int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19882 
19883                Style);
19884   Style.PenaltyBreakOpenParenthesis = 100000;
19885   EXPECT_EQ("foo((int)\n"
19886             "        aaaaaaaaaaaaaaaaaaaaaaaa);",
19887             format("foo((\n"
19888                    "int)aaaaaaaaaaaaaaaaaaaaaaaa);",
19889                    Style));
19890 }
19891 
TEST_F(FormatTest,BreakPenaltyAfterForLoopLParen)19892 TEST_F(FormatTest, BreakPenaltyAfterForLoopLParen) {
19893   FormatStyle Style = getLLVMStyle();
19894   Style.ColumnLimit = 4;
19895   Style.PenaltyExcessCharacter = 100;
19896   verifyFormat("for (\n"
19897                "    int iiiiiiiiiiiiiiiii =\n"
19898                "        0;\n"
19899                "    iiiiiiiiiiiiiiiii <\n"
19900                "    2;\n"
19901                "    iiiiiiiiiiiiiiiii++) {\n"
19902                "}",
19903 
19904                Style);
19905   Style.PenaltyBreakOpenParenthesis = 1250;
19906   EXPECT_EQ("for (int iiiiiiiiiiiiiiiii =\n"
19907             "         0;\n"
19908             "     iiiiiiiiiiiiiiiii <\n"
19909             "     2;\n"
19910             "     iiiiiiiiiiiiiiiii++) {\n"
19911             "}",
19912             format("for (\n"
19913                    "    int iiiiiiiiiiiiiiiii =\n"
19914                    "        0;\n"
19915                    "    iiiiiiiiiiiiiiiii <\n"
19916                    "    2;\n"
19917                    "    iiiiiiiiiiiiiiiii++) {\n"
19918                    "}",
19919                    Style));
19920 }
19921 
19922 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
19923   for (size_t i = 1; i < Styles.size(); ++i)                                   \
19924   EXPECT_EQ(Styles[0], Styles[i])                                              \
19925       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
19926 
TEST_F(FormatTest,GetsPredefinedStyleByName)19927 TEST_F(FormatTest, GetsPredefinedStyleByName) {
19928   SmallVector<FormatStyle, 3> Styles;
19929   Styles.resize(3);
19930 
19931   Styles[0] = getLLVMStyle();
19932   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
19933   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
19934   EXPECT_ALL_STYLES_EQUAL(Styles);
19935 
19936   Styles[0] = getGoogleStyle();
19937   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
19938   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
19939   EXPECT_ALL_STYLES_EQUAL(Styles);
19940 
19941   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19942   EXPECT_TRUE(
19943       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
19944   EXPECT_TRUE(
19945       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
19946   EXPECT_ALL_STYLES_EQUAL(Styles);
19947 
19948   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
19949   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
19950   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
19951   EXPECT_ALL_STYLES_EQUAL(Styles);
19952 
19953   Styles[0] = getMozillaStyle();
19954   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
19955   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
19956   EXPECT_ALL_STYLES_EQUAL(Styles);
19957 
19958   Styles[0] = getWebKitStyle();
19959   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
19960   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
19961   EXPECT_ALL_STYLES_EQUAL(Styles);
19962 
19963   Styles[0] = getGNUStyle();
19964   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
19965   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
19966   EXPECT_ALL_STYLES_EQUAL(Styles);
19967 
19968   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
19969 }
19970 
TEST_F(FormatTest,GetsCorrectBasedOnStyle)19971 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
19972   SmallVector<FormatStyle, 8> Styles;
19973   Styles.resize(2);
19974 
19975   Styles[0] = getGoogleStyle();
19976   Styles[1] = getLLVMStyle();
19977   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19978   EXPECT_ALL_STYLES_EQUAL(Styles);
19979 
19980   Styles.resize(5);
19981   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
19982   Styles[1] = getLLVMStyle();
19983   Styles[1].Language = FormatStyle::LK_JavaScript;
19984   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
19985 
19986   Styles[2] = getLLVMStyle();
19987   Styles[2].Language = FormatStyle::LK_JavaScript;
19988   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
19989                                   "BasedOnStyle: Google",
19990                                   &Styles[2])
19991                    .value());
19992 
19993   Styles[3] = getLLVMStyle();
19994   Styles[3].Language = FormatStyle::LK_JavaScript;
19995   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
19996                                   "Language: JavaScript",
19997                                   &Styles[3])
19998                    .value());
19999 
20000   Styles[4] = getLLVMStyle();
20001   Styles[4].Language = FormatStyle::LK_JavaScript;
20002   EXPECT_EQ(0, parseConfiguration("---\n"
20003                                   "BasedOnStyle: LLVM\n"
20004                                   "IndentWidth: 123\n"
20005                                   "---\n"
20006                                   "BasedOnStyle: Google\n"
20007                                   "Language: JavaScript",
20008                                   &Styles[4])
20009                    .value());
20010   EXPECT_ALL_STYLES_EQUAL(Styles);
20011 }
20012 
20013 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
20014   Style.FIELD = false;                                                         \
20015   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
20016   EXPECT_TRUE(Style.FIELD);                                                    \
20017   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
20018   EXPECT_FALSE(Style.FIELD);
20019 
20020 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
20021 
20022 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
20023   Style.STRUCT.FIELD = false;                                                  \
20024   EXPECT_EQ(0,                                                                 \
20025             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
20026                 .value());                                                     \
20027   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
20028   EXPECT_EQ(0,                                                                 \
20029             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
20030                 .value());                                                     \
20031   EXPECT_FALSE(Style.STRUCT.FIELD);
20032 
20033 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
20034   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
20035 
20036 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
20037   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
20038   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
20039   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
20040 
TEST_F(FormatTest,ParsesConfigurationBools)20041 TEST_F(FormatTest, ParsesConfigurationBools) {
20042   FormatStyle Style = {};
20043   Style.Language = FormatStyle::LK_Cpp;
20044   CHECK_PARSE_BOOL(AlignTrailingComments);
20045   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
20046   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
20047   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
20048   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
20049   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
20050   CHECK_PARSE_BOOL(BinPackArguments);
20051   CHECK_PARSE_BOOL(BinPackParameters);
20052   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
20053   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
20054   CHECK_PARSE_BOOL(BreakStringLiterals);
20055   CHECK_PARSE_BOOL(CompactNamespaces);
20056   CHECK_PARSE_BOOL(DeriveLineEnding);
20057   CHECK_PARSE_BOOL(DerivePointerAlignment);
20058   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
20059   CHECK_PARSE_BOOL(DisableFormat);
20060   CHECK_PARSE_BOOL(IndentAccessModifiers);
20061   CHECK_PARSE_BOOL(IndentCaseLabels);
20062   CHECK_PARSE_BOOL(IndentCaseBlocks);
20063   CHECK_PARSE_BOOL(IndentGotoLabels);
20064   CHECK_PARSE_BOOL_FIELD(IndentRequiresClause, "IndentRequires");
20065   CHECK_PARSE_BOOL(IndentRequiresClause);
20066   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
20067   CHECK_PARSE_BOOL(InsertBraces);
20068   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
20069   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
20070   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
20071   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
20072   CHECK_PARSE_BOOL(ReflowComments);
20073   CHECK_PARSE_BOOL(RemoveBracesLLVM);
20074   CHECK_PARSE_BOOL(SortUsingDeclarations);
20075   CHECK_PARSE_BOOL(SpacesInParentheses);
20076   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
20077   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
20078   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
20079   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
20080   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
20081   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
20082   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
20083   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
20084   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
20085   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
20086   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
20087   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
20088   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
20089   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
20090   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
20091   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
20092   CHECK_PARSE_BOOL(UseCRLF);
20093 
20094   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
20095   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
20096   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
20097   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
20098   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
20099   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
20100   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
20101   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
20102   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
20103   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
20104   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
20105   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
20106   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
20107   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
20108   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
20109   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
20110   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
20111   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterControlStatements);
20112   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterForeachMacros);
20113   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
20114                           AfterFunctionDeclarationName);
20115   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions,
20116                           AfterFunctionDefinitionName);
20117   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterIfMacros);
20118   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, AfterOverloadedOperator);
20119   CHECK_PARSE_NESTED_BOOL(SpaceBeforeParensOptions, BeforeNonEmptyParentheses);
20120 }
20121 
20122 #undef CHECK_PARSE_BOOL
20123 
TEST_F(FormatTest,ParsesConfiguration)20124 TEST_F(FormatTest, ParsesConfiguration) {
20125   FormatStyle Style = {};
20126   Style.Language = FormatStyle::LK_Cpp;
20127   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
20128   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
20129               ConstructorInitializerIndentWidth, 1234u);
20130   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
20131   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
20132   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
20133   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
20134   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
20135               PenaltyBreakBeforeFirstCallParameter, 1234u);
20136   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
20137               PenaltyBreakTemplateDeclaration, 1234u);
20138   CHECK_PARSE("PenaltyBreakOpenParenthesis: 1234", PenaltyBreakOpenParenthesis,
20139               1234u);
20140   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
20141   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
20142               PenaltyReturnTypeOnItsOwnLine, 1234u);
20143   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
20144               SpacesBeforeTrailingComments, 1234u);
20145   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
20146   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
20147   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
20148 
20149   Style.QualifierAlignment = FormatStyle::QAS_Right;
20150   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
20151               FormatStyle::QAS_Leave);
20152   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
20153               FormatStyle::QAS_Right);
20154   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
20155               FormatStyle::QAS_Left);
20156   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
20157               FormatStyle::QAS_Custom);
20158 
20159   Style.QualifierOrder.clear();
20160   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
20161               std::vector<std::string>({"const", "volatile", "type"}));
20162   Style.QualifierOrder.clear();
20163   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
20164               std::vector<std::string>({"const", "type"}));
20165   Style.QualifierOrder.clear();
20166   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
20167               std::vector<std::string>({"volatile", "type"}));
20168 
20169 #define CHECK_ALIGN_CONSECUTIVE(FIELD)                                         \
20170   do {                                                                         \
20171     Style.FIELD.Enabled = true;                                                \
20172     CHECK_PARSE(#FIELD ": None", FIELD,                                        \
20173                 FormatStyle::AlignConsecutiveStyle(                            \
20174                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
20175                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20176                      /*PadOperators=*/true}));                                 \
20177     CHECK_PARSE(#FIELD ": Consecutive", FIELD,                                 \
20178                 FormatStyle::AlignConsecutiveStyle(                            \
20179                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
20180                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20181                      /*PadOperators=*/true}));                                 \
20182     CHECK_PARSE(#FIELD ": AcrossEmptyLines", FIELD,                            \
20183                 FormatStyle::AlignConsecutiveStyle(                            \
20184                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
20185                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20186                      /*PadOperators=*/true}));                                 \
20187     CHECK_PARSE(#FIELD ": AcrossEmptyLinesAndComments", FIELD,                 \
20188                 FormatStyle::AlignConsecutiveStyle(                            \
20189                     {/*Enabled=*/true, /*AcrossEmptyLines=*/true,              \
20190                      /*AcrossComments=*/true, /*AlignCompound=*/false,         \
20191                      /*PadOperators=*/true}));                                 \
20192     /* For backwards compability, false / true should still parse */           \
20193     CHECK_PARSE(#FIELD ": false", FIELD,                                       \
20194                 FormatStyle::AlignConsecutiveStyle(                            \
20195                     {/*Enabled=*/false, /*AcrossEmptyLines=*/false,            \
20196                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20197                      /*PadOperators=*/true}));                                 \
20198     CHECK_PARSE(#FIELD ": true", FIELD,                                        \
20199                 FormatStyle::AlignConsecutiveStyle(                            \
20200                     {/*Enabled=*/true, /*AcrossEmptyLines=*/false,             \
20201                      /*AcrossComments=*/false, /*AlignCompound=*/false,        \
20202                      /*PadOperators=*/true}));                                 \
20203                                                                                \
20204     CHECK_PARSE_NESTED_BOOL(FIELD, Enabled);                                   \
20205     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossEmptyLines);                          \
20206     CHECK_PARSE_NESTED_BOOL(FIELD, AcrossComments);                            \
20207     CHECK_PARSE_NESTED_BOOL(FIELD, AlignCompound);                             \
20208     CHECK_PARSE_NESTED_BOOL(FIELD, PadOperators);                              \
20209   } while (false)
20210 
20211   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveAssignments);
20212   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveBitFields);
20213   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveMacros);
20214   CHECK_ALIGN_CONSECUTIVE(AlignConsecutiveDeclarations);
20215 
20216 #undef CHECK_ALIGN_CONSECUTIVE
20217 
20218   Style.PointerAlignment = FormatStyle::PAS_Middle;
20219   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
20220               FormatStyle::PAS_Left);
20221   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
20222               FormatStyle::PAS_Right);
20223   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
20224               FormatStyle::PAS_Middle);
20225   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
20226   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
20227               FormatStyle::RAS_Pointer);
20228   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
20229               FormatStyle::RAS_Left);
20230   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
20231               FormatStyle::RAS_Right);
20232   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
20233               FormatStyle::RAS_Middle);
20234   // For backward compatibility:
20235   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
20236               FormatStyle::PAS_Left);
20237   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
20238               FormatStyle::PAS_Right);
20239   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
20240               FormatStyle::PAS_Middle);
20241 
20242   Style.Standard = FormatStyle::LS_Auto;
20243   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
20244   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
20245   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
20246   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
20247   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
20248   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
20249   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
20250   // Legacy aliases:
20251   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
20252   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
20253   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
20254   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
20255 
20256   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
20257   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
20258               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
20259   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
20260               FormatStyle::BOS_None);
20261   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
20262               FormatStyle::BOS_All);
20263   // For backward compatibility:
20264   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
20265               FormatStyle::BOS_None);
20266   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
20267               FormatStyle::BOS_All);
20268 
20269   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
20270   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
20271               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20272   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
20273               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
20274   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
20275               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
20276   // For backward compatibility:
20277   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
20278               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
20279 
20280   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
20281   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
20282               FormatStyle::BILS_AfterComma);
20283   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
20284               FormatStyle::BILS_BeforeComma);
20285   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
20286               FormatStyle::BILS_AfterColon);
20287   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
20288               FormatStyle::BILS_BeforeColon);
20289   // For backward compatibility:
20290   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
20291               FormatStyle::BILS_BeforeComma);
20292 
20293   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20294   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
20295               FormatStyle::PCIS_Never);
20296   CHECK_PARSE("PackConstructorInitializers: BinPack",
20297               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20298   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
20299               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20300   CHECK_PARSE("PackConstructorInitializers: NextLine",
20301               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20302   // For backward compatibility:
20303   CHECK_PARSE("BasedOnStyle: Google\n"
20304               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20305               "AllowAllConstructorInitializersOnNextLine: false",
20306               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20307   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
20308   CHECK_PARSE("BasedOnStyle: Google\n"
20309               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
20310               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
20311   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20312               "AllowAllConstructorInitializersOnNextLine: true",
20313               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
20314   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
20315   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
20316               "AllowAllConstructorInitializersOnNextLine: false",
20317               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
20318 
20319   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
20320   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
20321               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
20322   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
20323               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
20324   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
20325               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
20326   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
20327               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
20328 
20329   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
20330   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
20331               FormatStyle::BAS_Align);
20332   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
20333               FormatStyle::BAS_DontAlign);
20334   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
20335               FormatStyle::BAS_AlwaysBreak);
20336   CHECK_PARSE("AlignAfterOpenBracket: BlockIndent", AlignAfterOpenBracket,
20337               FormatStyle::BAS_BlockIndent);
20338   // For backward compatibility:
20339   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
20340               FormatStyle::BAS_DontAlign);
20341   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
20342               FormatStyle::BAS_Align);
20343 
20344   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
20345   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
20346               FormatStyle::ENAS_DontAlign);
20347   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
20348               FormatStyle::ENAS_Left);
20349   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
20350               FormatStyle::ENAS_Right);
20351   // For backward compatibility:
20352   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
20353               FormatStyle::ENAS_Left);
20354   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
20355               FormatStyle::ENAS_Right);
20356 
20357   Style.AlignOperands = FormatStyle::OAS_Align;
20358   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
20359               FormatStyle::OAS_DontAlign);
20360   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
20361   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
20362               FormatStyle::OAS_AlignAfterOperator);
20363   // For backward compatibility:
20364   CHECK_PARSE("AlignOperands: false", AlignOperands,
20365               FormatStyle::OAS_DontAlign);
20366   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
20367 
20368   Style.UseTab = FormatStyle::UT_ForIndentation;
20369   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
20370   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
20371   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
20372   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
20373               FormatStyle::UT_ForContinuationAndIndentation);
20374   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
20375               FormatStyle::UT_AlignWithSpaces);
20376   // For backward compatibility:
20377   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
20378   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
20379 
20380   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
20381   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
20382               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20383   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
20384               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
20385   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
20386               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20387   // For backward compatibility:
20388   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
20389               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
20390   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
20391               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
20392 
20393   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
20394   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
20395               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20396   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
20397               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
20398   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
20399               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
20400   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
20401               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20402   // For backward compatibility:
20403   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
20404               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
20405   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
20406               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
20407 
20408   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
20409   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
20410               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
20411   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
20412               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
20413   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
20414               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
20415   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
20416               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
20417 
20418   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
20419   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
20420               FormatStyle::SBPO_Never);
20421   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
20422               FormatStyle::SBPO_Always);
20423   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
20424               FormatStyle::SBPO_ControlStatements);
20425   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
20426               SpaceBeforeParens,
20427               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20428   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
20429               FormatStyle::SBPO_NonEmptyParentheses);
20430   CHECK_PARSE("SpaceBeforeParens: Custom", SpaceBeforeParens,
20431               FormatStyle::SBPO_Custom);
20432   // For backward compatibility:
20433   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
20434               FormatStyle::SBPO_Never);
20435   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
20436               FormatStyle::SBPO_ControlStatements);
20437   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
20438               SpaceBeforeParens,
20439               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
20440 
20441   Style.ColumnLimit = 123;
20442   FormatStyle BaseStyle = getLLVMStyle();
20443   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
20444   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
20445 
20446   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
20447   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
20448               FormatStyle::BS_Attach);
20449   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
20450               FormatStyle::BS_Linux);
20451   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
20452               FormatStyle::BS_Mozilla);
20453   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
20454               FormatStyle::BS_Stroustrup);
20455   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
20456               FormatStyle::BS_Allman);
20457   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
20458               FormatStyle::BS_Whitesmiths);
20459   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
20460   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
20461               FormatStyle::BS_WebKit);
20462   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
20463               FormatStyle::BS_Custom);
20464 
20465   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
20466   CHECK_PARSE("BraceWrapping:\n"
20467               "  AfterControlStatement: MultiLine",
20468               BraceWrapping.AfterControlStatement,
20469               FormatStyle::BWACS_MultiLine);
20470   CHECK_PARSE("BraceWrapping:\n"
20471               "  AfterControlStatement: Always",
20472               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20473   CHECK_PARSE("BraceWrapping:\n"
20474               "  AfterControlStatement: Never",
20475               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20476   // For backward compatibility:
20477   CHECK_PARSE("BraceWrapping:\n"
20478               "  AfterControlStatement: true",
20479               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
20480   CHECK_PARSE("BraceWrapping:\n"
20481               "  AfterControlStatement: false",
20482               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
20483 
20484   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
20485   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
20486               FormatStyle::RTBS_None);
20487   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
20488               FormatStyle::RTBS_All);
20489   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
20490               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
20491   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
20492               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
20493   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
20494               AlwaysBreakAfterReturnType,
20495               FormatStyle::RTBS_TopLevelDefinitions);
20496 
20497   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
20498   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
20499               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
20500   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
20501               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20502   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
20503               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20504   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
20505               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
20506   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
20507               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
20508 
20509   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
20510   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
20511               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
20512   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
20513               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
20514   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
20515               AlwaysBreakAfterDefinitionReturnType,
20516               FormatStyle::DRTBS_TopLevel);
20517 
20518   Style.NamespaceIndentation = FormatStyle::NI_All;
20519   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
20520               FormatStyle::NI_None);
20521   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
20522               FormatStyle::NI_Inner);
20523   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
20524               FormatStyle::NI_All);
20525 
20526   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
20527   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
20528               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20529   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
20530               AllowShortIfStatementsOnASingleLine,
20531               FormatStyle::SIS_WithoutElse);
20532   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
20533               AllowShortIfStatementsOnASingleLine,
20534               FormatStyle::SIS_OnlyFirstIf);
20535   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
20536               AllowShortIfStatementsOnASingleLine,
20537               FormatStyle::SIS_AllIfsAndElse);
20538   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
20539               AllowShortIfStatementsOnASingleLine,
20540               FormatStyle::SIS_OnlyFirstIf);
20541   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
20542               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
20543   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
20544               AllowShortIfStatementsOnASingleLine,
20545               FormatStyle::SIS_WithoutElse);
20546 
20547   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
20548   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
20549               FormatStyle::IEBS_AfterExternBlock);
20550   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
20551               FormatStyle::IEBS_Indent);
20552   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
20553               FormatStyle::IEBS_NoIndent);
20554   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
20555               FormatStyle::IEBS_Indent);
20556   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
20557               FormatStyle::IEBS_NoIndent);
20558 
20559   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
20560   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
20561               FormatStyle::BFCS_Both);
20562   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
20563               FormatStyle::BFCS_None);
20564   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
20565               FormatStyle::BFCS_Before);
20566   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
20567               FormatStyle::BFCS_After);
20568 
20569   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
20570   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
20571               FormatStyle::SJSIO_After);
20572   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
20573               FormatStyle::SJSIO_Before);
20574 
20575   // FIXME: This is required because parsing a configuration simply overwrites
20576   // the first N elements of the list instead of resetting it.
20577   Style.ForEachMacros.clear();
20578   std::vector<std::string> BoostForeach;
20579   BoostForeach.push_back("BOOST_FOREACH");
20580   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
20581   std::vector<std::string> BoostAndQForeach;
20582   BoostAndQForeach.push_back("BOOST_FOREACH");
20583   BoostAndQForeach.push_back("Q_FOREACH");
20584   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
20585               BoostAndQForeach);
20586 
20587   Style.IfMacros.clear();
20588   std::vector<std::string> CustomIfs;
20589   CustomIfs.push_back("MYIF");
20590   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
20591 
20592   Style.AttributeMacros.clear();
20593   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
20594               std::vector<std::string>{"__capability"});
20595   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
20596               std::vector<std::string>({"attr1", "attr2"}));
20597 
20598   Style.StatementAttributeLikeMacros.clear();
20599   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
20600               StatementAttributeLikeMacros,
20601               std::vector<std::string>({"emit", "Q_EMIT"}));
20602 
20603   Style.StatementMacros.clear();
20604   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
20605               std::vector<std::string>{"QUNUSED"});
20606   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
20607               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
20608 
20609   Style.NamespaceMacros.clear();
20610   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
20611               std::vector<std::string>{"TESTSUITE"});
20612   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
20613               std::vector<std::string>({"TESTSUITE", "SUITE"}));
20614 
20615   Style.WhitespaceSensitiveMacros.clear();
20616   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
20617               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20618   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
20619               WhitespaceSensitiveMacros,
20620               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20621   Style.WhitespaceSensitiveMacros.clear();
20622   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
20623               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
20624   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
20625               WhitespaceSensitiveMacros,
20626               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
20627 
20628   Style.IncludeStyle.IncludeCategories.clear();
20629   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
20630       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
20631   CHECK_PARSE("IncludeCategories:\n"
20632               "  - Regex: abc/.*\n"
20633               "    Priority: 2\n"
20634               "  - Regex: .*\n"
20635               "    Priority: 1\n"
20636               "    CaseSensitive: true\n",
20637               IncludeStyle.IncludeCategories, ExpectedCategories);
20638   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
20639               "abc$");
20640   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
20641               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
20642 
20643   Style.SortIncludes = FormatStyle::SI_Never;
20644   CHECK_PARSE("SortIncludes: true", SortIncludes,
20645               FormatStyle::SI_CaseSensitive);
20646   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
20647   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
20648               FormatStyle::SI_CaseInsensitive);
20649   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
20650               FormatStyle::SI_CaseSensitive);
20651   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
20652 
20653   Style.RawStringFormats.clear();
20654   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
20655       {
20656           FormatStyle::LK_TextProto,
20657           {"pb", "proto"},
20658           {"PARSE_TEXT_PROTO"},
20659           /*CanonicalDelimiter=*/"",
20660           "llvm",
20661       },
20662       {
20663           FormatStyle::LK_Cpp,
20664           {"cc", "cpp"},
20665           {"C_CODEBLOCK", "CPPEVAL"},
20666           /*CanonicalDelimiter=*/"cc",
20667           /*BasedOnStyle=*/"",
20668       },
20669   };
20670 
20671   CHECK_PARSE("RawStringFormats:\n"
20672               "  - Language: TextProto\n"
20673               "    Delimiters:\n"
20674               "      - 'pb'\n"
20675               "      - 'proto'\n"
20676               "    EnclosingFunctions:\n"
20677               "      - 'PARSE_TEXT_PROTO'\n"
20678               "    BasedOnStyle: llvm\n"
20679               "  - Language: Cpp\n"
20680               "    Delimiters:\n"
20681               "      - 'cc'\n"
20682               "      - 'cpp'\n"
20683               "    EnclosingFunctions:\n"
20684               "      - 'C_CODEBLOCK'\n"
20685               "      - 'CPPEVAL'\n"
20686               "    CanonicalDelimiter: 'cc'",
20687               RawStringFormats, ExpectedRawStringFormats);
20688 
20689   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20690               "  Minimum: 0\n"
20691               "  Maximum: 0",
20692               SpacesInLineCommentPrefix.Minimum, 0u);
20693   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
20694   Style.SpacesInLineCommentPrefix.Minimum = 1;
20695   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20696               "  Minimum: 2",
20697               SpacesInLineCommentPrefix.Minimum, 0u);
20698   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20699               "  Maximum: -1",
20700               SpacesInLineCommentPrefix.Maximum, -1u);
20701   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20702               "  Minimum: 2",
20703               SpacesInLineCommentPrefix.Minimum, 2u);
20704   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
20705               "  Maximum: 1",
20706               SpacesInLineCommentPrefix.Maximum, 1u);
20707   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
20708 
20709   Style.SpacesInAngles = FormatStyle::SIAS_Always;
20710   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
20711   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
20712               FormatStyle::SIAS_Always);
20713   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
20714   // For backward compatibility:
20715   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
20716   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
20717 
20718   CHECK_PARSE("RequiresClausePosition: WithPreceding", RequiresClausePosition,
20719               FormatStyle::RCPS_WithPreceding);
20720   CHECK_PARSE("RequiresClausePosition: WithFollowing", RequiresClausePosition,
20721               FormatStyle::RCPS_WithFollowing);
20722   CHECK_PARSE("RequiresClausePosition: SingleLine", RequiresClausePosition,
20723               FormatStyle::RCPS_SingleLine);
20724   CHECK_PARSE("RequiresClausePosition: OwnLine", RequiresClausePosition,
20725               FormatStyle::RCPS_OwnLine);
20726 
20727   CHECK_PARSE("BreakBeforeConceptDeclarations: Never",
20728               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Never);
20729   CHECK_PARSE("BreakBeforeConceptDeclarations: Always",
20730               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20731   CHECK_PARSE("BreakBeforeConceptDeclarations: Allowed",
20732               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20733   // For backward compatibility:
20734   CHECK_PARSE("BreakBeforeConceptDeclarations: true",
20735               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Always);
20736   CHECK_PARSE("BreakBeforeConceptDeclarations: false",
20737               BreakBeforeConceptDeclarations, FormatStyle::BBCDS_Allowed);
20738 }
20739 
TEST_F(FormatTest,ParsesConfigurationWithLanguages)20740 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
20741   FormatStyle Style = {};
20742   Style.Language = FormatStyle::LK_Cpp;
20743   CHECK_PARSE("Language: Cpp\n"
20744               "IndentWidth: 12",
20745               IndentWidth, 12u);
20746   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
20747                                "IndentWidth: 34",
20748                                &Style),
20749             ParseError::Unsuitable);
20750   FormatStyle BinPackedTCS = {};
20751   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
20752   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
20753                                "InsertTrailingCommas: Wrapped",
20754                                &BinPackedTCS),
20755             ParseError::BinPackTrailingCommaConflict);
20756   EXPECT_EQ(12u, Style.IndentWidth);
20757   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20758   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20759 
20760   Style.Language = FormatStyle::LK_JavaScript;
20761   CHECK_PARSE("Language: JavaScript\n"
20762               "IndentWidth: 12",
20763               IndentWidth, 12u);
20764   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
20765   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
20766                                "IndentWidth: 34",
20767                                &Style),
20768             ParseError::Unsuitable);
20769   EXPECT_EQ(23u, Style.IndentWidth);
20770   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
20771   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20772 
20773   CHECK_PARSE("BasedOnStyle: LLVM\n"
20774               "IndentWidth: 67",
20775               IndentWidth, 67u);
20776 
20777   CHECK_PARSE("---\n"
20778               "Language: JavaScript\n"
20779               "IndentWidth: 12\n"
20780               "---\n"
20781               "Language: Cpp\n"
20782               "IndentWidth: 34\n"
20783               "...\n",
20784               IndentWidth, 12u);
20785 
20786   Style.Language = FormatStyle::LK_Cpp;
20787   CHECK_PARSE("---\n"
20788               "Language: JavaScript\n"
20789               "IndentWidth: 12\n"
20790               "---\n"
20791               "Language: Cpp\n"
20792               "IndentWidth: 34\n"
20793               "...\n",
20794               IndentWidth, 34u);
20795   CHECK_PARSE("---\n"
20796               "IndentWidth: 78\n"
20797               "---\n"
20798               "Language: JavaScript\n"
20799               "IndentWidth: 56\n"
20800               "...\n",
20801               IndentWidth, 78u);
20802 
20803   Style.ColumnLimit = 123;
20804   Style.IndentWidth = 234;
20805   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
20806   Style.TabWidth = 345;
20807   EXPECT_FALSE(parseConfiguration("---\n"
20808                                   "IndentWidth: 456\n"
20809                                   "BreakBeforeBraces: Allman\n"
20810                                   "---\n"
20811                                   "Language: JavaScript\n"
20812                                   "IndentWidth: 111\n"
20813                                   "TabWidth: 111\n"
20814                                   "---\n"
20815                                   "Language: Cpp\n"
20816                                   "BreakBeforeBraces: Stroustrup\n"
20817                                   "TabWidth: 789\n"
20818                                   "...\n",
20819                                   &Style));
20820   EXPECT_EQ(123u, Style.ColumnLimit);
20821   EXPECT_EQ(456u, Style.IndentWidth);
20822   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
20823   EXPECT_EQ(789u, Style.TabWidth);
20824 
20825   EXPECT_EQ(parseConfiguration("---\n"
20826                                "Language: JavaScript\n"
20827                                "IndentWidth: 56\n"
20828                                "---\n"
20829                                "IndentWidth: 78\n"
20830                                "...\n",
20831                                &Style),
20832             ParseError::Error);
20833   EXPECT_EQ(parseConfiguration("---\n"
20834                                "Language: JavaScript\n"
20835                                "IndentWidth: 56\n"
20836                                "---\n"
20837                                "Language: JavaScript\n"
20838                                "IndentWidth: 78\n"
20839                                "...\n",
20840                                &Style),
20841             ParseError::Error);
20842 
20843   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
20844 }
20845 
TEST_F(FormatTest,UsesLanguageForBasedOnStyle)20846 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
20847   FormatStyle Style = {};
20848   Style.Language = FormatStyle::LK_JavaScript;
20849   Style.BreakBeforeTernaryOperators = true;
20850   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
20851   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20852 
20853   Style.BreakBeforeTernaryOperators = true;
20854   EXPECT_EQ(0, parseConfiguration("---\n"
20855                                   "BasedOnStyle: Google\n"
20856                                   "---\n"
20857                                   "Language: JavaScript\n"
20858                                   "IndentWidth: 76\n"
20859                                   "...\n",
20860                                   &Style)
20861                    .value());
20862   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
20863   EXPECT_EQ(76u, Style.IndentWidth);
20864   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
20865 }
20866 
TEST_F(FormatTest,ConfigurationRoundTripTest)20867 TEST_F(FormatTest, ConfigurationRoundTripTest) {
20868   FormatStyle Style = getLLVMStyle();
20869   std::string YAML = configurationAsText(Style);
20870   FormatStyle ParsedStyle = {};
20871   ParsedStyle.Language = FormatStyle::LK_Cpp;
20872   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
20873   EXPECT_EQ(Style, ParsedStyle);
20874 }
20875 
TEST_F(FormatTest,WorksFor8bitEncodings)20876 TEST_F(FormatTest, WorksFor8bitEncodings) {
20877   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
20878             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
20879             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
20880             "\"\xef\xee\xf0\xf3...\"",
20881             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
20882                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
20883                    "\xef\xee\xf0\xf3...\"",
20884                    getLLVMStyleWithColumns(12)));
20885 }
20886 
TEST_F(FormatTest,HandlesUTF8BOM)20887 TEST_F(FormatTest, HandlesUTF8BOM) {
20888   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
20889   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
20890             format("\xef\xbb\xbf#include <iostream>"));
20891   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
20892             format("\xef\xbb\xbf\n#include <iostream>"));
20893 }
20894 
20895 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
20896 #if !defined(_MSC_VER)
20897 
TEST_F(FormatTest,CountsUTF8CharactersProperly)20898 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
20899   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
20900                getLLVMStyleWithColumns(35));
20901   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
20902                getLLVMStyleWithColumns(31));
20903   verifyFormat("// Однажды в студёную зимнюю пору...",
20904                getLLVMStyleWithColumns(36));
20905   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
20906   verifyFormat("/* Однажды в студёную зимнюю пору... */",
20907                getLLVMStyleWithColumns(39));
20908   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
20909                getLLVMStyleWithColumns(35));
20910 }
20911 
TEST_F(FormatTest,SplitsUTF8Strings)20912 TEST_F(FormatTest, SplitsUTF8Strings) {
20913   // Non-printable characters' width is currently considered to be the length in
20914   // bytes in UTF8. The characters can be displayed in very different manner
20915   // (zero-width, single width with a substitution glyph, expanded to their code
20916   // (e.g. "<8d>"), so there's no single correct way to handle them.
20917   EXPECT_EQ("\"aaaaÄ\"\n"
20918             "\"\xc2\x8d\";",
20919             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20920   EXPECT_EQ("\"aaaaaaaÄ\"\n"
20921             "\"\xc2\x8d\";",
20922             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
20923   EXPECT_EQ("\"Однажды, в \"\n"
20924             "\"студёную \"\n"
20925             "\"зимнюю \"\n"
20926             "\"пору,\"",
20927             format("\"Однажды, в студёную зимнюю пору,\"",
20928                    getLLVMStyleWithColumns(13)));
20929   EXPECT_EQ(
20930       "\"一 二 三 \"\n"
20931       "\"四 五六 \"\n"
20932       "\"七 八 九 \"\n"
20933       "\"十\"",
20934       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
20935   EXPECT_EQ("\"一\t\"\n"
20936             "\"二 \t\"\n"
20937             "\"三 四 \"\n"
20938             "\"五\t\"\n"
20939             "\"六 \t\"\n"
20940             "\"七 \"\n"
20941             "\"八九十\tqq\"",
20942             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
20943                    getLLVMStyleWithColumns(11)));
20944 
20945   // UTF8 character in an escape sequence.
20946   EXPECT_EQ("\"aaaaaa\"\n"
20947             "\"\\\xC2\x8D\"",
20948             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
20949 }
20950 
TEST_F(FormatTest,HandlesDoubleWidthCharsInMultiLineStrings)20951 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
20952   EXPECT_EQ("const char *sssss =\n"
20953             "    \"一二三四五六七八\\\n"
20954             " 九 十\";",
20955             format("const char *sssss = \"一二三四五六七八\\\n"
20956                    " 九 十\";",
20957                    getLLVMStyleWithColumns(30)));
20958 }
20959 
TEST_F(FormatTest,SplitsUTF8LineComments)20960 TEST_F(FormatTest, SplitsUTF8LineComments) {
20961   EXPECT_EQ("// aaaaÄ\xc2\x8d",
20962             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
20963   EXPECT_EQ("// Я из лесу\n"
20964             "// вышел; был\n"
20965             "// сильный\n"
20966             "// мороз.",
20967             format("// Я из лесу вышел; был сильный мороз.",
20968                    getLLVMStyleWithColumns(13)));
20969   EXPECT_EQ("// 一二三\n"
20970             "// 四五六七\n"
20971             "// 八  九\n"
20972             "// 十",
20973             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
20974 }
20975 
TEST_F(FormatTest,SplitsUTF8BlockComments)20976 TEST_F(FormatTest, SplitsUTF8BlockComments) {
20977   EXPECT_EQ("/* Гляжу,\n"
20978             " * поднимается\n"
20979             " * медленно в\n"
20980             " * гору\n"
20981             " * Лошадка,\n"
20982             " * везущая\n"
20983             " * хворосту\n"
20984             " * воз. */",
20985             format("/* Гляжу, поднимается медленно в гору\n"
20986                    " * Лошадка, везущая хворосту воз. */",
20987                    getLLVMStyleWithColumns(13)));
20988   EXPECT_EQ(
20989       "/* 一二三\n"
20990       " * 四五六七\n"
20991       " * 八  九\n"
20992       " * 十  */",
20993       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
20994   EXPECT_EQ("/* �������� ��������\n"
20995             " * ��������\n"
20996             " * ������-�� */",
20997             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
20998 }
20999 
21000 #endif // _MSC_VER
21001 
TEST_F(FormatTest,ConstructorInitializerIndentWidth)21002 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
21003   FormatStyle Style = getLLVMStyle();
21004 
21005   Style.ConstructorInitializerIndentWidth = 4;
21006   verifyFormat(
21007       "SomeClass::Constructor()\n"
21008       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
21009       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
21010       Style);
21011 
21012   Style.ConstructorInitializerIndentWidth = 2;
21013   verifyFormat(
21014       "SomeClass::Constructor()\n"
21015       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
21016       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
21017       Style);
21018 
21019   Style.ConstructorInitializerIndentWidth = 0;
21020   verifyFormat(
21021       "SomeClass::Constructor()\n"
21022       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
21023       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
21024       Style);
21025   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
21026   verifyFormat(
21027       "SomeLongTemplateVariableName<\n"
21028       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
21029       Style);
21030   verifyFormat("bool smaller = 1 < "
21031                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
21032                "                       "
21033                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
21034                Style);
21035 
21036   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
21037   verifyFormat("SomeClass::Constructor() :\n"
21038                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
21039                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
21040                Style);
21041 }
21042 
TEST_F(FormatTest,BreakConstructorInitializersBeforeComma)21043 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
21044   FormatStyle Style = getLLVMStyle();
21045   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
21046   Style.ConstructorInitializerIndentWidth = 4;
21047   verifyFormat("SomeClass::Constructor()\n"
21048                "    : a(a)\n"
21049                "    , b(b)\n"
21050                "    , c(c) {}",
21051                Style);
21052   verifyFormat("SomeClass::Constructor()\n"
21053                "    : a(a) {}",
21054                Style);
21055 
21056   Style.ColumnLimit = 0;
21057   verifyFormat("SomeClass::Constructor()\n"
21058                "    : a(a) {}",
21059                Style);
21060   verifyFormat("SomeClass::Constructor() noexcept\n"
21061                "    : a(a) {}",
21062                Style);
21063   verifyFormat("SomeClass::Constructor()\n"
21064                "    : a(a)\n"
21065                "    , b(b)\n"
21066                "    , c(c) {}",
21067                Style);
21068   verifyFormat("SomeClass::Constructor()\n"
21069                "    : a(a) {\n"
21070                "  foo();\n"
21071                "  bar();\n"
21072                "}",
21073                Style);
21074 
21075   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
21076   verifyFormat("SomeClass::Constructor()\n"
21077                "    : a(a)\n"
21078                "    , b(b)\n"
21079                "    , c(c) {\n}",
21080                Style);
21081   verifyFormat("SomeClass::Constructor()\n"
21082                "    : a(a) {\n}",
21083                Style);
21084 
21085   Style.ColumnLimit = 80;
21086   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
21087   Style.ConstructorInitializerIndentWidth = 2;
21088   verifyFormat("SomeClass::Constructor()\n"
21089                "  : a(a)\n"
21090                "  , b(b)\n"
21091                "  , c(c) {}",
21092                Style);
21093 
21094   Style.ConstructorInitializerIndentWidth = 0;
21095   verifyFormat("SomeClass::Constructor()\n"
21096                ": a(a)\n"
21097                ", b(b)\n"
21098                ", c(c) {}",
21099                Style);
21100 
21101   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
21102   Style.ConstructorInitializerIndentWidth = 4;
21103   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
21104   verifyFormat(
21105       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
21106       Style);
21107   verifyFormat(
21108       "SomeClass::Constructor()\n"
21109       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
21110       Style);
21111   Style.ConstructorInitializerIndentWidth = 4;
21112   Style.ColumnLimit = 60;
21113   verifyFormat("SomeClass::Constructor()\n"
21114                "    : aaaaaaaa(aaaaaaaa)\n"
21115                "    , aaaaaaaa(aaaaaaaa)\n"
21116                "    , aaaaaaaa(aaaaaaaa) {}",
21117                Style);
21118 }
21119 
TEST_F(FormatTest,ConstructorInitializersWithPreprocessorDirective)21120 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
21121   FormatStyle Style = getLLVMStyle();
21122   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
21123   Style.ConstructorInitializerIndentWidth = 4;
21124   verifyFormat("SomeClass::Constructor()\n"
21125                "    : a{a}\n"
21126                "    , b{b} {}",
21127                Style);
21128   verifyFormat("SomeClass::Constructor()\n"
21129                "    : a{a}\n"
21130                "#if CONDITION\n"
21131                "    , b{b}\n"
21132                "#endif\n"
21133                "{\n}",
21134                Style);
21135   Style.ConstructorInitializerIndentWidth = 2;
21136   verifyFormat("SomeClass::Constructor()\n"
21137                "#if CONDITION\n"
21138                "  : a{a}\n"
21139                "#endif\n"
21140                "  , b{b}\n"
21141                "  , c{c} {\n}",
21142                Style);
21143   Style.ConstructorInitializerIndentWidth = 0;
21144   verifyFormat("SomeClass::Constructor()\n"
21145                ": a{a}\n"
21146                "#ifdef CONDITION\n"
21147                ", b{b}\n"
21148                "#else\n"
21149                ", c{c}\n"
21150                "#endif\n"
21151                ", d{d} {\n}",
21152                Style);
21153   Style.ConstructorInitializerIndentWidth = 4;
21154   verifyFormat("SomeClass::Constructor()\n"
21155                "    : a{a}\n"
21156                "#if WINDOWS\n"
21157                "#if DEBUG\n"
21158                "    , b{0}\n"
21159                "#else\n"
21160                "    , b{1}\n"
21161                "#endif\n"
21162                "#else\n"
21163                "#if DEBUG\n"
21164                "    , b{2}\n"
21165                "#else\n"
21166                "    , b{3}\n"
21167                "#endif\n"
21168                "#endif\n"
21169                "{\n}",
21170                Style);
21171   verifyFormat("SomeClass::Constructor()\n"
21172                "    : a{a}\n"
21173                "#if WINDOWS\n"
21174                "    , b{0}\n"
21175                "#if DEBUG\n"
21176                "    , c{0}\n"
21177                "#else\n"
21178                "    , c{1}\n"
21179                "#endif\n"
21180                "#else\n"
21181                "#if DEBUG\n"
21182                "    , c{2}\n"
21183                "#else\n"
21184                "    , c{3}\n"
21185                "#endif\n"
21186                "    , b{1}\n"
21187                "#endif\n"
21188                "{\n}",
21189                Style);
21190 }
21191 
TEST_F(FormatTest,Destructors)21192 TEST_F(FormatTest, Destructors) {
21193   verifyFormat("void F(int &i) { i.~int(); }");
21194   verifyFormat("void F(int &i) { i->~int(); }");
21195 }
21196 
TEST_F(FormatTest,FormatsWithWebKitStyle)21197 TEST_F(FormatTest, FormatsWithWebKitStyle) {
21198   FormatStyle Style = getWebKitStyle();
21199 
21200   // Don't indent in outer namespaces.
21201   verifyFormat("namespace outer {\n"
21202                "int i;\n"
21203                "namespace inner {\n"
21204                "    int i;\n"
21205                "} // namespace inner\n"
21206                "} // namespace outer\n"
21207                "namespace other_outer {\n"
21208                "int i;\n"
21209                "}",
21210                Style);
21211 
21212   // Don't indent case labels.
21213   verifyFormat("switch (variable) {\n"
21214                "case 1:\n"
21215                "case 2:\n"
21216                "    doSomething();\n"
21217                "    break;\n"
21218                "default:\n"
21219                "    ++variable;\n"
21220                "}",
21221                Style);
21222 
21223   // Wrap before binary operators.
21224   EXPECT_EQ("void f()\n"
21225             "{\n"
21226             "    if (aaaaaaaaaaaaaaaa\n"
21227             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
21228             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
21229             "        return;\n"
21230             "}",
21231             format("void f() {\n"
21232                    "if (aaaaaaaaaaaaaaaa\n"
21233                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
21234                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
21235                    "return;\n"
21236                    "}",
21237                    Style));
21238 
21239   // Allow functions on a single line.
21240   verifyFormat("void f() { return; }", Style);
21241 
21242   // Allow empty blocks on a single line and insert a space in empty blocks.
21243   EXPECT_EQ("void f() { }", format("void f() {}", Style));
21244   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
21245   // However, don't merge non-empty short loops.
21246   EXPECT_EQ("while (true) {\n"
21247             "    continue;\n"
21248             "}",
21249             format("while (true) { continue; }", Style));
21250 
21251   // Constructor initializers are formatted one per line with the "," on the
21252   // new line.
21253   verifyFormat("Constructor()\n"
21254                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
21255                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
21256                "          aaaaaaaaaaaaaa)\n"
21257                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
21258                "{\n"
21259                "}",
21260                Style);
21261   verifyFormat("SomeClass::Constructor()\n"
21262                "    : a(a)\n"
21263                "{\n"
21264                "}",
21265                Style);
21266   EXPECT_EQ("SomeClass::Constructor()\n"
21267             "    : a(a)\n"
21268             "{\n"
21269             "}",
21270             format("SomeClass::Constructor():a(a){}", Style));
21271   verifyFormat("SomeClass::Constructor()\n"
21272                "    : a(a)\n"
21273                "    , b(b)\n"
21274                "    , c(c)\n"
21275                "{\n"
21276                "}",
21277                Style);
21278   verifyFormat("SomeClass::Constructor()\n"
21279                "    : a(a)\n"
21280                "{\n"
21281                "    foo();\n"
21282                "    bar();\n"
21283                "}",
21284                Style);
21285 
21286   // Access specifiers should be aligned left.
21287   verifyFormat("class C {\n"
21288                "public:\n"
21289                "    int i;\n"
21290                "};",
21291                Style);
21292 
21293   // Do not align comments.
21294   verifyFormat("int a; // Do not\n"
21295                "double b; // align comments.",
21296                Style);
21297 
21298   // Do not align operands.
21299   EXPECT_EQ("ASSERT(aaaa\n"
21300             "    || bbbb);",
21301             format("ASSERT ( aaaa\n||bbbb);", Style));
21302 
21303   // Accept input's line breaks.
21304   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
21305             "    || bbbbbbbbbbbbbbb) {\n"
21306             "    i++;\n"
21307             "}",
21308             format("if (aaaaaaaaaaaaaaa\n"
21309                    "|| bbbbbbbbbbbbbbb) { i++; }",
21310                    Style));
21311   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
21312             "    i++;\n"
21313             "}",
21314             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
21315 
21316   // Don't automatically break all macro definitions (llvm.org/PR17842).
21317   verifyFormat("#define aNumber 10", Style);
21318   // However, generally keep the line breaks that the user authored.
21319   EXPECT_EQ("#define aNumber \\\n"
21320             "    10",
21321             format("#define aNumber \\\n"
21322                    " 10",
21323                    Style));
21324 
21325   // Keep empty and one-element array literals on a single line.
21326   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
21327             "                                  copyItems:YES];",
21328             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
21329                    "copyItems:YES];",
21330                    Style));
21331   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
21332             "                                  copyItems:YES];",
21333             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
21334                    "             copyItems:YES];",
21335                    Style));
21336   // FIXME: This does not seem right, there should be more indentation before
21337   // the array literal's entries. Nested blocks have the same problem.
21338   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21339             "    @\"a\",\n"
21340             "    @\"a\"\n"
21341             "]\n"
21342             "                                  copyItems:YES];",
21343             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
21344                    "     @\"a\",\n"
21345                    "     @\"a\"\n"
21346                    "     ]\n"
21347                    "       copyItems:YES];",
21348                    Style));
21349   EXPECT_EQ(
21350       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21351       "                                  copyItems:YES];",
21352       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
21353              "   copyItems:YES];",
21354              Style));
21355 
21356   verifyFormat("[self.a b:c c:d];", Style);
21357   EXPECT_EQ("[self.a b:c\n"
21358             "        c:d];",
21359             format("[self.a b:c\n"
21360                    "c:d];",
21361                    Style));
21362 }
21363 
TEST_F(FormatTest,FormatsLambdas)21364 TEST_F(FormatTest, FormatsLambdas) {
21365   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
21366   verifyFormat(
21367       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
21368   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
21369   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
21370   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
21371   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
21372   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
21373   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
21374   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
21375   verifyFormat("int x = f(*+[] {});");
21376   verifyFormat("void f() {\n"
21377                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
21378                "}\n");
21379   verifyFormat("void f() {\n"
21380                "  other(x.begin(), //\n"
21381                "        x.end(),   //\n"
21382                "        [&](int, int) { return 1; });\n"
21383                "}\n");
21384   verifyFormat("void f() {\n"
21385                "  other.other.other.other.other(\n"
21386                "      x.begin(), x.end(),\n"
21387                "      [something, rather](int, int, int, int, int, int, int) { "
21388                "return 1; });\n"
21389                "}\n");
21390   verifyFormat(
21391       "void f() {\n"
21392       "  other.other.other.other.other(\n"
21393       "      x.begin(), x.end(),\n"
21394       "      [something, rather](int, int, int, int, int, int, int) {\n"
21395       "        //\n"
21396       "      });\n"
21397       "}\n");
21398   verifyFormat("SomeFunction([]() { // A cool function...\n"
21399                "  return 43;\n"
21400                "});");
21401   EXPECT_EQ("SomeFunction([]() {\n"
21402             "#define A a\n"
21403             "  return 43;\n"
21404             "});",
21405             format("SomeFunction([](){\n"
21406                    "#define A a\n"
21407                    "return 43;\n"
21408                    "});"));
21409   verifyFormat("void f() {\n"
21410                "  SomeFunction([](decltype(x), A *a) {});\n"
21411                "  SomeFunction([](typeof(x), A *a) {});\n"
21412                "  SomeFunction([](_Atomic(x), A *a) {});\n"
21413                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
21414                "}");
21415   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21416                "    [](const aaaaaaaaaa &a) { return a; });");
21417   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
21418                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
21419                "});");
21420   verifyFormat("Constructor()\n"
21421                "    : Field([] { // comment\n"
21422                "        int i;\n"
21423                "      }) {}");
21424   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
21425                "  return some_parameter.size();\n"
21426                "};");
21427   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
21428                "    [](const string &s) { return s; };");
21429   verifyFormat("int i = aaaaaa ? 1 //\n"
21430                "               : [] {\n"
21431                "                   return 2; //\n"
21432                "                 }();");
21433   verifyFormat("llvm::errs() << \"number of twos is \"\n"
21434                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
21435                "                  return x == 2; // force break\n"
21436                "                });");
21437   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21438                "    [=](int iiiiiiiiiiii) {\n"
21439                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
21440                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
21441                "    });",
21442                getLLVMStyleWithColumns(60));
21443 
21444   verifyFormat("SomeFunction({[&] {\n"
21445                "                // comment\n"
21446                "              },\n"
21447                "              [&] {\n"
21448                "                // comment\n"
21449                "              }});");
21450   verifyFormat("SomeFunction({[&] {\n"
21451                "  // comment\n"
21452                "}});");
21453   verifyFormat(
21454       "virtual aaaaaaaaaaaaaaaa(\n"
21455       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
21456       "    aaaaa aaaaaaaaa);");
21457 
21458   // Lambdas with return types.
21459   verifyFormat("int c = []() -> int { return 2; }();\n");
21460   verifyFormat("int c = []() -> int * { return 2; }();\n");
21461   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
21462   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
21463   verifyFormat("foo([]() noexcept -> int {});");
21464   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
21465   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
21466   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
21467   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
21468   verifyFormat("[a, a]() -> a<1> {};");
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 << 2> { return {}; };");
21475   verifyFormat("[]() -> foo<!5> { return {}; };");
21476   verifyFormat("[]() -> foo<~5> { 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<5 < 2> { return {}; };");
21486   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
21487   verifyFormat("namespace bar {\n"
21488                "// broken:\n"
21489                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
21490                "} // namespace bar");
21491   verifyFormat("namespace bar {\n"
21492                "// broken:\n"
21493                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
21494                "} // namespace bar");
21495   verifyFormat("namespace bar {\n"
21496                "// broken:\n"
21497                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
21498                "} // namespace bar");
21499   verifyFormat("namespace bar {\n"
21500                "// broken:\n"
21501                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
21502                "} // namespace bar");
21503   verifyFormat("namespace bar {\n"
21504                "// broken:\n"
21505                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
21506                "} // namespace bar");
21507   verifyFormat("namespace bar {\n"
21508                "// broken:\n"
21509                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
21510                "} // namespace bar");
21511   verifyFormat("namespace bar {\n"
21512                "// broken:\n"
21513                "auto foo{[]() -> foo<!5> { return {}; }};\n"
21514                "} // namespace bar");
21515   verifyFormat("namespace bar {\n"
21516                "// broken:\n"
21517                "auto foo{[]() -> foo<~5> { return {}; }};\n"
21518                "} // namespace bar");
21519   verifyFormat("namespace bar {\n"
21520                "// broken:\n"
21521                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
21522                "} // namespace bar");
21523   verifyFormat("namespace bar {\n"
21524                "// broken:\n"
21525                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
21526                "} // namespace bar");
21527   verifyFormat("namespace bar {\n"
21528                "// broken:\n"
21529                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
21530                "} // namespace bar");
21531   verifyFormat("namespace bar {\n"
21532                "// broken:\n"
21533                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
21534                "} // namespace bar");
21535   verifyFormat("namespace bar {\n"
21536                "// broken:\n"
21537                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
21538                "} // namespace bar");
21539   verifyFormat("namespace bar {\n"
21540                "// broken:\n"
21541                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
21542                "} // namespace bar");
21543   verifyFormat("namespace bar {\n"
21544                "// broken:\n"
21545                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
21546                "} // namespace bar");
21547   verifyFormat("namespace bar {\n"
21548                "// broken:\n"
21549                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
21550                "} // namespace bar");
21551   verifyFormat("namespace bar {\n"
21552                "// broken:\n"
21553                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
21554                "} // namespace bar");
21555   verifyFormat("namespace bar {\n"
21556                "// broken:\n"
21557                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
21558                "} // namespace bar");
21559   verifyFormat("[]() -> a<1> {};");
21560   verifyFormat("[]() -> a<1> { ; };");
21561   verifyFormat("[]() -> a<1> { ; }();");
21562   verifyFormat("[a, a]() -> a<true> {};");
21563   verifyFormat("[]() -> a<true> {};");
21564   verifyFormat("[]() -> a<true> { ; };");
21565   verifyFormat("[]() -> a<true> { ; }();");
21566   verifyFormat("[a, a]() -> a<false> {};");
21567   verifyFormat("[]() -> a<false> {};");
21568   verifyFormat("[]() -> a<false> { ; };");
21569   verifyFormat("[]() -> a<false> { ; }();");
21570   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
21571   verifyFormat("namespace bar {\n"
21572                "auto foo{[]() -> foo<false> { ; }};\n"
21573                "} // namespace bar");
21574   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
21575                "                   int j) -> int {\n"
21576                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
21577                "};");
21578   verifyFormat(
21579       "aaaaaaaaaaaaaaaaaaaaaa(\n"
21580       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
21581       "      return aaaaaaaaaaaaaaaaa;\n"
21582       "    });",
21583       getLLVMStyleWithColumns(70));
21584   verifyFormat("[]() //\n"
21585                "    -> int {\n"
21586                "  return 1; //\n"
21587                "};");
21588   verifyFormat("[]() -> Void<T...> {};");
21589   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
21590   verifyFormat("SomeFunction({[]() -> int[] { return {}; }});");
21591   verifyFormat("SomeFunction({[]() -> int *[] { return {}; }});");
21592   verifyFormat("SomeFunction({[]() -> int (*)[] { return {}; }});");
21593   verifyFormat("SomeFunction({[]() -> ns::type<int (*)[]> { return {}; }});");
21594   verifyFormat("return int{[x = x]() { return x; }()};");
21595 
21596   // Lambdas with explicit template argument lists.
21597   verifyFormat(
21598       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
21599   verifyFormat("auto L = []<class T>(T) {\n"
21600                "  {\n"
21601                "    f();\n"
21602                "    g();\n"
21603                "  }\n"
21604                "};\n");
21605   verifyFormat("auto L = []<class... T>(T...) {\n"
21606                "  {\n"
21607                "    f();\n"
21608                "    g();\n"
21609                "  }\n"
21610                "};\n");
21611   verifyFormat("auto L = []<typename... T>(T...) {\n"
21612                "  {\n"
21613                "    f();\n"
21614                "    g();\n"
21615                "  }\n"
21616                "};\n");
21617   verifyFormat("auto L = []<template <typename...> class T>(T...) {\n"
21618                "  {\n"
21619                "    f();\n"
21620                "    g();\n"
21621                "  }\n"
21622                "};\n");
21623   verifyFormat("auto L = []</*comment*/ class... T>(T...) {\n"
21624                "  {\n"
21625                "    f();\n"
21626                "    g();\n"
21627                "  }\n"
21628                "};\n");
21629 
21630   // Multiple lambdas in the same parentheses change indentation rules. These
21631   // lambdas are forced to start on new lines.
21632   verifyFormat("SomeFunction(\n"
21633                "    []() {\n"
21634                "      //\n"
21635                "    },\n"
21636                "    []() {\n"
21637                "      //\n"
21638                "    });");
21639 
21640   // A lambda passed as arg0 is always pushed to the next line.
21641   verifyFormat("SomeFunction(\n"
21642                "    [this] {\n"
21643                "      //\n"
21644                "    },\n"
21645                "    1);\n");
21646 
21647   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
21648   // the arg0 case above.
21649   auto Style = getGoogleStyle();
21650   Style.BinPackArguments = false;
21651   verifyFormat("SomeFunction(\n"
21652                "    a,\n"
21653                "    [this] {\n"
21654                "      //\n"
21655                "    },\n"
21656                "    b);\n",
21657                Style);
21658   verifyFormat("SomeFunction(\n"
21659                "    a,\n"
21660                "    [this] {\n"
21661                "      //\n"
21662                "    },\n"
21663                "    b);\n");
21664 
21665   // A lambda with a very long line forces arg0 to be pushed out irrespective of
21666   // the BinPackArguments value (as long as the code is wide enough).
21667   verifyFormat(
21668       "something->SomeFunction(\n"
21669       "    a,\n"
21670       "    [this] {\n"
21671       "      "
21672       "D0000000000000000000000000000000000000000000000000000000000001();\n"
21673       "    },\n"
21674       "    b);\n");
21675 
21676   // A multi-line lambda is pulled up as long as the introducer fits on the
21677   // previous line and there are no further args.
21678   verifyFormat("function(1, [this, that] {\n"
21679                "  //\n"
21680                "});\n");
21681   verifyFormat("function([this, that] {\n"
21682                "  //\n"
21683                "});\n");
21684   // FIXME: this format is not ideal and we should consider forcing the first
21685   // arg onto its own line.
21686   verifyFormat("function(a, b, c, //\n"
21687                "         d, [this, that] {\n"
21688                "           //\n"
21689                "         });\n");
21690 
21691   // Multiple lambdas are treated correctly even when there is a short arg0.
21692   verifyFormat("SomeFunction(\n"
21693                "    1,\n"
21694                "    [this] {\n"
21695                "      //\n"
21696                "    },\n"
21697                "    [this] {\n"
21698                "      //\n"
21699                "    },\n"
21700                "    1);\n");
21701 
21702   // More complex introducers.
21703   verifyFormat("return [i, args...] {};");
21704 
21705   // Not lambdas.
21706   verifyFormat("constexpr char hello[]{\"hello\"};");
21707   verifyFormat("double &operator[](int i) { return 0; }\n"
21708                "int i;");
21709   verifyFormat("std::unique_ptr<int[]> foo() {}");
21710   verifyFormat("int i = a[a][a]->f();");
21711   verifyFormat("int i = (*b)[a]->f();");
21712 
21713   // Other corner cases.
21714   verifyFormat("void f() {\n"
21715                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
21716                "  );\n"
21717                "}");
21718   verifyFormat("auto k = *[](int *j) { return j; }(&i);");
21719 
21720   // Lambdas created through weird macros.
21721   verifyFormat("void f() {\n"
21722                "  MACRO((const AA &a) { return 1; });\n"
21723                "  MACRO((AA &a) { return 1; });\n"
21724                "}");
21725 
21726   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
21727                "      doo_dah();\n"
21728                "      doo_dah();\n"
21729                "    })) {\n"
21730                "}");
21731   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
21732                "                doo_dah();\n"
21733                "                doo_dah();\n"
21734                "              })) {\n"
21735                "}");
21736   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
21737                "                doo_dah();\n"
21738                "                doo_dah();\n"
21739                "              })) {\n"
21740                "}");
21741   verifyFormat("auto lambda = []() {\n"
21742                "  int a = 2\n"
21743                "#if A\n"
21744                "          + 2\n"
21745                "#endif\n"
21746                "      ;\n"
21747                "};");
21748 
21749   // Lambdas with complex multiline introducers.
21750   verifyFormat(
21751       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21752       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
21753       "        -> ::std::unordered_set<\n"
21754       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
21755       "      //\n"
21756       "    });");
21757 
21758   FormatStyle DoNotMerge = getLLVMStyle();
21759   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
21760   verifyFormat("auto c = []() {\n"
21761                "  return b;\n"
21762                "};",
21763                "auto c = []() { return b; };", DoNotMerge);
21764   verifyFormat("auto c = []() {\n"
21765                "};",
21766                " auto c = []() {};", DoNotMerge);
21767 
21768   FormatStyle MergeEmptyOnly = getLLVMStyle();
21769   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
21770   verifyFormat("auto c = []() {\n"
21771                "  return b;\n"
21772                "};",
21773                "auto c = []() {\n"
21774                "  return b;\n"
21775                " };",
21776                MergeEmptyOnly);
21777   verifyFormat("auto c = []() {};",
21778                "auto c = []() {\n"
21779                "};",
21780                MergeEmptyOnly);
21781 
21782   FormatStyle MergeInline = getLLVMStyle();
21783   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
21784   verifyFormat("auto c = []() {\n"
21785                "  return b;\n"
21786                "};",
21787                "auto c = []() { return b; };", MergeInline);
21788   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
21789                MergeInline);
21790   verifyFormat("function([]() { return b; }, a)",
21791                "function([]() { return b; }, a)", MergeInline);
21792   verifyFormat("function(a, []() { return b; })",
21793                "function(a, []() { return b; })", MergeInline);
21794 
21795   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
21796   // AllowShortLambdasOnASingleLine
21797   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
21798   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
21799   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
21800   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21801       FormatStyle::ShortLambdaStyle::SLS_None;
21802   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
21803                "    []()\n"
21804                "    {\n"
21805                "      return 17;\n"
21806                "    });",
21807                LLVMWithBeforeLambdaBody);
21808   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
21809                "    []()\n"
21810                "    {\n"
21811                "    });",
21812                LLVMWithBeforeLambdaBody);
21813   verifyFormat("auto fct_SLS_None = []()\n"
21814                "{\n"
21815                "  return 17;\n"
21816                "};",
21817                LLVMWithBeforeLambdaBody);
21818   verifyFormat("TwoNestedLambdas_SLS_None(\n"
21819                "    []()\n"
21820                "    {\n"
21821                "      return Call(\n"
21822                "          []()\n"
21823                "          {\n"
21824                "            return 17;\n"
21825                "          });\n"
21826                "    });",
21827                LLVMWithBeforeLambdaBody);
21828   verifyFormat("void Fct() {\n"
21829                "  return {[]()\n"
21830                "          {\n"
21831                "            return 17;\n"
21832                "          }};\n"
21833                "}",
21834                LLVMWithBeforeLambdaBody);
21835 
21836   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21837       FormatStyle::ShortLambdaStyle::SLS_Empty;
21838   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
21839                "    []()\n"
21840                "    {\n"
21841                "      return 17;\n"
21842                "    });",
21843                LLVMWithBeforeLambdaBody);
21844   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
21845                LLVMWithBeforeLambdaBody);
21846   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
21847                "ongFunctionName_SLS_Empty(\n"
21848                "    []() {});",
21849                LLVMWithBeforeLambdaBody);
21850   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
21851                "                                []()\n"
21852                "                                {\n"
21853                "                                  return 17;\n"
21854                "                                });",
21855                LLVMWithBeforeLambdaBody);
21856   verifyFormat("auto fct_SLS_Empty = []()\n"
21857                "{\n"
21858                "  return 17;\n"
21859                "};",
21860                LLVMWithBeforeLambdaBody);
21861   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
21862                "    []()\n"
21863                "    {\n"
21864                "      return Call([]() {});\n"
21865                "    });",
21866                LLVMWithBeforeLambdaBody);
21867   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
21868                "                           []()\n"
21869                "                           {\n"
21870                "                             return Call([]() {});\n"
21871                "                           });",
21872                LLVMWithBeforeLambdaBody);
21873   verifyFormat(
21874       "FctWithLongLineInLambda_SLS_Empty(\n"
21875       "    []()\n"
21876       "    {\n"
21877       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21878       "                               AndShouldNotBeConsiderAsInline,\n"
21879       "                               LambdaBodyMustBeBreak);\n"
21880       "    });",
21881       LLVMWithBeforeLambdaBody);
21882 
21883   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21884       FormatStyle::ShortLambdaStyle::SLS_Inline;
21885   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
21886                LLVMWithBeforeLambdaBody);
21887   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
21888                LLVMWithBeforeLambdaBody);
21889   verifyFormat("auto fct_SLS_Inline = []()\n"
21890                "{\n"
21891                "  return 17;\n"
21892                "};",
21893                LLVMWithBeforeLambdaBody);
21894   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
21895                "17; }); });",
21896                LLVMWithBeforeLambdaBody);
21897   verifyFormat(
21898       "FctWithLongLineInLambda_SLS_Inline(\n"
21899       "    []()\n"
21900       "    {\n"
21901       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21902       "                               AndShouldNotBeConsiderAsInline,\n"
21903       "                               LambdaBodyMustBeBreak);\n"
21904       "    });",
21905       LLVMWithBeforeLambdaBody);
21906   verifyFormat("FctWithMultipleParams_SLS_Inline("
21907                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21908                "                                 []() { return 17; });",
21909                LLVMWithBeforeLambdaBody);
21910   verifyFormat(
21911       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
21912       LLVMWithBeforeLambdaBody);
21913 
21914   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
21915       FormatStyle::ShortLambdaStyle::SLS_All;
21916   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
21917                LLVMWithBeforeLambdaBody);
21918   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
21919                LLVMWithBeforeLambdaBody);
21920   verifyFormat("auto fct_SLS_All = []() { return 17; };",
21921                LLVMWithBeforeLambdaBody);
21922   verifyFormat("FctWithOneParam_SLS_All(\n"
21923                "    []()\n"
21924                "    {\n"
21925                "      // A cool function...\n"
21926                "      return 43;\n"
21927                "    });",
21928                LLVMWithBeforeLambdaBody);
21929   verifyFormat("FctWithMultipleParams_SLS_All("
21930                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
21931                "                              []() { return 17; });",
21932                LLVMWithBeforeLambdaBody);
21933   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
21934                LLVMWithBeforeLambdaBody);
21935   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
21936                LLVMWithBeforeLambdaBody);
21937   verifyFormat(
21938       "FctWithLongLineInLambda_SLS_All(\n"
21939       "    []()\n"
21940       "    {\n"
21941       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21942       "                               AndShouldNotBeConsiderAsInline,\n"
21943       "                               LambdaBodyMustBeBreak);\n"
21944       "    });",
21945       LLVMWithBeforeLambdaBody);
21946   verifyFormat(
21947       "auto fct_SLS_All = []()\n"
21948       "{\n"
21949       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21950       "                           AndShouldNotBeConsiderAsInline,\n"
21951       "                           LambdaBodyMustBeBreak);\n"
21952       "};",
21953       LLVMWithBeforeLambdaBody);
21954   LLVMWithBeforeLambdaBody.BinPackParameters = false;
21955   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
21956                LLVMWithBeforeLambdaBody);
21957   verifyFormat(
21958       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
21959       "                                FirstParam,\n"
21960       "                                SecondParam,\n"
21961       "                                ThirdParam,\n"
21962       "                                FourthParam);",
21963       LLVMWithBeforeLambdaBody);
21964   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21965                "    []() { return "
21966                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
21967                "    FirstParam,\n"
21968                "    SecondParam,\n"
21969                "    ThirdParam,\n"
21970                "    FourthParam);",
21971                LLVMWithBeforeLambdaBody);
21972   verifyFormat(
21973       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
21974       "                                SecondParam,\n"
21975       "                                ThirdParam,\n"
21976       "                                FourthParam,\n"
21977       "                                []() { return SomeValueNotSoLong; });",
21978       LLVMWithBeforeLambdaBody);
21979   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
21980                "    []()\n"
21981                "    {\n"
21982                "      return "
21983                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
21984                "eConsiderAsInline;\n"
21985                "    });",
21986                LLVMWithBeforeLambdaBody);
21987   verifyFormat(
21988       "FctWithLongLineInLambda_SLS_All(\n"
21989       "    []()\n"
21990       "    {\n"
21991       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
21992       "                               AndShouldNotBeConsiderAsInline,\n"
21993       "                               LambdaBodyMustBeBreak);\n"
21994       "    });",
21995       LLVMWithBeforeLambdaBody);
21996   verifyFormat("FctWithTwoParams_SLS_All(\n"
21997                "    []()\n"
21998                "    {\n"
21999                "      // A cool function...\n"
22000                "      return 43;\n"
22001                "    },\n"
22002                "    87);",
22003                LLVMWithBeforeLambdaBody);
22004   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
22005                LLVMWithBeforeLambdaBody);
22006   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
22007                LLVMWithBeforeLambdaBody);
22008   verifyFormat(
22009       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
22010       LLVMWithBeforeLambdaBody);
22011   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
22012                "}); }, x);",
22013                LLVMWithBeforeLambdaBody);
22014   verifyFormat("TwoNestedLambdas_SLS_All(\n"
22015                "    []()\n"
22016                "    {\n"
22017                "      // A cool function...\n"
22018                "      return Call([]() { return 17; });\n"
22019                "    });",
22020                LLVMWithBeforeLambdaBody);
22021   verifyFormat("TwoNestedLambdas_SLS_All(\n"
22022                "    []()\n"
22023                "    {\n"
22024                "      return Call(\n"
22025                "          []()\n"
22026                "          {\n"
22027                "            // A cool function...\n"
22028                "            return 17;\n"
22029                "          });\n"
22030                "    });",
22031                LLVMWithBeforeLambdaBody);
22032 
22033   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
22034       FormatStyle::ShortLambdaStyle::SLS_None;
22035 
22036   verifyFormat("auto select = [this]() -> const Library::Object *\n"
22037                "{\n"
22038                "  return MyAssignment::SelectFromList(this);\n"
22039                "};\n",
22040                LLVMWithBeforeLambdaBody);
22041 
22042   verifyFormat("auto select = [this]() -> const Library::Object &\n"
22043                "{\n"
22044                "  return MyAssignment::SelectFromList(this);\n"
22045                "};\n",
22046                LLVMWithBeforeLambdaBody);
22047 
22048   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
22049                "{\n"
22050                "  return MyAssignment::SelectFromList(this);\n"
22051                "};\n",
22052                LLVMWithBeforeLambdaBody);
22053 
22054   verifyFormat("namespace test {\n"
22055                "class Test {\n"
22056                "public:\n"
22057                "  Test() = default;\n"
22058                "};\n"
22059                "} // namespace test",
22060                LLVMWithBeforeLambdaBody);
22061 
22062   // Lambdas with different indentation styles.
22063   Style = getLLVMStyleWithColumns(100);
22064   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
22065             "  return promise.then(\n"
22066             "      [this, &someVariable, someObject = "
22067             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
22068             "        return someObject.startAsyncAction().then(\n"
22069             "            [this, &someVariable](AsyncActionResult result) "
22070             "mutable { result.processMore(); });\n"
22071             "      });\n"
22072             "}\n",
22073             format("SomeResult doSomething(SomeObject promise) {\n"
22074                    "  return promise.then([this, &someVariable, someObject = "
22075                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
22076                    "    return someObject.startAsyncAction().then([this, "
22077                    "&someVariable](AsyncActionResult result) mutable {\n"
22078                    "      result.processMore();\n"
22079                    "    });\n"
22080                    "  });\n"
22081                    "}\n",
22082                    Style));
22083   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
22084   verifyFormat("test() {\n"
22085                "  ([]() -> {\n"
22086                "    int b = 32;\n"
22087                "    return 3;\n"
22088                "  }).foo();\n"
22089                "}",
22090                Style);
22091   verifyFormat("test() {\n"
22092                "  []() -> {\n"
22093                "    int b = 32;\n"
22094                "    return 3;\n"
22095                "  }\n"
22096                "}",
22097                Style);
22098   verifyFormat("std::sort(v.begin(), v.end(),\n"
22099                "          [](const auto &someLongArgumentName, const auto "
22100                "&someOtherLongArgumentName) {\n"
22101                "  return someLongArgumentName.someMemberVariable < "
22102                "someOtherLongArgumentName.someMemberVariable;\n"
22103                "});",
22104                Style);
22105   verifyFormat("test() {\n"
22106                "  (\n"
22107                "      []() -> {\n"
22108                "        int b = 32;\n"
22109                "        return 3;\n"
22110                "      },\n"
22111                "      foo, bar)\n"
22112                "      .foo();\n"
22113                "}",
22114                Style);
22115   verifyFormat("test() {\n"
22116                "  ([]() -> {\n"
22117                "    int b = 32;\n"
22118                "    return 3;\n"
22119                "  })\n"
22120                "      .foo()\n"
22121                "      .bar();\n"
22122                "}",
22123                Style);
22124   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
22125             "  return promise.then(\n"
22126             "      [this, &someVariable, someObject = "
22127             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
22128             "    return someObject.startAsyncAction().then(\n"
22129             "        [this, &someVariable](AsyncActionResult result) mutable { "
22130             "result.processMore(); });\n"
22131             "  });\n"
22132             "}\n",
22133             format("SomeResult doSomething(SomeObject promise) {\n"
22134                    "  return promise.then([this, &someVariable, someObject = "
22135                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
22136                    "    return someObject.startAsyncAction().then([this, "
22137                    "&someVariable](AsyncActionResult result) mutable {\n"
22138                    "      result.processMore();\n"
22139                    "    });\n"
22140                    "  });\n"
22141                    "}\n",
22142                    Style));
22143   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
22144             "  return promise.then([this, &someVariable] {\n"
22145             "    return someObject.startAsyncAction().then(\n"
22146             "        [this, &someVariable](AsyncActionResult result) mutable { "
22147             "result.processMore(); });\n"
22148             "  });\n"
22149             "}\n",
22150             format("SomeResult doSomething(SomeObject promise) {\n"
22151                    "  return promise.then([this, &someVariable] {\n"
22152                    "    return someObject.startAsyncAction().then([this, "
22153                    "&someVariable](AsyncActionResult result) mutable {\n"
22154                    "      result.processMore();\n"
22155                    "    });\n"
22156                    "  });\n"
22157                    "}\n",
22158                    Style));
22159   Style = getGoogleStyle();
22160   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
22161   EXPECT_EQ("#define A                                       \\\n"
22162             "  [] {                                          \\\n"
22163             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
22164             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
22165             "      }",
22166             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
22167                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
22168                    Style));
22169   // TODO: The current formatting has a minor issue that's not worth fixing
22170   // right now whereby the closing brace is indented relative to the signature
22171   // instead of being aligned. This only happens with macros.
22172 }
22173 
TEST_F(FormatTest,LambdaWithLineComments)22174 TEST_F(FormatTest, LambdaWithLineComments) {
22175   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
22176   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
22177   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
22178   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
22179       FormatStyle::ShortLambdaStyle::SLS_All;
22180 
22181   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
22182   verifyFormat("auto k = []() // comment\n"
22183                "{ return; }",
22184                LLVMWithBeforeLambdaBody);
22185   verifyFormat("auto k = []() /* comment */ { return; }",
22186                LLVMWithBeforeLambdaBody);
22187   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
22188                LLVMWithBeforeLambdaBody);
22189   verifyFormat("auto k = []() // X\n"
22190                "{ return; }",
22191                LLVMWithBeforeLambdaBody);
22192   verifyFormat(
22193       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
22194       "{ return; }",
22195       LLVMWithBeforeLambdaBody);
22196 
22197   LLVMWithBeforeLambdaBody.ColumnLimit = 0;
22198 
22199   verifyFormat("foo([]()\n"
22200                "    {\n"
22201                "      bar();    //\n"
22202                "      return 1; // comment\n"
22203                "    }());",
22204                "foo([]() {\n"
22205                "  bar(); //\n"
22206                "  return 1; // comment\n"
22207                "}());",
22208                LLVMWithBeforeLambdaBody);
22209   verifyFormat("foo(\n"
22210                "    1, MACRO {\n"
22211                "      baz();\n"
22212                "      bar(); // comment\n"
22213                "    },\n"
22214                "    []() {});",
22215                "foo(\n"
22216                "  1, MACRO { baz(); bar(); // comment\n"
22217                "  }, []() {}\n"
22218                ");",
22219                LLVMWithBeforeLambdaBody);
22220 }
22221 
TEST_F(FormatTest,EmptyLinesInLambdas)22222 TEST_F(FormatTest, EmptyLinesInLambdas) {
22223   verifyFormat("auto lambda = []() {\n"
22224                "  x(); //\n"
22225                "};",
22226                "auto lambda = []() {\n"
22227                "\n"
22228                "  x(); //\n"
22229                "\n"
22230                "};");
22231 }
22232 
TEST_F(FormatTest,FormatsBlocks)22233 TEST_F(FormatTest, FormatsBlocks) {
22234   FormatStyle ShortBlocks = getLLVMStyle();
22235   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22236   verifyFormat("int (^Block)(int, int);", ShortBlocks);
22237   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
22238   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
22239   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
22240   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
22241   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
22242 
22243   verifyFormat("foo(^{ bar(); });", ShortBlocks);
22244   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
22245   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
22246 
22247   verifyFormat("[operation setCompletionBlock:^{\n"
22248                "  [self onOperationDone];\n"
22249                "}];");
22250   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
22251                "  [self onOperationDone];\n"
22252                "}]};");
22253   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
22254                "  f();\n"
22255                "}];");
22256   verifyFormat("int a = [operation block:^int(int *i) {\n"
22257                "  return 1;\n"
22258                "}];");
22259   verifyFormat("[myObject doSomethingWith:arg1\n"
22260                "                      aaa:^int(int *a) {\n"
22261                "                        return 1;\n"
22262                "                      }\n"
22263                "                      bbb:f(a * bbbbbbbb)];");
22264 
22265   verifyFormat("[operation setCompletionBlock:^{\n"
22266                "  [self.delegate newDataAvailable];\n"
22267                "}];",
22268                getLLVMStyleWithColumns(60));
22269   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
22270                "  NSString *path = [self sessionFilePath];\n"
22271                "  if (path) {\n"
22272                "    // ...\n"
22273                "  }\n"
22274                "});");
22275   verifyFormat("[[SessionService sharedService]\n"
22276                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22277                "      if (window) {\n"
22278                "        [self windowDidLoad:window];\n"
22279                "      } else {\n"
22280                "        [self errorLoadingWindow];\n"
22281                "      }\n"
22282                "    }];");
22283   verifyFormat("void (^largeBlock)(void) = ^{\n"
22284                "  // ...\n"
22285                "};\n",
22286                getLLVMStyleWithColumns(40));
22287   verifyFormat("[[SessionService sharedService]\n"
22288                "    loadWindowWithCompletionBlock: //\n"
22289                "        ^(SessionWindow *window) {\n"
22290                "          if (window) {\n"
22291                "            [self windowDidLoad:window];\n"
22292                "          } else {\n"
22293                "            [self errorLoadingWindow];\n"
22294                "          }\n"
22295                "        }];",
22296                getLLVMStyleWithColumns(60));
22297   verifyFormat("[myObject doSomethingWith:arg1\n"
22298                "    firstBlock:^(Foo *a) {\n"
22299                "      // ...\n"
22300                "      int i;\n"
22301                "    }\n"
22302                "    secondBlock:^(Bar *b) {\n"
22303                "      // ...\n"
22304                "      int i;\n"
22305                "    }\n"
22306                "    thirdBlock:^Foo(Bar *b) {\n"
22307                "      // ...\n"
22308                "      int i;\n"
22309                "    }];");
22310   verifyFormat("[myObject doSomethingWith:arg1\n"
22311                "               firstBlock:-1\n"
22312                "              secondBlock:^(Bar *b) {\n"
22313                "                // ...\n"
22314                "                int i;\n"
22315                "              }];");
22316 
22317   verifyFormat("f(^{\n"
22318                "  @autoreleasepool {\n"
22319                "    if (a) {\n"
22320                "      g();\n"
22321                "    }\n"
22322                "  }\n"
22323                "});");
22324   verifyFormat("Block b = ^int *(A *a, B *b) {}");
22325   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
22326                "};");
22327 
22328   FormatStyle FourIndent = getLLVMStyle();
22329   FourIndent.ObjCBlockIndentWidth = 4;
22330   verifyFormat("[operation setCompletionBlock:^{\n"
22331                "    [self onOperationDone];\n"
22332                "}];",
22333                FourIndent);
22334 }
22335 
TEST_F(FormatTest,FormatsBlocksWithZeroColumnWidth)22336 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
22337   FormatStyle ZeroColumn = getLLVMStyleWithColumns(0);
22338 
22339   verifyFormat("[[SessionService sharedService] "
22340                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22341                "  if (window) {\n"
22342                "    [self windowDidLoad:window];\n"
22343                "  } else {\n"
22344                "    [self errorLoadingWindow];\n"
22345                "  }\n"
22346                "}];",
22347                ZeroColumn);
22348   EXPECT_EQ("[[SessionService sharedService]\n"
22349             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22350             "      if (window) {\n"
22351             "        [self windowDidLoad:window];\n"
22352             "      } else {\n"
22353             "        [self errorLoadingWindow];\n"
22354             "      }\n"
22355             "    }];",
22356             format("[[SessionService sharedService]\n"
22357                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
22358                    "                if (window) {\n"
22359                    "    [self windowDidLoad:window];\n"
22360                    "  } else {\n"
22361                    "    [self errorLoadingWindow];\n"
22362                    "  }\n"
22363                    "}];",
22364                    ZeroColumn));
22365   verifyFormat("[myObject doSomethingWith:arg1\n"
22366                "    firstBlock:^(Foo *a) {\n"
22367                "      // ...\n"
22368                "      int i;\n"
22369                "    }\n"
22370                "    secondBlock:^(Bar *b) {\n"
22371                "      // ...\n"
22372                "      int i;\n"
22373                "    }\n"
22374                "    thirdBlock:^Foo(Bar *b) {\n"
22375                "      // ...\n"
22376                "      int i;\n"
22377                "    }];",
22378                ZeroColumn);
22379   verifyFormat("f(^{\n"
22380                "  @autoreleasepool {\n"
22381                "    if (a) {\n"
22382                "      g();\n"
22383                "    }\n"
22384                "  }\n"
22385                "});",
22386                ZeroColumn);
22387   verifyFormat("void (^largeBlock)(void) = ^{\n"
22388                "  // ...\n"
22389                "};",
22390                ZeroColumn);
22391 
22392   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
22393   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
22394             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22395   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
22396   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
22397             "  int i;\n"
22398             "};",
22399             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
22400 }
22401 
TEST_F(FormatTest,SupportsCRLF)22402 TEST_F(FormatTest, SupportsCRLF) {
22403   EXPECT_EQ("int a;\r\n"
22404             "int b;\r\n"
22405             "int c;\r\n",
22406             format("int a;\r\n"
22407                    "  int b;\r\n"
22408                    "    int c;\r\n",
22409                    getLLVMStyle()));
22410   EXPECT_EQ("int a;\r\n"
22411             "int b;\r\n"
22412             "int c;\r\n",
22413             format("int a;\r\n"
22414                    "  int b;\n"
22415                    "    int c;\r\n",
22416                    getLLVMStyle()));
22417   EXPECT_EQ("int a;\n"
22418             "int b;\n"
22419             "int c;\n",
22420             format("int a;\r\n"
22421                    "  int b;\n"
22422                    "    int c;\n",
22423                    getLLVMStyle()));
22424   EXPECT_EQ("\"aaaaaaa \"\r\n"
22425             "\"bbbbbbb\";\r\n",
22426             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
22427   EXPECT_EQ("#define A \\\r\n"
22428             "  b;      \\\r\n"
22429             "  c;      \\\r\n"
22430             "  d;\r\n",
22431             format("#define A \\\r\n"
22432                    "  b; \\\r\n"
22433                    "  c; d; \r\n",
22434                    getGoogleStyle()));
22435 
22436   EXPECT_EQ("/*\r\n"
22437             "multi line block comments\r\n"
22438             "should not introduce\r\n"
22439             "an extra carriage return\r\n"
22440             "*/\r\n",
22441             format("/*\r\n"
22442                    "multi line block comments\r\n"
22443                    "should not introduce\r\n"
22444                    "an extra carriage return\r\n"
22445                    "*/\r\n"));
22446   EXPECT_EQ("/*\r\n"
22447             "\r\n"
22448             "*/",
22449             format("/*\r\n"
22450                    "    \r\r\r\n"
22451                    "*/"));
22452 
22453   FormatStyle style = getLLVMStyle();
22454 
22455   style.DeriveLineEnding = true;
22456   style.UseCRLF = false;
22457   EXPECT_EQ("union FooBarBazQux {\n"
22458             "  int foo;\n"
22459             "  int bar;\n"
22460             "  int baz;\n"
22461             "};",
22462             format("union FooBarBazQux {\r\n"
22463                    "  int foo;\n"
22464                    "  int bar;\r\n"
22465                    "  int baz;\n"
22466                    "};",
22467                    style));
22468   style.UseCRLF = true;
22469   EXPECT_EQ("union FooBarBazQux {\r\n"
22470             "  int foo;\r\n"
22471             "  int bar;\r\n"
22472             "  int baz;\r\n"
22473             "};",
22474             format("union FooBarBazQux {\r\n"
22475                    "  int foo;\n"
22476                    "  int bar;\r\n"
22477                    "  int baz;\n"
22478                    "};",
22479                    style));
22480 
22481   style.DeriveLineEnding = false;
22482   style.UseCRLF = false;
22483   EXPECT_EQ("union FooBarBazQux {\n"
22484             "  int foo;\n"
22485             "  int bar;\n"
22486             "  int baz;\n"
22487             "  int qux;\n"
22488             "};",
22489             format("union FooBarBazQux {\r\n"
22490                    "  int foo;\n"
22491                    "  int bar;\r\n"
22492                    "  int baz;\n"
22493                    "  int qux;\r\n"
22494                    "};",
22495                    style));
22496   style.UseCRLF = true;
22497   EXPECT_EQ("union FooBarBazQux {\r\n"
22498             "  int foo;\r\n"
22499             "  int bar;\r\n"
22500             "  int baz;\r\n"
22501             "  int qux;\r\n"
22502             "};",
22503             format("union FooBarBazQux {\r\n"
22504                    "  int foo;\n"
22505                    "  int bar;\r\n"
22506                    "  int baz;\n"
22507                    "  int qux;\n"
22508                    "};",
22509                    style));
22510 
22511   style.DeriveLineEnding = true;
22512   style.UseCRLF = false;
22513   EXPECT_EQ("union FooBarBazQux {\r\n"
22514             "  int foo;\r\n"
22515             "  int bar;\r\n"
22516             "  int baz;\r\n"
22517             "  int qux;\r\n"
22518             "};",
22519             format("union FooBarBazQux {\r\n"
22520                    "  int foo;\n"
22521                    "  int bar;\r\n"
22522                    "  int baz;\n"
22523                    "  int qux;\r\n"
22524                    "};",
22525                    style));
22526   style.UseCRLF = true;
22527   EXPECT_EQ("union FooBarBazQux {\n"
22528             "  int foo;\n"
22529             "  int bar;\n"
22530             "  int baz;\n"
22531             "  int qux;\n"
22532             "};",
22533             format("union FooBarBazQux {\r\n"
22534                    "  int foo;\n"
22535                    "  int bar;\r\n"
22536                    "  int baz;\n"
22537                    "  int qux;\n"
22538                    "};",
22539                    style));
22540 }
22541 
TEST_F(FormatTest,MunchSemicolonAfterBlocks)22542 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
22543   verifyFormat("MY_CLASS(C) {\n"
22544                "  int i;\n"
22545                "  int j;\n"
22546                "};");
22547 }
22548 
TEST_F(FormatTest,ConfigurableContinuationIndentWidth)22549 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
22550   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
22551   TwoIndent.ContinuationIndentWidth = 2;
22552 
22553   EXPECT_EQ("int i =\n"
22554             "  longFunction(\n"
22555             "    arg);",
22556             format("int i = longFunction(arg);", TwoIndent));
22557 
22558   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
22559   SixIndent.ContinuationIndentWidth = 6;
22560 
22561   EXPECT_EQ("int i =\n"
22562             "      longFunction(\n"
22563             "            arg);",
22564             format("int i = longFunction(arg);", SixIndent));
22565 }
22566 
TEST_F(FormatTest,WrappedClosingParenthesisIndent)22567 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
22568   FormatStyle Style = getLLVMStyle();
22569   verifyFormat("int Foo::getter(\n"
22570                "    //\n"
22571                ") const {\n"
22572                "  return foo;\n"
22573                "}",
22574                Style);
22575   verifyFormat("void Foo::setter(\n"
22576                "    //\n"
22577                ") {\n"
22578                "  foo = 1;\n"
22579                "}",
22580                Style);
22581 }
22582 
TEST_F(FormatTest,SpacesInAngles)22583 TEST_F(FormatTest, SpacesInAngles) {
22584   FormatStyle Spaces = getLLVMStyle();
22585   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22586 
22587   verifyFormat("vector< ::std::string > x1;", Spaces);
22588   verifyFormat("Foo< int, Bar > x2;", Spaces);
22589   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
22590 
22591   verifyFormat("static_cast< int >(arg);", Spaces);
22592   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
22593   verifyFormat("f< int, float >();", Spaces);
22594   verifyFormat("template <> g() {}", Spaces);
22595   verifyFormat("template < std::vector< int > > f() {}", Spaces);
22596   verifyFormat("std::function< void(int, int) > fct;", Spaces);
22597   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
22598                Spaces);
22599 
22600   Spaces.Standard = FormatStyle::LS_Cpp03;
22601   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22602   verifyFormat("A< A< int > >();", Spaces);
22603 
22604   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22605   verifyFormat("A<A<int> >();", Spaces);
22606 
22607   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22608   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
22609                Spaces);
22610   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
22611                Spaces);
22612 
22613   verifyFormat("A<A<int> >();", Spaces);
22614   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
22615   verifyFormat("A< A< int > >();", Spaces);
22616 
22617   Spaces.Standard = FormatStyle::LS_Cpp11;
22618   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22619   verifyFormat("A< A< int > >();", Spaces);
22620 
22621   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
22622   verifyFormat("vector<::std::string> x4;", Spaces);
22623   verifyFormat("vector<int> x5;", Spaces);
22624   verifyFormat("Foo<int, Bar> x6;", Spaces);
22625   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22626 
22627   verifyFormat("A<A<int>>();", Spaces);
22628 
22629   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
22630   verifyFormat("vector<::std::string> x4;", Spaces);
22631   verifyFormat("vector< ::std::string > x4;", Spaces);
22632   verifyFormat("vector<int> x5;", Spaces);
22633   verifyFormat("vector< int > x5;", Spaces);
22634   verifyFormat("Foo<int, Bar> x6;", Spaces);
22635   verifyFormat("Foo< int, Bar > x6;", Spaces);
22636   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
22637   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
22638 
22639   verifyFormat("A<A<int>>();", Spaces);
22640   verifyFormat("A< A< int > >();", Spaces);
22641   verifyFormat("A<A<int > >();", Spaces);
22642   verifyFormat("A< A< int>>();", Spaces);
22643 
22644   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
22645   verifyFormat("// clang-format off\n"
22646                "foo<<<1, 1>>>();\n"
22647                "// clang-format on\n",
22648                Spaces);
22649   verifyFormat("// clang-format off\n"
22650                "foo< < <1, 1> > >();\n"
22651                "// clang-format on\n",
22652                Spaces);
22653 }
22654 
TEST_F(FormatTest,SpaceAfterTemplateKeyword)22655 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
22656   FormatStyle Style = getLLVMStyle();
22657   Style.SpaceAfterTemplateKeyword = false;
22658   verifyFormat("template<int> void foo();", Style);
22659 }
22660 
TEST_F(FormatTest,TripleAngleBrackets)22661 TEST_F(FormatTest, TripleAngleBrackets) {
22662   verifyFormat("f<<<1, 1>>>();");
22663   verifyFormat("f<<<1, 1, 1, s>>>();");
22664   verifyFormat("f<<<a, b, c, d>>>();");
22665   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
22666   verifyFormat("f<param><<<1, 1>>>();");
22667   verifyFormat("f<1><<<1, 1>>>();");
22668   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
22669   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22670                "aaaaaaaaaaa<<<\n    1, 1>>>();");
22671   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
22672                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
22673 }
22674 
TEST_F(FormatTest,MergeLessLessAtEnd)22675 TEST_F(FormatTest, MergeLessLessAtEnd) {
22676   verifyFormat("<<");
22677   EXPECT_EQ("< < <", format("\\\n<<<"));
22678   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22679                "aaallvm::outs() <<");
22680   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
22681                "aaaallvm::outs()\n    <<");
22682 }
22683 
TEST_F(FormatTest,HandleUnbalancedImplicitBracesAcrossPPBranches)22684 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
22685   std::string code = "#if A\n"
22686                      "#if B\n"
22687                      "a.\n"
22688                      "#endif\n"
22689                      "    a = 1;\n"
22690                      "#else\n"
22691                      "#endif\n"
22692                      "#if C\n"
22693                      "#else\n"
22694                      "#endif\n";
22695   EXPECT_EQ(code, format(code));
22696 }
22697 
TEST_F(FormatTest,HandleConflictMarkers)22698 TEST_F(FormatTest, HandleConflictMarkers) {
22699   // Git/SVN conflict markers.
22700   EXPECT_EQ("int a;\n"
22701             "void f() {\n"
22702             "  callme(some(parameter1,\n"
22703             "<<<<<<< text by the vcs\n"
22704             "              parameter2),\n"
22705             "||||||| text by the vcs\n"
22706             "              parameter2),\n"
22707             "         parameter3,\n"
22708             "======= text by the vcs\n"
22709             "              parameter2, parameter3),\n"
22710             ">>>>>>> text by the vcs\n"
22711             "         otherparameter);\n",
22712             format("int a;\n"
22713                    "void f() {\n"
22714                    "  callme(some(parameter1,\n"
22715                    "<<<<<<< text by the vcs\n"
22716                    "  parameter2),\n"
22717                    "||||||| text by the vcs\n"
22718                    "  parameter2),\n"
22719                    "  parameter3,\n"
22720                    "======= text by the vcs\n"
22721                    "  parameter2,\n"
22722                    "  parameter3),\n"
22723                    ">>>>>>> text by the vcs\n"
22724                    "  otherparameter);\n"));
22725 
22726   // Perforce markers.
22727   EXPECT_EQ("void f() {\n"
22728             "  function(\n"
22729             ">>>> text by the vcs\n"
22730             "      parameter,\n"
22731             "==== text by the vcs\n"
22732             "      parameter,\n"
22733             "==== text by the vcs\n"
22734             "      parameter,\n"
22735             "<<<< text by the vcs\n"
22736             "      parameter);\n",
22737             format("void f() {\n"
22738                    "  function(\n"
22739                    ">>>> text by the vcs\n"
22740                    "  parameter,\n"
22741                    "==== text by the vcs\n"
22742                    "  parameter,\n"
22743                    "==== text by the vcs\n"
22744                    "  parameter,\n"
22745                    "<<<< text by the vcs\n"
22746                    "  parameter);\n"));
22747 
22748   EXPECT_EQ("<<<<<<<\n"
22749             "|||||||\n"
22750             "=======\n"
22751             ">>>>>>>",
22752             format("<<<<<<<\n"
22753                    "|||||||\n"
22754                    "=======\n"
22755                    ">>>>>>>"));
22756 
22757   EXPECT_EQ("<<<<<<<\n"
22758             "|||||||\n"
22759             "int i;\n"
22760             "=======\n"
22761             ">>>>>>>",
22762             format("<<<<<<<\n"
22763                    "|||||||\n"
22764                    "int i;\n"
22765                    "=======\n"
22766                    ">>>>>>>"));
22767 
22768   // FIXME: Handle parsing of macros around conflict markers correctly:
22769   EXPECT_EQ("#define Macro \\\n"
22770             "<<<<<<<\n"
22771             "Something \\\n"
22772             "|||||||\n"
22773             "Else \\\n"
22774             "=======\n"
22775             "Other \\\n"
22776             ">>>>>>>\n"
22777             "    End int i;\n",
22778             format("#define Macro \\\n"
22779                    "<<<<<<<\n"
22780                    "  Something \\\n"
22781                    "|||||||\n"
22782                    "  Else \\\n"
22783                    "=======\n"
22784                    "  Other \\\n"
22785                    ">>>>>>>\n"
22786                    "  End\n"
22787                    "int i;\n"));
22788 
22789   verifyFormat(R"(====
22790 #ifdef A
22791 a
22792 #else
22793 b
22794 #endif
22795 )");
22796 }
22797 
TEST_F(FormatTest,DisableRegions)22798 TEST_F(FormatTest, DisableRegions) {
22799   EXPECT_EQ("int i;\n"
22800             "// clang-format off\n"
22801             "  int j;\n"
22802             "// clang-format on\n"
22803             "int k;",
22804             format(" int  i;\n"
22805                    "   // clang-format off\n"
22806                    "  int j;\n"
22807                    " // clang-format on\n"
22808                    "   int   k;"));
22809   EXPECT_EQ("int i;\n"
22810             "/* clang-format off */\n"
22811             "  int j;\n"
22812             "/* clang-format on */\n"
22813             "int k;",
22814             format(" int  i;\n"
22815                    "   /* clang-format off */\n"
22816                    "  int j;\n"
22817                    " /* clang-format on */\n"
22818                    "   int   k;"));
22819 
22820   // Don't reflow comments within disabled regions.
22821   EXPECT_EQ("// clang-format off\n"
22822             "// long long long long long long line\n"
22823             "/* clang-format on */\n"
22824             "/* long long long\n"
22825             " * long long long\n"
22826             " * line */\n"
22827             "int i;\n"
22828             "/* clang-format off */\n"
22829             "/* long long long long long long line */\n",
22830             format("// clang-format off\n"
22831                    "// long long long long long long line\n"
22832                    "/* clang-format on */\n"
22833                    "/* long long long long long long line */\n"
22834                    "int i;\n"
22835                    "/* clang-format off */\n"
22836                    "/* long long long long long long line */\n",
22837                    getLLVMStyleWithColumns(20)));
22838 }
22839 
TEST_F(FormatTest,DoNotCrashOnInvalidInput)22840 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
22841   format("? ) =");
22842   verifyNoCrash("#define a\\\n /**/}");
22843 }
22844 
TEST_F(FormatTest,FormatsTableGenCode)22845 TEST_F(FormatTest, FormatsTableGenCode) {
22846   FormatStyle Style = getLLVMStyle();
22847   Style.Language = FormatStyle::LK_TableGen;
22848   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
22849 }
22850 
TEST_F(FormatTest,ArrayOfTemplates)22851 TEST_F(FormatTest, ArrayOfTemplates) {
22852   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
22853             format("auto a = new unique_ptr<int > [ 10];"));
22854 
22855   FormatStyle Spaces = getLLVMStyle();
22856   Spaces.SpacesInSquareBrackets = true;
22857   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
22858             format("auto a = new unique_ptr<int > [10];", Spaces));
22859 }
22860 
TEST_F(FormatTest,ArrayAsTemplateType)22861 TEST_F(FormatTest, ArrayAsTemplateType) {
22862   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
22863             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
22864 
22865   FormatStyle Spaces = getLLVMStyle();
22866   Spaces.SpacesInSquareBrackets = true;
22867   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
22868             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
22869 }
22870 
TEST_F(FormatTest,NoSpaceAfterSuper)22871 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
22872 
TEST(FormatStyle,GetStyleWithEmptyFileName)22873 TEST(FormatStyle, GetStyleWithEmptyFileName) {
22874   llvm::vfs::InMemoryFileSystem FS;
22875   auto Style1 = getStyle("file", "", "Google", "", &FS);
22876   ASSERT_TRUE((bool)Style1);
22877   ASSERT_EQ(*Style1, getGoogleStyle());
22878 }
22879 
TEST(FormatStyle,GetStyleOfFile)22880 TEST(FormatStyle, GetStyleOfFile) {
22881   llvm::vfs::InMemoryFileSystem FS;
22882   // Test 1: format file in the same directory.
22883   ASSERT_TRUE(
22884       FS.addFile("/a/.clang-format", 0,
22885                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
22886   ASSERT_TRUE(
22887       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22888   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
22889   ASSERT_TRUE((bool)Style1);
22890   ASSERT_EQ(*Style1, getLLVMStyle());
22891 
22892   // Test 2.1: fallback to default.
22893   ASSERT_TRUE(
22894       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22895   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
22896   ASSERT_TRUE((bool)Style2);
22897   ASSERT_EQ(*Style2, getMozillaStyle());
22898 
22899   // Test 2.2: no format on 'none' fallback style.
22900   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22901   ASSERT_TRUE((bool)Style2);
22902   ASSERT_EQ(*Style2, getNoStyle());
22903 
22904   // Test 2.3: format if config is found with no based style while fallback is
22905   // 'none'.
22906   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
22907                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
22908   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
22909   ASSERT_TRUE((bool)Style2);
22910   ASSERT_EQ(*Style2, getLLVMStyle());
22911 
22912   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
22913   Style2 = getStyle("{}", "a.h", "none", "", &FS);
22914   ASSERT_TRUE((bool)Style2);
22915   ASSERT_EQ(*Style2, getLLVMStyle());
22916 
22917   // Test 3: format file in parent directory.
22918   ASSERT_TRUE(
22919       FS.addFile("/c/.clang-format", 0,
22920                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
22921   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
22922                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22923   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
22924   ASSERT_TRUE((bool)Style3);
22925   ASSERT_EQ(*Style3, getGoogleStyle());
22926 
22927   // Test 4: error on invalid fallback style
22928   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
22929   ASSERT_FALSE((bool)Style4);
22930   llvm::consumeError(Style4.takeError());
22931 
22932   // Test 5: error on invalid yaml on command line
22933   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
22934   ASSERT_FALSE((bool)Style5);
22935   llvm::consumeError(Style5.takeError());
22936 
22937   // Test 6: error on invalid style
22938   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
22939   ASSERT_FALSE((bool)Style6);
22940   llvm::consumeError(Style6.takeError());
22941 
22942   // Test 7: found config file, error on parsing it
22943   ASSERT_TRUE(
22944       FS.addFile("/d/.clang-format", 0,
22945                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
22946                                                   "InvalidKey: InvalidValue")));
22947   ASSERT_TRUE(
22948       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
22949   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
22950   ASSERT_FALSE((bool)Style7a);
22951   llvm::consumeError(Style7a.takeError());
22952 
22953   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
22954   ASSERT_TRUE((bool)Style7b);
22955 
22956   // Test 8: inferred per-language defaults apply.
22957   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
22958   ASSERT_TRUE((bool)StyleTd);
22959   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
22960 
22961   // Test 9.1.1: overwriting a file style, when no parent file exists with no
22962   // fallback style.
22963   ASSERT_TRUE(FS.addFile(
22964       "/e/sub/.clang-format", 0,
22965       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
22966                                        "ColumnLimit: 20")));
22967   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
22968                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22969   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
22970   ASSERT_TRUE(static_cast<bool>(Style9));
22971   ASSERT_EQ(*Style9, [] {
22972     auto Style = getNoStyle();
22973     Style.ColumnLimit = 20;
22974     return Style;
22975   }());
22976 
22977   // Test 9.1.2: propagate more than one level with no parent file.
22978   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
22979                          llvm::MemoryBuffer::getMemBuffer("int i;")));
22980   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
22981                          llvm::MemoryBuffer::getMemBuffer(
22982                              "BasedOnStyle: InheritParentConfig\n"
22983                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
22984   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
22985 
22986   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
22987   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
22988   ASSERT_TRUE(static_cast<bool>(Style9));
22989   ASSERT_EQ(*Style9, [&NonDefaultWhiteSpaceMacros] {
22990     auto Style = getNoStyle();
22991     Style.ColumnLimit = 20;
22992     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
22993     return Style;
22994   }());
22995 
22996   // Test 9.2: with LLVM fallback style
22997   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
22998   ASSERT_TRUE(static_cast<bool>(Style9));
22999   ASSERT_EQ(*Style9, [] {
23000     auto Style = getLLVMStyle();
23001     Style.ColumnLimit = 20;
23002     return Style;
23003   }());
23004 
23005   // Test 9.3: with a parent file
23006   ASSERT_TRUE(
23007       FS.addFile("/e/.clang-format", 0,
23008                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
23009                                                   "UseTab: Always")));
23010   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
23011   ASSERT_TRUE(static_cast<bool>(Style9));
23012   ASSERT_EQ(*Style9, [] {
23013     auto Style = getGoogleStyle();
23014     Style.ColumnLimit = 20;
23015     Style.UseTab = FormatStyle::UT_Always;
23016     return Style;
23017   }());
23018 
23019   // Test 9.4: propagate more than one level with a parent file.
23020   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
23021     auto Style = getGoogleStyle();
23022     Style.ColumnLimit = 20;
23023     Style.UseTab = FormatStyle::UT_Always;
23024     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
23025     return Style;
23026   }();
23027 
23028   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
23029   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
23030   ASSERT_TRUE(static_cast<bool>(Style9));
23031   ASSERT_EQ(*Style9, SubSubStyle);
23032 
23033   // Test 9.5: use InheritParentConfig as style name
23034   Style9 =
23035       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
23036   ASSERT_TRUE(static_cast<bool>(Style9));
23037   ASSERT_EQ(*Style9, SubSubStyle);
23038 
23039   // Test 9.6: use command line style with inheritance
23040   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
23041                     "none", "", &FS);
23042   ASSERT_TRUE(static_cast<bool>(Style9));
23043   ASSERT_EQ(*Style9, SubSubStyle);
23044 
23045   // Test 9.7: use command line style with inheritance and own config
23046   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
23047                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
23048                     "/e/sub/code.cpp", "none", "", &FS);
23049   ASSERT_TRUE(static_cast<bool>(Style9));
23050   ASSERT_EQ(*Style9, SubSubStyle);
23051 
23052   // Test 9.8: use inheritance from a file without BasedOnStyle
23053   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
23054                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
23055   ASSERT_TRUE(
23056       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
23057                  llvm::MemoryBuffer::getMemBuffer(
23058                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
23059   // Make sure we do not use the fallback style
23060   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
23061   ASSERT_TRUE(static_cast<bool>(Style9));
23062   ASSERT_EQ(*Style9, [] {
23063     auto Style = getLLVMStyle();
23064     Style.ColumnLimit = 123;
23065     return Style;
23066   }());
23067 
23068   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
23069   ASSERT_TRUE(static_cast<bool>(Style9));
23070   ASSERT_EQ(*Style9, [] {
23071     auto Style = getLLVMStyle();
23072     Style.ColumnLimit = 123;
23073     Style.IndentWidth = 7;
23074     return Style;
23075   }());
23076 
23077   // Test 9.9: use inheritance from a specific config file.
23078   Style9 = getStyle("file:/e/sub/sub/.clang-format", "/e/sub/sub/code.cpp",
23079                     "none", "", &FS);
23080   ASSERT_TRUE(static_cast<bool>(Style9));
23081   ASSERT_EQ(*Style9, SubSubStyle);
23082 }
23083 
TEST(FormatStyle,GetStyleOfSpecificFile)23084 TEST(FormatStyle, GetStyleOfSpecificFile) {
23085   llvm::vfs::InMemoryFileSystem FS;
23086   // Specify absolute path to a format file in a parent directory.
23087   ASSERT_TRUE(
23088       FS.addFile("/e/.clang-format", 0,
23089                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
23090   ASSERT_TRUE(
23091       FS.addFile("/e/explicit.clang-format", 0,
23092                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
23093   ASSERT_TRUE(FS.addFile("/e/sub/sub/sub/test.cpp", 0,
23094                          llvm::MemoryBuffer::getMemBuffer("int i;")));
23095   auto Style = getStyle("file:/e/explicit.clang-format",
23096                         "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
23097   ASSERT_TRUE(static_cast<bool>(Style));
23098   ASSERT_EQ(*Style, getGoogleStyle());
23099 
23100   // Specify relative path to a format file.
23101   ASSERT_TRUE(
23102       FS.addFile("../../e/explicit.clang-format", 0,
23103                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
23104   Style = getStyle("file:../../e/explicit.clang-format",
23105                    "/e/sub/sub/sub/test.cpp", "LLVM", "", &FS);
23106   ASSERT_TRUE(static_cast<bool>(Style));
23107   ASSERT_EQ(*Style, getGoogleStyle());
23108 
23109   // Specify path to a format file that does not exist.
23110   Style = getStyle("file:/e/missing.clang-format", "/e/sub/sub/sub/test.cpp",
23111                    "LLVM", "", &FS);
23112   ASSERT_FALSE(static_cast<bool>(Style));
23113   llvm::consumeError(Style.takeError());
23114 
23115   // Specify path to a file on the filesystem.
23116   SmallString<128> FormatFilePath;
23117   std::error_code ECF = llvm::sys::fs::createTemporaryFile(
23118       "FormatFileTest", "tpl", FormatFilePath);
23119   EXPECT_FALSE((bool)ECF);
23120   llvm::raw_fd_ostream FormatFileTest(FormatFilePath, ECF);
23121   EXPECT_FALSE((bool)ECF);
23122   FormatFileTest << "BasedOnStyle: Google\n";
23123   FormatFileTest.close();
23124 
23125   SmallString<128> TestFilePath;
23126   std::error_code ECT =
23127       llvm::sys::fs::createTemporaryFile("CodeFileTest", "cc", TestFilePath);
23128   EXPECT_FALSE((bool)ECT);
23129   llvm::raw_fd_ostream CodeFileTest(TestFilePath, ECT);
23130   CodeFileTest << "int i;\n";
23131   CodeFileTest.close();
23132 
23133   std::string format_file_arg = std::string("file:") + FormatFilePath.c_str();
23134   Style = getStyle(format_file_arg, TestFilePath, "LLVM", "", nullptr);
23135 
23136   llvm::sys::fs::remove(FormatFilePath.c_str());
23137   llvm::sys::fs::remove(TestFilePath.c_str());
23138   ASSERT_TRUE(static_cast<bool>(Style));
23139   ASSERT_EQ(*Style, getGoogleStyle());
23140 }
23141 
TEST_F(ReplacementTest,FormatCodeAfterReplacements)23142 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
23143   // Column limit is 20.
23144   std::string Code = "Type *a =\n"
23145                      "    new Type();\n"
23146                      "g(iiiii, 0, jjjjj,\n"
23147                      "  0, kkkkk, 0, mm);\n"
23148                      "int  bad     = format   ;";
23149   std::string Expected = "auto a = new Type();\n"
23150                          "g(iiiii, nullptr,\n"
23151                          "  jjjjj, nullptr,\n"
23152                          "  kkkkk, nullptr,\n"
23153                          "  mm);\n"
23154                          "int  bad     = format   ;";
23155   FileID ID = Context.createInMemoryFile("format.cpp", Code);
23156   tooling::Replacements Replaces = toReplacements(
23157       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
23158                             "auto "),
23159        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
23160                             "nullptr"),
23161        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
23162                             "nullptr"),
23163        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
23164                             "nullptr")});
23165 
23166   FormatStyle Style = getLLVMStyle();
23167   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
23168   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
23169   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
23170       << llvm::toString(FormattedReplaces.takeError()) << "\n";
23171   auto Result = applyAllReplacements(Code, *FormattedReplaces);
23172   EXPECT_TRUE(static_cast<bool>(Result));
23173   EXPECT_EQ(Expected, *Result);
23174 }
23175 
TEST_F(ReplacementTest,SortIncludesAfterReplacement)23176 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
23177   std::string Code = "#include \"a.h\"\n"
23178                      "#include \"c.h\"\n"
23179                      "\n"
23180                      "int main() {\n"
23181                      "  return 0;\n"
23182                      "}";
23183   std::string Expected = "#include \"a.h\"\n"
23184                          "#include \"b.h\"\n"
23185                          "#include \"c.h\"\n"
23186                          "\n"
23187                          "int main() {\n"
23188                          "  return 0;\n"
23189                          "}";
23190   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
23191   tooling::Replacements Replaces = toReplacements(
23192       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
23193                             "#include \"b.h\"\n")});
23194 
23195   FormatStyle Style = getLLVMStyle();
23196   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
23197   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
23198   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
23199       << llvm::toString(FormattedReplaces.takeError()) << "\n";
23200   auto Result = applyAllReplacements(Code, *FormattedReplaces);
23201   EXPECT_TRUE(static_cast<bool>(Result));
23202   EXPECT_EQ(Expected, *Result);
23203 }
23204 
TEST_F(FormatTest,FormatSortsUsingDeclarations)23205 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
23206   EXPECT_EQ("using std::cin;\n"
23207             "using std::cout;",
23208             format("using std::cout;\n"
23209                    "using std::cin;",
23210                    getGoogleStyle()));
23211 }
23212 
TEST_F(FormatTest,UTF8CharacterLiteralCpp03)23213 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
23214   FormatStyle Style = getLLVMStyle();
23215   Style.Standard = FormatStyle::LS_Cpp03;
23216   // cpp03 recognize this string as identifier u8 and literal character 'a'
23217   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
23218 }
23219 
TEST_F(FormatTest,UTF8CharacterLiteralCpp11)23220 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
23221   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
23222   // all modes, including C++11, C++14 and C++17
23223   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
23224 }
23225 
TEST_F(FormatTest,DoNotFormatLikelyXml)23226 TEST_F(FormatTest, DoNotFormatLikelyXml) {
23227   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
23228   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
23229 }
23230 
TEST_F(FormatTest,StructuredBindings)23231 TEST_F(FormatTest, StructuredBindings) {
23232   // Structured bindings is a C++17 feature.
23233   // all modes, including C++11, C++14 and C++17
23234   verifyFormat("auto [a, b] = f();");
23235   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
23236   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
23237   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
23238   EXPECT_EQ("auto const volatile [a, b] = f();",
23239             format("auto  const   volatile[a, b] = f();"));
23240   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
23241   EXPECT_EQ("auto &[a, b, c] = f();",
23242             format("auto   &[  a  ,  b,c   ] = f();"));
23243   EXPECT_EQ("auto &&[a, b, c] = f();",
23244             format("auto   &&[  a  ,  b,c   ] = f();"));
23245   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
23246   EXPECT_EQ("auto const volatile &&[a, b] = f();",
23247             format("auto  const  volatile  &&[a, b] = f();"));
23248   EXPECT_EQ("auto const &&[a, b] = f();",
23249             format("auto  const   &&  [a, b] = f();"));
23250   EXPECT_EQ("const auto &[a, b] = f();",
23251             format("const  auto  &  [a, b] = f();"));
23252   EXPECT_EQ("const auto volatile &&[a, b] = f();",
23253             format("const  auto   volatile  &&[a, b] = f();"));
23254   EXPECT_EQ("volatile const auto &&[a, b] = f();",
23255             format("volatile  const  auto   &&[a, b] = f();"));
23256   EXPECT_EQ("const auto &&[a, b] = f();",
23257             format("const  auto  &&  [a, b] = f();"));
23258 
23259   // Make sure we don't mistake structured bindings for lambdas.
23260   FormatStyle PointerMiddle = getLLVMStyle();
23261   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
23262   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
23263   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
23264   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
23265   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
23266   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
23267   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
23268   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
23269   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
23270   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
23271   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
23272   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
23273   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
23274 
23275   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
23276             format("for (const auto   &&   [a, b] : some_range) {\n}"));
23277   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
23278             format("for (const auto   &   [a, b] : some_range) {\n}"));
23279   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
23280             format("for (const auto[a, b] : some_range) {\n}"));
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 &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
23284   EXPECT_EQ("auto const &[x, y](expr);",
23285             format("auto  const  &  [x,y]  (expr);"));
23286   EXPECT_EQ("auto const &&[x, y](expr);",
23287             format("auto  const  &&  [x,y]  (expr);"));
23288   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
23289   EXPECT_EQ("auto const &[x, y]{expr};",
23290             format("auto  const  &  [x,y]  {expr};"));
23291   EXPECT_EQ("auto const &&[x, y]{expr};",
23292             format("auto  const  &&  [x,y]  {expr};"));
23293 
23294   FormatStyle Spaces = getLLVMStyle();
23295   Spaces.SpacesInSquareBrackets = true;
23296   verifyFormat("auto [ a, b ] = f();", Spaces);
23297   verifyFormat("auto &&[ a, b ] = f();", Spaces);
23298   verifyFormat("auto &[ a, b ] = f();", Spaces);
23299   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
23300   verifyFormat("auto const &[ a, b ] = f();", Spaces);
23301 }
23302 
TEST_F(FormatTest,FileAndCode)23303 TEST_F(FormatTest, FileAndCode) {
23304   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
23305   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
23306   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
23307   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
23308   EXPECT_EQ(FormatStyle::LK_ObjC,
23309             guessLanguage("foo.h", "@interface Foo\n@end\n"));
23310   EXPECT_EQ(
23311       FormatStyle::LK_ObjC,
23312       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
23313   EXPECT_EQ(FormatStyle::LK_ObjC,
23314             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
23315   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
23316   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
23317   EXPECT_EQ(FormatStyle::LK_ObjC,
23318             guessLanguage("foo", "@interface Foo\n@end\n"));
23319   EXPECT_EQ(FormatStyle::LK_ObjC,
23320             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
23321   EXPECT_EQ(
23322       FormatStyle::LK_ObjC,
23323       guessLanguage("foo.h",
23324                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
23325   EXPECT_EQ(
23326       FormatStyle::LK_Cpp,
23327       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
23328   // Only one of the two preprocessor regions has ObjC-like code.
23329   EXPECT_EQ(FormatStyle::LK_ObjC,
23330             guessLanguage("foo.h", "#if A\n"
23331                                    "#define B() C\n"
23332                                    "#else\n"
23333                                    "#define B() [NSString a:@\"\"]\n"
23334                                    "#endif\n"));
23335 }
23336 
TEST_F(FormatTest,GuessLanguageWithCpp11AttributeSpecifiers)23337 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
23338   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
23339   EXPECT_EQ(FormatStyle::LK_ObjC,
23340             guessLanguage("foo.h", "array[[calculator getIndex]];"));
23341   EXPECT_EQ(FormatStyle::LK_Cpp,
23342             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
23343   EXPECT_EQ(
23344       FormatStyle::LK_Cpp,
23345       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
23346   EXPECT_EQ(FormatStyle::LK_ObjC,
23347             guessLanguage("foo.h", "[[noreturn foo] bar];"));
23348   EXPECT_EQ(FormatStyle::LK_Cpp,
23349             guessLanguage("foo.h", "[[clang::fallthrough]];"));
23350   EXPECT_EQ(FormatStyle::LK_ObjC,
23351             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
23352   EXPECT_EQ(FormatStyle::LK_Cpp,
23353             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
23354   EXPECT_EQ(FormatStyle::LK_Cpp,
23355             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
23356   EXPECT_EQ(FormatStyle::LK_ObjC,
23357             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
23358   EXPECT_EQ(FormatStyle::LK_Cpp,
23359             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
23360   EXPECT_EQ(
23361       FormatStyle::LK_Cpp,
23362       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
23363   EXPECT_EQ(
23364       FormatStyle::LK_Cpp,
23365       guessLanguage("foo.h",
23366                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
23367   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
23368 }
23369 
TEST_F(FormatTest,GuessLanguageWithCaret)23370 TEST_F(FormatTest, GuessLanguageWithCaret) {
23371   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
23372   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
23373   EXPECT_EQ(FormatStyle::LK_ObjC,
23374             guessLanguage("foo.h", "int(^)(char, float);"));
23375   EXPECT_EQ(FormatStyle::LK_ObjC,
23376             guessLanguage("foo.h", "int(^foo)(char, float);"));
23377   EXPECT_EQ(FormatStyle::LK_ObjC,
23378             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
23379   EXPECT_EQ(FormatStyle::LK_ObjC,
23380             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
23381   EXPECT_EQ(
23382       FormatStyle::LK_ObjC,
23383       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
23384 }
23385 
TEST_F(FormatTest,GuessLanguageWithPragmas)23386 TEST_F(FormatTest, GuessLanguageWithPragmas) {
23387   EXPECT_EQ(FormatStyle::LK_Cpp,
23388             guessLanguage("foo.h", "__pragma(warning(disable:))"));
23389   EXPECT_EQ(FormatStyle::LK_Cpp,
23390             guessLanguage("foo.h", "#pragma(warning(disable:))"));
23391   EXPECT_EQ(FormatStyle::LK_Cpp,
23392             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
23393 }
23394 
TEST_F(FormatTest,FormatsInlineAsmSymbolicNames)23395 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
23396   // ASM symbolic names are identifiers that must be surrounded by [] without
23397   // space in between:
23398   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
23399 
23400   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
23401   verifyFormat(R"(//
23402 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
23403 )");
23404 
23405   // A list of several ASM symbolic names.
23406   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
23407 
23408   // ASM symbolic names in inline ASM with inputs and outputs.
23409   verifyFormat(R"(//
23410 asm("cmoveq %1, %2, %[result]"
23411     : [result] "=r"(result)
23412     : "r"(test), "r"(new), "[result]"(old));
23413 )");
23414 
23415   // ASM symbolic names in inline ASM with no outputs.
23416   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
23417 }
23418 
TEST_F(FormatTest,GuessedLanguageWithInlineAsmClobbers)23419 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
23420   EXPECT_EQ(FormatStyle::LK_Cpp,
23421             guessLanguage("foo.h", "void f() {\n"
23422                                    "  asm (\"mov %[e], %[d]\"\n"
23423                                    "     : [d] \"=rm\" (d)\n"
23424                                    "       [e] \"rm\" (*e));\n"
23425                                    "}"));
23426   EXPECT_EQ(FormatStyle::LK_Cpp,
23427             guessLanguage("foo.h", "void f() {\n"
23428                                    "  _asm (\"mov %[e], %[d]\"\n"
23429                                    "     : [d] \"=rm\" (d)\n"
23430                                    "       [e] \"rm\" (*e));\n"
23431                                    "}"));
23432   EXPECT_EQ(FormatStyle::LK_Cpp,
23433             guessLanguage("foo.h", "void f() {\n"
23434                                    "  __asm (\"mov %[e], %[d]\"\n"
23435                                    "     : [d] \"=rm\" (d)\n"
23436                                    "       [e] \"rm\" (*e));\n"
23437                                    "}"));
23438   EXPECT_EQ(FormatStyle::LK_Cpp,
23439             guessLanguage("foo.h", "void f() {\n"
23440                                    "  __asm__ (\"mov %[e], %[d]\"\n"
23441                                    "     : [d] \"=rm\" (d)\n"
23442                                    "       [e] \"rm\" (*e));\n"
23443                                    "}"));
23444   EXPECT_EQ(FormatStyle::LK_Cpp,
23445             guessLanguage("foo.h", "void f() {\n"
23446                                    "  asm (\"mov %[e], %[d]\"\n"
23447                                    "     : [d] \"=rm\" (d),\n"
23448                                    "       [e] \"rm\" (*e));\n"
23449                                    "}"));
23450   EXPECT_EQ(FormatStyle::LK_Cpp,
23451             guessLanguage("foo.h", "void f() {\n"
23452                                    "  asm volatile (\"mov %[e], %[d]\"\n"
23453                                    "     : [d] \"=rm\" (d)\n"
23454                                    "       [e] \"rm\" (*e));\n"
23455                                    "}"));
23456 }
23457 
TEST_F(FormatTest,GuessLanguageWithChildLines)23458 TEST_F(FormatTest, GuessLanguageWithChildLines) {
23459   EXPECT_EQ(FormatStyle::LK_Cpp,
23460             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
23461   EXPECT_EQ(FormatStyle::LK_ObjC,
23462             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
23463   EXPECT_EQ(
23464       FormatStyle::LK_Cpp,
23465       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
23466   EXPECT_EQ(
23467       FormatStyle::LK_ObjC,
23468       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
23469 }
23470 
TEST_F(FormatTest,TypenameMacros)23471 TEST_F(FormatTest, TypenameMacros) {
23472   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
23473 
23474   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
23475   FormatStyle Google = getGoogleStyleWithColumns(0);
23476   Google.TypenameMacros = TypenameMacros;
23477   verifyFormat("struct foo {\n"
23478                "  int bar;\n"
23479                "  TAILQ_ENTRY(a) bleh;\n"
23480                "};",
23481                Google);
23482 
23483   FormatStyle Macros = getLLVMStyle();
23484   Macros.TypenameMacros = TypenameMacros;
23485 
23486   verifyFormat("STACK_OF(int) a;", Macros);
23487   verifyFormat("STACK_OF(int) *a;", Macros);
23488   verifyFormat("STACK_OF(int const *) *a;", Macros);
23489   verifyFormat("STACK_OF(int *const) *a;", Macros);
23490   verifyFormat("STACK_OF(int, string) a;", Macros);
23491   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
23492   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
23493   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
23494   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
23495   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
23496   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
23497 
23498   Macros.PointerAlignment = FormatStyle::PAS_Left;
23499   verifyFormat("STACK_OF(int)* a;", Macros);
23500   verifyFormat("STACK_OF(int*)* a;", Macros);
23501   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
23502   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
23503   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
23504 }
23505 
TEST_F(FormatTest,AtomicQualifier)23506 TEST_F(FormatTest, AtomicQualifier) {
23507   // Check that we treate _Atomic as a type and not a function call
23508   FormatStyle Google = getGoogleStyleWithColumns(0);
23509   verifyFormat("struct foo {\n"
23510                "  int a1;\n"
23511                "  _Atomic(a) a2;\n"
23512                "  _Atomic(_Atomic(int) *const) a3;\n"
23513                "};",
23514                Google);
23515   verifyFormat("_Atomic(uint64_t) a;");
23516   verifyFormat("_Atomic(uint64_t) *a;");
23517   verifyFormat("_Atomic(uint64_t const *) *a;");
23518   verifyFormat("_Atomic(uint64_t *const) *a;");
23519   verifyFormat("_Atomic(const uint64_t *) *a;");
23520   verifyFormat("_Atomic(uint64_t) a;");
23521   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
23522   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
23523   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
23524   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
23525 
23526   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
23527   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
23528   FormatStyle Style = getLLVMStyle();
23529   Style.PointerAlignment = FormatStyle::PAS_Left;
23530   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
23531   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
23532   verifyFormat("_Atomic(int)* a;", Style);
23533   verifyFormat("_Atomic(int*)* a;", Style);
23534   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
23535 
23536   Style.SpacesInCStyleCastParentheses = true;
23537   Style.SpacesInParentheses = false;
23538   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
23539   Style.SpacesInCStyleCastParentheses = false;
23540   Style.SpacesInParentheses = true;
23541   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
23542   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
23543 }
23544 
TEST_F(FormatTest,AmbersandInLamda)23545 TEST_F(FormatTest, AmbersandInLamda) {
23546   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
23547   FormatStyle AlignStyle = getLLVMStyle();
23548   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
23549   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23550   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
23551   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
23552 }
23553 
TEST_F(FormatTest,SpacesInConditionalStatement)23554 TEST_F(FormatTest, SpacesInConditionalStatement) {
23555   FormatStyle Spaces = getLLVMStyle();
23556   Spaces.IfMacros.clear();
23557   Spaces.IfMacros.push_back("MYIF");
23558   Spaces.SpacesInConditionalStatement = true;
23559   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
23560   verifyFormat("if ( !a )\n  return;", Spaces);
23561   verifyFormat("if ( a )\n  return;", Spaces);
23562   verifyFormat("if constexpr ( a )\n  return;", Spaces);
23563   verifyFormat("MYIF ( a )\n  return;", Spaces);
23564   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
23565   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
23566   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
23567   verifyFormat("while ( a )\n  return;", Spaces);
23568   verifyFormat("while ( (a && b) )\n  return;", Spaces);
23569   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
23570   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
23571   // Check that space on the left of "::" is inserted as expected at beginning
23572   // of condition.
23573   verifyFormat("while ( ::func() )\n  return;", Spaces);
23574 
23575   // Check impact of ControlStatementsExceptControlMacros is honored.
23576   Spaces.SpaceBeforeParens =
23577       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
23578   verifyFormat("MYIF( a )\n  return;", Spaces);
23579   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
23580   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
23581 }
23582 
TEST_F(FormatTest,AlternativeOperators)23583 TEST_F(FormatTest, AlternativeOperators) {
23584   // Test case for ensuring alternate operators are not
23585   // combined with their right most neighbour.
23586   verifyFormat("int a and b;");
23587   verifyFormat("int a and_eq b;");
23588   verifyFormat("int a bitand b;");
23589   verifyFormat("int a bitor b;");
23590   verifyFormat("int a compl b;");
23591   verifyFormat("int a not b;");
23592   verifyFormat("int a not_eq b;");
23593   verifyFormat("int a or b;");
23594   verifyFormat("int a xor b;");
23595   verifyFormat("int a xor_eq b;");
23596   verifyFormat("return this not_eq bitand other;");
23597   verifyFormat("bool operator not_eq(const X bitand other)");
23598 
23599   verifyFormat("int a and 5;");
23600   verifyFormat("int a and_eq 5;");
23601   verifyFormat("int a bitand 5;");
23602   verifyFormat("int a bitor 5;");
23603   verifyFormat("int a compl 5;");
23604   verifyFormat("int a not 5;");
23605   verifyFormat("int a not_eq 5;");
23606   verifyFormat("int a or 5;");
23607   verifyFormat("int a xor 5;");
23608   verifyFormat("int a xor_eq 5;");
23609 
23610   verifyFormat("int a compl(5);");
23611   verifyFormat("int a not(5);");
23612 
23613   /* FIXME handle alternate tokens
23614    * https://en.cppreference.com/w/cpp/language/operator_alternative
23615   // alternative tokens
23616   verifyFormat("compl foo();");     //  ~foo();
23617   verifyFormat("foo() <%%>;");      // foo();
23618   verifyFormat("void foo() <%%>;"); // void foo(){}
23619   verifyFormat("int a <:1:>;");     // int a[1];[
23620   verifyFormat("%:define ABC abc"); // #define ABC abc
23621   verifyFormat("%:%:");             // ##
23622   */
23623 }
23624 
TEST_F(FormatTest,STLWhileNotDefineChed)23625 TEST_F(FormatTest, STLWhileNotDefineChed) {
23626   verifyFormat("#if defined(while)\n"
23627                "#define while EMIT WARNING C4005\n"
23628                "#endif // while");
23629 }
23630 
TEST_F(FormatTest,OperatorSpacing)23631 TEST_F(FormatTest, OperatorSpacing) {
23632   FormatStyle Style = getLLVMStyle();
23633   Style.PointerAlignment = FormatStyle::PAS_Right;
23634   verifyFormat("Foo::operator*();", Style);
23635   verifyFormat("Foo::operator void *();", Style);
23636   verifyFormat("Foo::operator void **();", Style);
23637   verifyFormat("Foo::operator void *&();", Style);
23638   verifyFormat("Foo::operator void *&&();", 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 const *&&();", Style);
23643   verifyFormat("Foo::operator()(void *);", Style);
23644   verifyFormat("Foo::operator*(void *);", Style);
23645   verifyFormat("Foo::operator*();", Style);
23646   verifyFormat("Foo::operator**();", Style);
23647   verifyFormat("Foo::operator&();", Style);
23648   verifyFormat("Foo::operator<int> *();", Style);
23649   verifyFormat("Foo::operator<Foo> *();", Style);
23650   verifyFormat("Foo::operator<int> **();", Style);
23651   verifyFormat("Foo::operator<Foo> **();", Style);
23652   verifyFormat("Foo::operator<int> &();", Style);
23653   verifyFormat("Foo::operator<Foo> &();", Style);
23654   verifyFormat("Foo::operator<int> &&();", Style);
23655   verifyFormat("Foo::operator<Foo> &&();", Style);
23656   verifyFormat("Foo::operator<int> *&();", Style);
23657   verifyFormat("Foo::operator<Foo> *&();", Style);
23658   verifyFormat("Foo::operator<int> *&&();", Style);
23659   verifyFormat("Foo::operator<Foo> *&&();", Style);
23660   verifyFormat("operator*(int (*)(), class Foo);", Style);
23661 
23662   verifyFormat("Foo::operator&();", Style);
23663   verifyFormat("Foo::operator void &();", Style);
23664   verifyFormat("Foo::operator void const &();", Style);
23665   verifyFormat("Foo::operator()(void &);", Style);
23666   verifyFormat("Foo::operator&(void &);", Style);
23667   verifyFormat("Foo::operator&();", Style);
23668   verifyFormat("operator&(int (&)(), class Foo);", Style);
23669   verifyFormat("operator&&(int (&)(), class Foo);", Style);
23670 
23671   verifyFormat("Foo::operator&&();", Style);
23672   verifyFormat("Foo::operator**();", Style);
23673   verifyFormat("Foo::operator void &&();", Style);
23674   verifyFormat("Foo::operator void const &&();", Style);
23675   verifyFormat("Foo::operator()(void &&);", Style);
23676   verifyFormat("Foo::operator&&(void &&);", Style);
23677   verifyFormat("Foo::operator&&();", Style);
23678   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23679   verifyFormat("operator const nsTArrayRight<E> &()", Style);
23680   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
23681                Style);
23682   verifyFormat("operator void **()", 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   verifyFormat("operator const FooRight<Object> *&&()", Style);
23688 
23689   Style.PointerAlignment = FormatStyle::PAS_Left;
23690   verifyFormat("Foo::operator*();", Style);
23691   verifyFormat("Foo::operator**();", Style);
23692   verifyFormat("Foo::operator void*();", Style);
23693   verifyFormat("Foo::operator void**();", Style);
23694   verifyFormat("Foo::operator void*&();", Style);
23695   verifyFormat("Foo::operator void*&&();", 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 void const*&&();", Style);
23700   verifyFormat("Foo::operator/*comment*/ void*();", Style);
23701   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
23702   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
23703   verifyFormat("Foo::operator()(void*);", Style);
23704   verifyFormat("Foo::operator*(void*);", Style);
23705   verifyFormat("Foo::operator*();", Style);
23706   verifyFormat("Foo::operator<int>*();", Style);
23707   verifyFormat("Foo::operator<Foo>*();", Style);
23708   verifyFormat("Foo::operator<int>**();", Style);
23709   verifyFormat("Foo::operator<Foo>**();", Style);
23710   verifyFormat("Foo::operator<Foo>*&();", Style);
23711   verifyFormat("Foo::operator<int>&();", Style);
23712   verifyFormat("Foo::operator<Foo>&();", Style);
23713   verifyFormat("Foo::operator<int>&&();", Style);
23714   verifyFormat("Foo::operator<Foo>&&();", Style);
23715   verifyFormat("Foo::operator<int>*&();", Style);
23716   verifyFormat("Foo::operator<Foo>*&();", Style);
23717   verifyFormat("operator*(int (*)(), class Foo);", Style);
23718 
23719   verifyFormat("Foo::operator&();", Style);
23720   verifyFormat("Foo::operator void&();", Style);
23721   verifyFormat("Foo::operator void const&();", Style);
23722   verifyFormat("Foo::operator/*comment*/ void&();", Style);
23723   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
23724   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
23725   verifyFormat("Foo::operator()(void&);", Style);
23726   verifyFormat("Foo::operator&(void&);", Style);
23727   verifyFormat("Foo::operator&();", Style);
23728   verifyFormat("operator&(int (&)(), class Foo);", Style);
23729   verifyFormat("operator&(int (&&)(), class Foo);", Style);
23730   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23731 
23732   verifyFormat("Foo::operator&&();", Style);
23733   verifyFormat("Foo::operator void&&();", Style);
23734   verifyFormat("Foo::operator void const&&();", Style);
23735   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
23736   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
23737   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
23738   verifyFormat("Foo::operator()(void&&);", Style);
23739   verifyFormat("Foo::operator&&(void&&);", Style);
23740   verifyFormat("Foo::operator&&();", Style);
23741   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23742   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
23743   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
23744                Style);
23745   verifyFormat("operator void**()", 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   verifyFormat("operator const FooLeft<Object>*&&()", Style);
23751 
23752   // PR45107
23753   verifyFormat("operator Vector<String>&();", Style);
23754   verifyFormat("operator const Vector<String>&();", Style);
23755   verifyFormat("operator foo::Bar*();", Style);
23756   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
23757   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
23758                Style);
23759 
23760   Style.PointerAlignment = FormatStyle::PAS_Middle;
23761   verifyFormat("Foo::operator*();", Style);
23762   verifyFormat("Foo::operator void *();", Style);
23763   verifyFormat("Foo::operator()(void *);", Style);
23764   verifyFormat("Foo::operator*(void *);", Style);
23765   verifyFormat("Foo::operator*();", Style);
23766   verifyFormat("operator*(int (*)(), class Foo);", Style);
23767 
23768   verifyFormat("Foo::operator&();", Style);
23769   verifyFormat("Foo::operator void &();", Style);
23770   verifyFormat("Foo::operator void const &();", Style);
23771   verifyFormat("Foo::operator()(void &);", Style);
23772   verifyFormat("Foo::operator&(void &);", Style);
23773   verifyFormat("Foo::operator&();", Style);
23774   verifyFormat("operator&(int (&)(), class Foo);", Style);
23775 
23776   verifyFormat("Foo::operator&&();", Style);
23777   verifyFormat("Foo::operator void &&();", Style);
23778   verifyFormat("Foo::operator void const &&();", Style);
23779   verifyFormat("Foo::operator()(void &&);", Style);
23780   verifyFormat("Foo::operator&&(void &&);", Style);
23781   verifyFormat("Foo::operator&&();", Style);
23782   verifyFormat("operator&&(int (&&)(), class Foo);", Style);
23783 }
23784 
TEST_F(FormatTest,OperatorPassedAsAFunctionPtr)23785 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
23786   FormatStyle Style = getLLVMStyle();
23787   // PR46157
23788   verifyFormat("foo(operator+, -42);", Style);
23789   verifyFormat("foo(operator++, -42);", Style);
23790   verifyFormat("foo(operator--, -42);", Style);
23791   verifyFormat("foo(-42, operator--);", Style);
23792   verifyFormat("foo(-42, operator, );", Style);
23793   verifyFormat("foo(operator, , -42);", Style);
23794 }
23795 
TEST_F(FormatTest,WhitespaceSensitiveMacros)23796 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
23797   FormatStyle Style = getLLVMStyle();
23798   Style.WhitespaceSensitiveMacros.push_back("FOO");
23799 
23800   // Don't use the helpers here, since 'mess up' will change the whitespace
23801   // and these are all whitespace sensitive by definition
23802   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
23803             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
23804   EXPECT_EQ(
23805       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
23806       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
23807   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
23808             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
23809   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
23810             "       Still=Intentional);",
23811             format("FOO(String-ized&Messy+But,: :\n"
23812                    "       Still=Intentional);",
23813                    Style));
23814   Style.AlignConsecutiveAssignments.Enabled = true;
23815   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
23816             "       Still=Intentional);",
23817             format("FOO(String-ized=&Messy+But,: :\n"
23818                    "       Still=Intentional);",
23819                    Style));
23820 
23821   Style.ColumnLimit = 21;
23822   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
23823             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
23824 }
23825 
TEST_F(FormatTest,VeryLongNamespaceCommentSplit)23826 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
23827   // These tests are not in NamespaceEndCommentsFixerTest because that doesn't
23828   // test its interaction with line wrapping
23829   FormatStyle Style = getLLVMStyleWithColumns(80);
23830   verifyFormat("namespace {\n"
23831                "int i;\n"
23832                "int j;\n"
23833                "} // namespace",
23834                Style);
23835 
23836   verifyFormat("namespace AAA {\n"
23837                "int i;\n"
23838                "int j;\n"
23839                "} // namespace AAA",
23840                Style);
23841 
23842   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
23843             "int i;\n"
23844             "int j;\n"
23845             "} // namespace Averyveryveryverylongnamespace",
23846             format("namespace Averyveryveryverylongnamespace {\n"
23847                    "int i;\n"
23848                    "int j;\n"
23849                    "}",
23850                    Style));
23851 
23852   EXPECT_EQ(
23853       "namespace "
23854       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23855       "    went::mad::now {\n"
23856       "int i;\n"
23857       "int j;\n"
23858       "} // namespace\n"
23859       "  // "
23860       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23861       "went::mad::now",
23862       format("namespace "
23863              "would::it::save::you::a::lot::of::time::if_::i::"
23864              "just::gave::up::and_::went::mad::now {\n"
23865              "int i;\n"
23866              "int j;\n"
23867              "}",
23868              Style));
23869 
23870   // This used to duplicate the comment again and again on subsequent runs
23871   EXPECT_EQ(
23872       "namespace "
23873       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
23874       "    went::mad::now {\n"
23875       "int i;\n"
23876       "int j;\n"
23877       "} // namespace\n"
23878       "  // "
23879       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
23880       "went::mad::now",
23881       format("namespace "
23882              "would::it::save::you::a::lot::of::time::if_::i::"
23883              "just::gave::up::and_::went::mad::now {\n"
23884              "int i;\n"
23885              "int j;\n"
23886              "} // namespace\n"
23887              "  // "
23888              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
23889              "and_::went::mad::now",
23890              Style));
23891 }
23892 
TEST_F(FormatTest,LikelyUnlikely)23893 TEST_F(FormatTest, LikelyUnlikely) {
23894   FormatStyle Style = getLLVMStyle();
23895 
23896   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23897                "  return 29;\n"
23898                "}",
23899                Style);
23900 
23901   verifyFormat("if (argc > 5) [[likely]] {\n"
23902                "  return 29;\n"
23903                "}",
23904                Style);
23905 
23906   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23907                "  return 29;\n"
23908                "} else [[likely]] {\n"
23909                "  return 42;\n"
23910                "}\n",
23911                Style);
23912 
23913   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23914                "  return 29;\n"
23915                "} else if (argc > 10) [[likely]] {\n"
23916                "  return 99;\n"
23917                "} else {\n"
23918                "  return 42;\n"
23919                "}\n",
23920                Style);
23921 
23922   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
23923                "  return 29;\n"
23924                "}",
23925                Style);
23926 
23927   verifyFormat("if (argc > 5) [[unlikely]]\n"
23928                "  return 29;\n",
23929                Style);
23930   verifyFormat("if (argc > 5) [[likely]]\n"
23931                "  return 29;\n",
23932                Style);
23933 
23934   verifyFormat("while (limit > 0) [[unlikely]] {\n"
23935                "  --limit;\n"
23936                "}",
23937                Style);
23938   verifyFormat("for (auto &limit : limits) [[likely]] {\n"
23939                "  --limit;\n"
23940                "}",
23941                Style);
23942 
23943   verifyFormat("for (auto &limit : limits) [[unlikely]]\n"
23944                "  --limit;",
23945                Style);
23946   verifyFormat("while (limit > 0) [[likely]]\n"
23947                "  --limit;",
23948                Style);
23949 
23950   Style.AttributeMacros.push_back("UNLIKELY");
23951   Style.AttributeMacros.push_back("LIKELY");
23952   verifyFormat("if (argc > 5) UNLIKELY\n"
23953                "  return 29;\n",
23954                Style);
23955 
23956   verifyFormat("if (argc > 5) UNLIKELY {\n"
23957                "  return 29;\n"
23958                "}",
23959                Style);
23960   verifyFormat("if (argc > 5) UNLIKELY {\n"
23961                "  return 29;\n"
23962                "} else [[likely]] {\n"
23963                "  return 42;\n"
23964                "}\n",
23965                Style);
23966   verifyFormat("if (argc > 5) UNLIKELY {\n"
23967                "  return 29;\n"
23968                "} else LIKELY {\n"
23969                "  return 42;\n"
23970                "}\n",
23971                Style);
23972   verifyFormat("if (argc > 5) [[unlikely]] {\n"
23973                "  return 29;\n"
23974                "} else LIKELY {\n"
23975                "  return 42;\n"
23976                "}\n",
23977                Style);
23978 
23979   verifyFormat("for (auto &limit : limits) UNLIKELY {\n"
23980                "  --limit;\n"
23981                "}",
23982                Style);
23983   verifyFormat("while (limit > 0) LIKELY {\n"
23984                "  --limit;\n"
23985                "}",
23986                Style);
23987 
23988   verifyFormat("while (limit > 0) UNLIKELY\n"
23989                "  --limit;",
23990                Style);
23991   verifyFormat("for (auto &limit : limits) LIKELY\n"
23992                "  --limit;",
23993                Style);
23994 }
23995 
TEST_F(FormatTest,PenaltyIndentedWhitespace)23996 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
23997   verifyFormat("Constructor()\n"
23998                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
23999                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
24000                "aaaaaaaaaaaaaaaaaat))");
24001   verifyFormat("Constructor()\n"
24002                "    : aaaaaaaaaaaaa(aaaaaa), "
24003                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
24004 
24005   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
24006   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
24007   verifyFormat("Constructor()\n"
24008                "    : aaaaaa(aaaaaa),\n"
24009                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
24010                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
24011                StyleWithWhitespacePenalty);
24012   verifyFormat("Constructor()\n"
24013                "    : aaaaaaaaaaaaa(aaaaaa), "
24014                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
24015                StyleWithWhitespacePenalty);
24016 }
24017 
TEST_F(FormatTest,LLVMDefaultStyle)24018 TEST_F(FormatTest, LLVMDefaultStyle) {
24019   FormatStyle Style = getLLVMStyle();
24020   verifyFormat("extern \"C\" {\n"
24021                "int foo();\n"
24022                "}",
24023                Style);
24024 }
TEST_F(FormatTest,GNUDefaultStyle)24025 TEST_F(FormatTest, GNUDefaultStyle) {
24026   FormatStyle Style = getGNUStyle();
24027   verifyFormat("extern \"C\"\n"
24028                "{\n"
24029                "  int foo ();\n"
24030                "}",
24031                Style);
24032 }
TEST_F(FormatTest,MozillaDefaultStyle)24033 TEST_F(FormatTest, MozillaDefaultStyle) {
24034   FormatStyle Style = getMozillaStyle();
24035   verifyFormat("extern \"C\"\n"
24036                "{\n"
24037                "  int foo();\n"
24038                "}",
24039                Style);
24040 }
TEST_F(FormatTest,GoogleDefaultStyle)24041 TEST_F(FormatTest, GoogleDefaultStyle) {
24042   FormatStyle Style = getGoogleStyle();
24043   verifyFormat("extern \"C\" {\n"
24044                "int foo();\n"
24045                "}",
24046                Style);
24047 }
TEST_F(FormatTest,ChromiumDefaultStyle)24048 TEST_F(FormatTest, ChromiumDefaultStyle) {
24049   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
24050   verifyFormat("extern \"C\" {\n"
24051                "int foo();\n"
24052                "}",
24053                Style);
24054 }
TEST_F(FormatTest,MicrosoftDefaultStyle)24055 TEST_F(FormatTest, MicrosoftDefaultStyle) {
24056   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
24057   verifyFormat("extern \"C\"\n"
24058                "{\n"
24059                "    int foo();\n"
24060                "}",
24061                Style);
24062 }
TEST_F(FormatTest,WebKitDefaultStyle)24063 TEST_F(FormatTest, WebKitDefaultStyle) {
24064   FormatStyle Style = getWebKitStyle();
24065   verifyFormat("extern \"C\" {\n"
24066                "int foo();\n"
24067                "}",
24068                Style);
24069 }
24070 
TEST_F(FormatTest,Concepts)24071 TEST_F(FormatTest, Concepts) {
24072   EXPECT_EQ(getLLVMStyle().BreakBeforeConceptDeclarations,
24073             FormatStyle::BBCDS_Always);
24074   verifyFormat("template <typename T>\n"
24075                "concept True = true;");
24076 
24077   verifyFormat("template <typename T>\n"
24078                "concept C = ((false || foo()) && C2<T>) ||\n"
24079                "            (std::trait<T>::value && Baz) || sizeof(T) >= 6;",
24080                getLLVMStyleWithColumns(60));
24081 
24082   verifyFormat("template <typename T>\n"
24083                "concept DelayedCheck = true && requires(T t) { t.bar(); } && "
24084                "sizeof(T) <= 8;");
24085 
24086   verifyFormat("template <typename T>\n"
24087                "concept DelayedCheck = true && requires(T t) {\n"
24088                "                                 t.bar();\n"
24089                "                                 t.baz();\n"
24090                "                               } && sizeof(T) <= 8;");
24091 
24092   verifyFormat("template <typename T>\n"
24093                "concept DelayedCheck = true && requires(T t) { // Comment\n"
24094                "                                 t.bar();\n"
24095                "                                 t.baz();\n"
24096                "                               } && sizeof(T) <= 8;");
24097 
24098   verifyFormat("template <typename T>\n"
24099                "concept DelayedCheck = false || requires(T t) { t.bar(); } && "
24100                "sizeof(T) <= 8;");
24101 
24102   verifyFormat("template <typename T>\n"
24103                "concept DelayedCheck = !!false || requires(T t) { t.bar(); } "
24104                "&& sizeof(T) <= 8;");
24105 
24106   verifyFormat(
24107       "template <typename T>\n"
24108       "concept DelayedCheck = static_cast<bool>(0) ||\n"
24109       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24110 
24111   verifyFormat("template <typename T>\n"
24112                "concept DelayedCheck = bool(0) || requires(T t) { t.bar(); } "
24113                "&& sizeof(T) <= 8;");
24114 
24115   verifyFormat(
24116       "template <typename T>\n"
24117       "concept DelayedCheck = (bool)(0) ||\n"
24118       "                       requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24119 
24120   verifyFormat("template <typename T>\n"
24121                "concept DelayedCheck = (bool)0 || requires(T t) { t.bar(); } "
24122                "&& sizeof(T) <= 8;");
24123 
24124   verifyFormat("template <typename T>\n"
24125                "concept Size = sizeof(T) >= 5 && requires(T t) { t.bar(); } && "
24126                "sizeof(T) <= 8;");
24127 
24128   verifyFormat("template <typename T>\n"
24129                "concept Size = 2 < 5 && 2 <= 5 && 8 >= 5 && 8 > 5 &&\n"
24130                "               requires(T t) {\n"
24131                "                 t.bar();\n"
24132                "                 t.baz();\n"
24133                "               } && sizeof(T) <= 8 && !(4 < 3);",
24134                getLLVMStyleWithColumns(60));
24135 
24136   verifyFormat("template <typename T>\n"
24137                "concept TrueOrNot = IsAlwaysTrue || IsNeverTrue;");
24138 
24139   verifyFormat("template <typename T>\n"
24140                "concept C = foo();");
24141 
24142   verifyFormat("template <typename T>\n"
24143                "concept C = foo(T());");
24144 
24145   verifyFormat("template <typename T>\n"
24146                "concept C = foo(T{});");
24147 
24148   verifyFormat("template <typename T>\n"
24149                "concept Size = V<sizeof(T)>::Value > 5;");
24150 
24151   verifyFormat("template <typename T>\n"
24152                "concept True = S<T>::Value;");
24153 
24154   verifyFormat(
24155       "template <typename T>\n"
24156       "concept C = []() { return true; }() && requires(T t) { t.bar(); } &&\n"
24157       "            sizeof(T) <= 8;");
24158 
24159   // FIXME: This is misformatted because the fake l paren starts at bool, not at
24160   // the lambda l square.
24161   verifyFormat("template <typename T>\n"
24162                "concept C = [] -> bool { return true; }() && requires(T t) { "
24163                "t.bar(); } &&\n"
24164                "                      sizeof(T) <= 8;");
24165 
24166   verifyFormat(
24167       "template <typename T>\n"
24168       "concept C = decltype([]() { return std::true_type{}; }())::value &&\n"
24169       "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24170 
24171   verifyFormat("template <typename T>\n"
24172                "concept C = decltype([]() { return std::true_type{}; "
24173                "}())::value && requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24174                getLLVMStyleWithColumns(120));
24175 
24176   verifyFormat("template <typename T>\n"
24177                "concept C = decltype([]() -> std::true_type { return {}; "
24178                "}())::value &&\n"
24179                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;");
24180 
24181   verifyFormat("template <typename T>\n"
24182                "concept C = true;\n"
24183                "Foo Bar;");
24184 
24185   verifyFormat("template <typename T>\n"
24186                "concept Hashable = requires(T a) {\n"
24187                "                     { std::hash<T>{}(a) } -> "
24188                "std::convertible_to<std::size_t>;\n"
24189                "                   };");
24190 
24191   verifyFormat(
24192       "template <typename T>\n"
24193       "concept EqualityComparable = requires(T a, T b) {\n"
24194       "                               { a == b } -> std::same_as<bool>;\n"
24195       "                             };");
24196 
24197   verifyFormat(
24198       "template <typename T>\n"
24199       "concept EqualityComparable = requires(T a, T b) {\n"
24200       "                               { a == b } -> std::same_as<bool>;\n"
24201       "                               { a != b } -> std::same_as<bool>;\n"
24202       "                             };");
24203 
24204   verifyFormat("template <typename T>\n"
24205                "concept WeakEqualityComparable = requires(T a, T b) {\n"
24206                "                                   { a == b };\n"
24207                "                                   { a != b };\n"
24208                "                                 };");
24209 
24210   verifyFormat("template <typename T>\n"
24211                "concept HasSizeT = requires { typename T::size_t; };");
24212 
24213   verifyFormat("template <typename T>\n"
24214                "concept Semiregular =\n"
24215                "    DefaultConstructible<T> && CopyConstructible<T> && "
24216                "CopyAssignable<T> &&\n"
24217                "    requires(T a, std::size_t n) {\n"
24218                "      requires Same<T *, decltype(&a)>;\n"
24219                "      { a.~T() } noexcept;\n"
24220                "      requires Same<T *, decltype(new T)>;\n"
24221                "      requires Same<T *, decltype(new T[n])>;\n"
24222                "      { delete new T; };\n"
24223                "      { delete new T[n]; };\n"
24224                "    };");
24225 
24226   verifyFormat("template <typename T>\n"
24227                "concept Semiregular =\n"
24228                "    requires(T a, std::size_t n) {\n"
24229                "      requires Same<T *, decltype(&a)>;\n"
24230                "      { a.~T() } noexcept;\n"
24231                "      requires Same<T *, decltype(new T)>;\n"
24232                "      requires Same<T *, decltype(new T[n])>;\n"
24233                "      { delete new T; };\n"
24234                "      { delete new T[n]; };\n"
24235                "      { new T } -> std::same_as<T *>;\n"
24236                "    } && DefaultConstructible<T> && CopyConstructible<T> && "
24237                "CopyAssignable<T>;");
24238 
24239   verifyFormat(
24240       "template <typename T>\n"
24241       "concept Semiregular =\n"
24242       "    DefaultConstructible<T> && requires(T a, std::size_t n) {\n"
24243       "                                 requires Same<T *, decltype(&a)>;\n"
24244       "                                 { a.~T() } noexcept;\n"
24245       "                                 requires Same<T *, decltype(new T)>;\n"
24246       "                                 requires Same<T *, decltype(new "
24247       "T[n])>;\n"
24248       "                                 { delete new T; };\n"
24249       "                                 { delete new T[n]; };\n"
24250       "                               } && CopyConstructible<T> && "
24251       "CopyAssignable<T>;");
24252 
24253   verifyFormat("template <typename T>\n"
24254                "concept Two = requires(T t) {\n"
24255                "                { t.foo() } -> std::same_as<Bar>;\n"
24256                "              } && requires(T &&t) {\n"
24257                "                     { t.foo() } -> std::same_as<Bar &&>;\n"
24258                "                   };");
24259 
24260   verifyFormat(
24261       "template <typename T>\n"
24262       "concept C = requires(T x) {\n"
24263       "              { *x } -> std::convertible_to<typename T::inner>;\n"
24264       "              { x + 1 } noexcept -> std::same_as<int>;\n"
24265       "              { x * 1 } -> std::convertible_to<T>;\n"
24266       "            };");
24267 
24268   verifyFormat(
24269       "template <typename T, typename U = T>\n"
24270       "concept Swappable = requires(T &&t, U &&u) {\n"
24271       "                      swap(std::forward<T>(t), std::forward<U>(u));\n"
24272       "                      swap(std::forward<U>(u), std::forward<T>(t));\n"
24273       "                    };");
24274 
24275   verifyFormat("template <typename T, typename U>\n"
24276                "concept Common = requires(T &&t, U &&u) {\n"
24277                "                   typename CommonType<T, U>;\n"
24278                "                   { CommonType<T, U>(std::forward<T>(t)) };\n"
24279                "                 };");
24280 
24281   verifyFormat("template <typename T, typename U>\n"
24282                "concept Common = requires(T &&t, U &&u) {\n"
24283                "                   typename CommonType<T, U>;\n"
24284                "                   { CommonType<T, U>{std::forward<T>(t)} };\n"
24285                "                 };");
24286 
24287   verifyFormat(
24288       "template <typename T>\n"
24289       "concept C = requires(T t) {\n"
24290       "              requires Bar<T> && Foo<T>;\n"
24291       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24292       "            };");
24293 
24294   verifyFormat("template <typename T>\n"
24295                "concept HasFoo = requires(T t) {\n"
24296                "                   { t.foo() };\n"
24297                "                   t.foo();\n"
24298                "                 };\n"
24299                "template <typename T>\n"
24300                "concept HasBar = requires(T t) {\n"
24301                "                   { t.bar() };\n"
24302                "                   t.bar();\n"
24303                "                 };");
24304 
24305   verifyFormat("template <typename T>\n"
24306                "concept Large = sizeof(T) > 10;");
24307 
24308   verifyFormat("template <typename T, typename U>\n"
24309                "concept FooableWith = requires(T t, U u) {\n"
24310                "                        typename T::foo_type;\n"
24311                "                        { t.foo(u) } -> typename T::foo_type;\n"
24312                "                        t++;\n"
24313                "                      };\n"
24314                "void doFoo(FooableWith<int> auto t) { t.foo(3); }");
24315 
24316   verifyFormat("template <typename T>\n"
24317                "concept Context = is_specialization_of_v<context, T>;");
24318 
24319   verifyFormat("template <typename T>\n"
24320                "concept Node = std::is_object_v<T>;");
24321 
24322   verifyFormat("template <class T>\n"
24323                "concept integral = __is_integral(T);");
24324 
24325   verifyFormat("template <class T>\n"
24326                "concept is2D = __array_extent(T, 1) == 2;");
24327 
24328   verifyFormat("template <class T>\n"
24329                "concept isRhs = __is_rvalue_expr(std::declval<T>() + 2)");
24330 
24331   verifyFormat("template <class T, class T2>\n"
24332                "concept Same = __is_same_as<T, T2>;");
24333 
24334   verifyFormat(
24335       "template <class _InIt, class _OutIt>\n"
24336       "concept _Can_reread_dest =\n"
24337       "    std::forward_iterator<_OutIt> &&\n"
24338       "    std::same_as<std::iter_value_t<_InIt>, std::iter_value_t<_OutIt>>;");
24339 
24340   auto Style = getLLVMStyle();
24341   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Allowed;
24342 
24343   verifyFormat(
24344       "template <typename T>\n"
24345       "concept C = requires(T t) {\n"
24346       "              requires Bar<T> && Foo<T>;\n"
24347       "              requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24348       "            };",
24349       Style);
24350 
24351   verifyFormat("template <typename T>\n"
24352                "concept HasFoo = requires(T t) {\n"
24353                "                   { t.foo() };\n"
24354                "                   t.foo();\n"
24355                "                 };\n"
24356                "template <typename T>\n"
24357                "concept HasBar = requires(T t) {\n"
24358                "                   { t.bar() };\n"
24359                "                   t.bar();\n"
24360                "                 };",
24361                Style);
24362 
24363   verifyFormat("template <typename T> concept True = true;", Style);
24364 
24365   verifyFormat("template <typename T>\n"
24366                "concept C = decltype([]() -> std::true_type { return {}; "
24367                "}())::value &&\n"
24368                "            requires(T t) { t.bar(); } && sizeof(T) <= 8;",
24369                Style);
24370 
24371   verifyFormat("template <typename T>\n"
24372                "concept Semiregular =\n"
24373                "    DefaultConstructible<T> && CopyConstructible<T> && "
24374                "CopyAssignable<T> &&\n"
24375                "    requires(T a, std::size_t n) {\n"
24376                "      requires Same<T *, decltype(&a)>;\n"
24377                "      { a.~T() } noexcept;\n"
24378                "      requires Same<T *, decltype(new T)>;\n"
24379                "      requires Same<T *, decltype(new T[n])>;\n"
24380                "      { delete new T; };\n"
24381                "      { delete new T[n]; };\n"
24382                "    };",
24383                Style);
24384 
24385   Style.BreakBeforeConceptDeclarations = FormatStyle::BBCDS_Never;
24386 
24387   verifyFormat("template <typename T> concept C =\n"
24388                "    requires(T t) {\n"
24389                "      requires Bar<T> && Foo<T>;\n"
24390                "      requires((trait<T> && Baz) || (T2<T> && Foo<T>));\n"
24391                "    };",
24392                Style);
24393 
24394   verifyFormat("template <typename T> concept HasFoo = requires(T t) {\n"
24395                "                                         { t.foo() };\n"
24396                "                                         t.foo();\n"
24397                "                                       };\n"
24398                "template <typename T> concept HasBar = requires(T t) {\n"
24399                "                                         { t.bar() };\n"
24400                "                                         t.bar();\n"
24401                "                                       };",
24402                Style);
24403 
24404   verifyFormat("template <typename T> concept True = true;", Style);
24405 
24406   verifyFormat(
24407       "template <typename T> concept C = decltype([]() -> std::true_type {\n"
24408       "                                    return {};\n"
24409       "                                  }())::value &&\n"
24410       "                                  requires(T t) { t.bar(); } && "
24411       "sizeof(T) <= 8;",
24412       Style);
24413 
24414   verifyFormat("template <typename T> concept Semiregular =\n"
24415                "    DefaultConstructible<T> && CopyConstructible<T> && "
24416                "CopyAssignable<T> &&\n"
24417                "    requires(T a, std::size_t n) {\n"
24418                "      requires Same<T *, decltype(&a)>;\n"
24419                "      { a.~T() } noexcept;\n"
24420                "      requires Same<T *, decltype(new T)>;\n"
24421                "      requires Same<T *, decltype(new T[n])>;\n"
24422                "      { delete new T; };\n"
24423                "      { delete new T[n]; };\n"
24424                "    };",
24425                Style);
24426 
24427   // The following tests are invalid C++, we just want to make sure we don't
24428   // assert.
24429   verifyFormat("template <typename T>\n"
24430                "concept C = requires C2<T>;");
24431 
24432   verifyFormat("template <typename T>\n"
24433                "concept C = 5 + 4;");
24434 
24435   verifyFormat("template <typename T>\n"
24436                "concept C =\n"
24437                "class X;");
24438 
24439   verifyFormat("template <typename T>\n"
24440                "concept C = [] && true;");
24441 
24442   verifyFormat("template <typename T>\n"
24443                "concept C = [] && requires(T t) { typename T::size_type; };");
24444 }
24445 
TEST_F(FormatTest,RequiresClausesPositions)24446 TEST_F(FormatTest, RequiresClausesPositions) {
24447   auto Style = getLLVMStyle();
24448   EXPECT_EQ(Style.RequiresClausePosition, FormatStyle::RCPS_OwnLine);
24449   EXPECT_EQ(Style.IndentRequiresClause, true);
24450 
24451   verifyFormat("template <typename T>\n"
24452                "  requires(Foo<T> && std::trait<T>)\n"
24453                "struct Bar;",
24454                Style);
24455 
24456   verifyFormat("template <typename T>\n"
24457                "  requires(Foo<T> && std::trait<T>)\n"
24458                "class Bar {\n"
24459                "public:\n"
24460                "  Bar(T t);\n"
24461                "  bool baz();\n"
24462                "};",
24463                Style);
24464 
24465   verifyFormat(
24466       "template <typename T>\n"
24467       "  requires requires(T &&t) {\n"
24468       "             typename T::I;\n"
24469       "             requires(F<typename T::I> && std::trait<typename T::I>);\n"
24470       "           }\n"
24471       "Bar(T) -> Bar<typename T::I>;",
24472       Style);
24473 
24474   verifyFormat("template <typename T>\n"
24475                "  requires(Foo<T> && std::trait<T>)\n"
24476                "constexpr T MyGlobal;",
24477                Style);
24478 
24479   verifyFormat("template <typename T>\n"
24480                "  requires Foo<T> && requires(T t) {\n"
24481                "                       { t.baz() } -> std::same_as<bool>;\n"
24482                "                       requires std::same_as<T::Factor, int>;\n"
24483                "                     }\n"
24484                "inline int bar(T t) {\n"
24485                "  return t.baz() ? T::Factor : 5;\n"
24486                "}",
24487                Style);
24488 
24489   verifyFormat("template <typename T>\n"
24490                "inline int bar(T t)\n"
24491                "  requires Foo<T> && requires(T t) {\n"
24492                "                       { t.baz() } -> std::same_as<bool>;\n"
24493                "                       requires std::same_as<T::Factor, int>;\n"
24494                "                     }\n"
24495                "{\n"
24496                "  return t.baz() ? T::Factor : 5;\n"
24497                "}",
24498                Style);
24499 
24500   verifyFormat("template <typename T>\n"
24501                "  requires F<T>\n"
24502                "int bar(T t) {\n"
24503                "  return 5;\n"
24504                "}",
24505                Style);
24506 
24507   verifyFormat("template <typename T>\n"
24508                "int bar(T t)\n"
24509                "  requires F<T>\n"
24510                "{\n"
24511                "  return 5;\n"
24512                "}",
24513                Style);
24514 
24515   verifyFormat("template <typename T>\n"
24516                "int bar(T t)\n"
24517                "  requires F<T>;",
24518                Style);
24519 
24520   Style.IndentRequiresClause = false;
24521   verifyFormat("template <typename T>\n"
24522                "requires F<T>\n"
24523                "int bar(T t) {\n"
24524                "  return 5;\n"
24525                "}",
24526                Style);
24527 
24528   verifyFormat("template <typename T>\n"
24529                "int bar(T t)\n"
24530                "requires F<T>\n"
24531                "{\n"
24532                "  return 5;\n"
24533                "}",
24534                Style);
24535 
24536   Style.RequiresClausePosition = FormatStyle::RCPS_SingleLine;
24537   verifyFormat("template <typename T> requires Foo<T> struct Bar {};\n"
24538                "template <typename T> requires Foo<T> void bar() {}\n"
24539                "template <typename T> void bar() requires Foo<T> {}\n"
24540                "template <typename T> void bar() requires Foo<T>;\n"
24541                "template <typename T> requires Foo<T> Bar(T) -> Bar<T>;",
24542                Style);
24543 
24544   auto ColumnStyle = Style;
24545   ColumnStyle.ColumnLimit = 40;
24546   verifyFormat("template <typename AAAAAAA>\n"
24547                "requires Foo<T> struct Bar {};\n"
24548                "template <typename AAAAAAA>\n"
24549                "requires Foo<T> void bar() {}\n"
24550                "template <typename AAAAAAA>\n"
24551                "void bar() requires Foo<T> {}\n"
24552                "template <typename AAAAAAA>\n"
24553                "requires Foo<T> Baz(T) -> Baz<T>;",
24554                ColumnStyle);
24555 
24556   verifyFormat("template <typename T>\n"
24557                "requires Foo<AAAAAAA> struct Bar {};\n"
24558                "template <typename T>\n"
24559                "requires Foo<AAAAAAA> void bar() {}\n"
24560                "template <typename T>\n"
24561                "void bar() requires Foo<AAAAAAA> {}\n"
24562                "template <typename T>\n"
24563                "requires Foo<AAAAAAA> Bar(T) -> Bar<T>;",
24564                ColumnStyle);
24565 
24566   verifyFormat("template <typename AAAAAAA>\n"
24567                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24568                "struct Bar {};\n"
24569                "template <typename AAAAAAA>\n"
24570                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24571                "void bar() {}\n"
24572                "template <typename AAAAAAA>\n"
24573                "void bar()\n"
24574                "    requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24575                "template <typename AAAAAAA>\n"
24576                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24577                "template <typename AAAAAAA>\n"
24578                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24579                "Bar(T) -> Bar<T>;",
24580                ColumnStyle);
24581 
24582   Style.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24583   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithFollowing;
24584 
24585   verifyFormat("template <typename T>\n"
24586                "requires Foo<T> struct Bar {};\n"
24587                "template <typename T>\n"
24588                "requires Foo<T> void bar() {}\n"
24589                "template <typename T>\n"
24590                "void bar()\n"
24591                "requires Foo<T> {}\n"
24592                "template <typename T>\n"
24593                "void bar()\n"
24594                "requires Foo<T>;\n"
24595                "template <typename T>\n"
24596                "requires Foo<T> Bar(T) -> Bar<T>;",
24597                Style);
24598 
24599   verifyFormat("template <typename AAAAAAA>\n"
24600                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24601                "struct Bar {};\n"
24602                "template <typename AAAAAAA>\n"
24603                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24604                "void bar() {}\n"
24605                "template <typename AAAAAAA>\n"
24606                "void bar()\n"
24607                "requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24608                "template <typename AAAAAAA>\n"
24609                "requires Foo<AAAAAAAA> Bar(T) -> Bar<T>;\n"
24610                "template <typename AAAAAAA>\n"
24611                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24612                "Bar(T) -> Bar<T>;",
24613                ColumnStyle);
24614 
24615   Style.IndentRequiresClause = true;
24616   ColumnStyle.IndentRequiresClause = true;
24617 
24618   verifyFormat("template <typename T>\n"
24619                "  requires Foo<T> struct Bar {};\n"
24620                "template <typename T>\n"
24621                "  requires Foo<T> void bar() {}\n"
24622                "template <typename T>\n"
24623                "void bar()\n"
24624                "  requires Foo<T> {}\n"
24625                "template <typename T>\n"
24626                "  requires Foo<T> Bar(T) -> Bar<T>;",
24627                Style);
24628 
24629   verifyFormat("template <typename AAAAAAA>\n"
24630                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24631                "struct Bar {};\n"
24632                "template <typename AAAAAAA>\n"
24633                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24634                "void bar() {}\n"
24635                "template <typename AAAAAAA>\n"
24636                "void bar()\n"
24637                "  requires Foo<AAAAAAAAAAAAAAAA> {}\n"
24638                "template <typename AAAAAAA>\n"
24639                "  requires Foo<AAAAAA> Bar(T) -> Bar<T>;\n"
24640                "template <typename AAAAAAA>\n"
24641                "  requires Foo<AAAAAAAAAAAAAAAA>\n"
24642                "Bar(T) -> Bar<T>;",
24643                ColumnStyle);
24644 
24645   Style.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24646   ColumnStyle.RequiresClausePosition = FormatStyle::RCPS_WithPreceding;
24647 
24648   verifyFormat("template <typename T> requires Foo<T>\n"
24649                "struct Bar {};\n"
24650                "template <typename T> requires Foo<T>\n"
24651                "void bar() {}\n"
24652                "template <typename T>\n"
24653                "void bar() requires Foo<T>\n"
24654                "{}\n"
24655                "template <typename T> void bar() requires Foo<T>;\n"
24656                "template <typename T> requires Foo<T>\n"
24657                "Bar(T) -> Bar<T>;",
24658                Style);
24659 
24660   verifyFormat("template <typename AAAAAAA>\n"
24661                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24662                "struct Bar {};\n"
24663                "template <typename AAAAAAA>\n"
24664                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24665                "void bar() {}\n"
24666                "template <typename AAAAAAA>\n"
24667                "void bar()\n"
24668                "    requires Foo<AAAAAAAAAAAAAAAA>\n"
24669                "{}\n"
24670                "template <typename AAAAAAA>\n"
24671                "requires Foo<AAAAAAAA>\n"
24672                "Bar(T) -> Bar<T>;\n"
24673                "template <typename AAAAAAA>\n"
24674                "requires Foo<AAAAAAAAAAAAAAAA>\n"
24675                "Bar(T) -> Bar<T>;",
24676                ColumnStyle);
24677 }
24678 
TEST_F(FormatTest,RequiresClauses)24679 TEST_F(FormatTest, RequiresClauses) {
24680   verifyFormat("struct [[nodiscard]] zero_t {\n"
24681                "  template <class T>\n"
24682                "    requires requires { number_zero_v<T>; }\n"
24683                "  [[nodiscard]] constexpr operator T() const {\n"
24684                "    return number_zero_v<T>;\n"
24685                "  }\n"
24686                "};");
24687 
24688   auto Style = getLLVMStyle();
24689 
24690   verifyFormat(
24691       "template <typename T>\n"
24692       "  requires is_default_constructible_v<hash<T>> and\n"
24693       "           is_copy_constructible_v<hash<T>> and\n"
24694       "           is_move_constructible_v<hash<T>> and\n"
24695       "           is_copy_assignable_v<hash<T>> and "
24696       "is_move_assignable_v<hash<T>> and\n"
24697       "           is_destructible_v<hash<T>> and is_swappable_v<hash<T>> and\n"
24698       "           is_callable_v<hash<T>(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<T &>()))> and\n"
24701       "           is_same_v<size_t, decltype(hash<T>(declval<const T &>()))>\n"
24702       "struct S {};",
24703       Style);
24704 
24705   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
24706   verifyFormat(
24707       "template <typename T>\n"
24708       "  requires is_default_constructible_v<hash<T>>\n"
24709       "           and is_copy_constructible_v<hash<T>>\n"
24710       "           and is_move_constructible_v<hash<T>>\n"
24711       "           and is_copy_assignable_v<hash<T>> and "
24712       "is_move_assignable_v<hash<T>>\n"
24713       "           and is_destructible_v<hash<T>> and is_swappable_v<hash<T>>\n"
24714       "           and is_callable_v<hash<T>(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<T &>()))>\n"
24717       "           and is_same_v<size_t, decltype(hash<T>(declval<const T "
24718       "&>()))>\n"
24719       "struct S {};",
24720       Style);
24721 
24722   Style = getLLVMStyle();
24723   Style.ConstructorInitializerIndentWidth = 4;
24724   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
24725   Style.PackConstructorInitializers = FormatStyle::PCIS_Never;
24726   verifyFormat("constexpr Foo(Foo const &other)\n"
24727                "  requires std::is_copy_constructible<T>\n"
24728                "    : value{other.value} {\n"
24729                "  do_magic();\n"
24730                "  do_more_magic();\n"
24731                "}",
24732                Style);
24733 
24734   // Not a clause, but we once hit an assert.
24735   verifyFormat("#if 0\n"
24736                "#else\n"
24737                "foo();\n"
24738                "#endif\n"
24739                "bar(requires);");
24740 }
24741 
TEST_F(FormatTest,StatementAttributeLikeMacros)24742 TEST_F(FormatTest, StatementAttributeLikeMacros) {
24743   FormatStyle Style = getLLVMStyle();
24744   StringRef Source = "void Foo::slot() {\n"
24745                      "  unsigned char MyChar = 'x';\n"
24746                      "  emit signal(MyChar);\n"
24747                      "  Q_EMIT signal(MyChar);\n"
24748                      "}";
24749 
24750   EXPECT_EQ(Source, format(Source, Style));
24751 
24752   Style.AlignConsecutiveDeclarations.Enabled = true;
24753   EXPECT_EQ("void Foo::slot() {\n"
24754             "  unsigned char MyChar = 'x';\n"
24755             "  emit          signal(MyChar);\n"
24756             "  Q_EMIT signal(MyChar);\n"
24757             "}",
24758             format(Source, Style));
24759 
24760   Style.StatementAttributeLikeMacros.push_back("emit");
24761   EXPECT_EQ(Source, format(Source, Style));
24762 
24763   Style.StatementAttributeLikeMacros = {};
24764   EXPECT_EQ("void Foo::slot() {\n"
24765             "  unsigned char MyChar = 'x';\n"
24766             "  emit          signal(MyChar);\n"
24767             "  Q_EMIT        signal(MyChar);\n"
24768             "}",
24769             format(Source, Style));
24770 }
24771 
TEST_F(FormatTest,IndentAccessModifiers)24772 TEST_F(FormatTest, IndentAccessModifiers) {
24773   FormatStyle Style = getLLVMStyle();
24774   Style.IndentAccessModifiers = true;
24775   // Members are *two* levels below the record;
24776   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
24777   verifyFormat("class C {\n"
24778                "    int i;\n"
24779                "};\n",
24780                Style);
24781   verifyFormat("union C {\n"
24782                "    int i;\n"
24783                "    unsigned u;\n"
24784                "};\n",
24785                Style);
24786   // Access modifiers should be indented one level below the record.
24787   verifyFormat("class C {\n"
24788                "  public:\n"
24789                "    int i;\n"
24790                "};\n",
24791                Style);
24792   verifyFormat("struct S {\n"
24793                "  private:\n"
24794                "    class C {\n"
24795                "        int j;\n"
24796                "\n"
24797                "      public:\n"
24798                "        C();\n"
24799                "    };\n"
24800                "\n"
24801                "  public:\n"
24802                "    int i;\n"
24803                "};\n",
24804                Style);
24805   // Enumerations are not records and should be unaffected.
24806   Style.AllowShortEnumsOnASingleLine = false;
24807   verifyFormat("enum class E {\n"
24808                "  A,\n"
24809                "  B\n"
24810                "};\n",
24811                Style);
24812   // Test with a different indentation width;
24813   // also proves that the result is Style.AccessModifierOffset agnostic.
24814   Style.IndentWidth = 3;
24815   verifyFormat("class C {\n"
24816                "   public:\n"
24817                "      int i;\n"
24818                "};\n",
24819                Style);
24820 }
24821 
TEST_F(FormatTest,LimitlessStringsAndComments)24822 TEST_F(FormatTest, LimitlessStringsAndComments) {
24823   auto Style = getLLVMStyleWithColumns(0);
24824   constexpr StringRef Code =
24825       "/**\n"
24826       " * This is a multiline comment with quite some long lines, at least for "
24827       "the LLVM Style.\n"
24828       " * We will redo this with strings and line comments. Just to  check if "
24829       "everything is working.\n"
24830       " */\n"
24831       "bool foo() {\n"
24832       "  /* Single line multi line comment. */\n"
24833       "  const std::string String = \"This is a multiline string with quite "
24834       "some long lines, at least for the LLVM Style.\"\n"
24835       "                             \"We already did it with multi line "
24836       "comments, and we will do it with line comments. Just to check if "
24837       "everything is working.\";\n"
24838       "  // This is a line comment (block) with quite some long lines, at "
24839       "least for the LLVM Style.\n"
24840       "  // We already did this with multi line comments and strings. Just to "
24841       "check if everything is working.\n"
24842       "  const std::string SmallString = \"Hello World\";\n"
24843       "  // Small line comment\n"
24844       "  return String.size() > SmallString.size();\n"
24845       "}";
24846   EXPECT_EQ(Code, format(Code, Style));
24847 }
24848 
TEST_F(FormatTest,FormatDecayCopy)24849 TEST_F(FormatTest, FormatDecayCopy) {
24850   // error cases from unit tests
24851   verifyFormat("foo(auto())");
24852   verifyFormat("foo(auto{})");
24853   verifyFormat("foo(auto({}))");
24854   verifyFormat("foo(auto{{}})");
24855 
24856   verifyFormat("foo(auto(1))");
24857   verifyFormat("foo(auto{1})");
24858   verifyFormat("foo(new auto(1))");
24859   verifyFormat("foo(new auto{1})");
24860   verifyFormat("decltype(auto(1)) x;");
24861   verifyFormat("decltype(auto{1}) x;");
24862   verifyFormat("auto(x);");
24863   verifyFormat("auto{x};");
24864   verifyFormat("new auto{x};");
24865   verifyFormat("auto{x} = y;");
24866   verifyFormat("auto(x) = y;"); // actually a declaration, but this is clearly
24867                                 // the user's own fault
24868   verifyFormat("integral auto(x) = y;"); // actually a declaration, but this is
24869                                          // clearly the user's own fault
24870   verifyFormat("auto(*p)() = f;");       // actually a declaration; TODO FIXME
24871 }
24872 
TEST_F(FormatTest,Cpp20ModulesSupport)24873 TEST_F(FormatTest, Cpp20ModulesSupport) {
24874   FormatStyle Style = getLLVMStyle();
24875   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
24876   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
24877 
24878   verifyFormat("export import foo;", Style);
24879   verifyFormat("export import foo:bar;", Style);
24880   verifyFormat("export import foo.bar;", Style);
24881   verifyFormat("export import foo.bar:baz;", Style);
24882   verifyFormat("export import :bar;", Style);
24883   verifyFormat("export module foo:bar;", Style);
24884   verifyFormat("export module foo;", Style);
24885   verifyFormat("export module foo.bar;", Style);
24886   verifyFormat("export module foo.bar:baz;", Style);
24887   verifyFormat("export import <string_view>;", Style);
24888 
24889   verifyFormat("export type_name var;", Style);
24890   verifyFormat("template <class T> export using A = B<T>;", Style);
24891   verifyFormat("export using A = B;", Style);
24892   verifyFormat("export int func() {\n"
24893                "  foo();\n"
24894                "}",
24895                Style);
24896   verifyFormat("export struct {\n"
24897                "  int foo;\n"
24898                "};",
24899                Style);
24900   verifyFormat("export {\n"
24901                "  int foo;\n"
24902                "};",
24903                Style);
24904   verifyFormat("export export char const *hello() { return \"hello\"; }");
24905 
24906   verifyFormat("import bar;", Style);
24907   verifyFormat("import foo.bar;", Style);
24908   verifyFormat("import foo:bar;", Style);
24909   verifyFormat("import :bar;", Style);
24910   verifyFormat("import <ctime>;", Style);
24911   verifyFormat("import \"header\";", Style);
24912 
24913   verifyFormat("module foo;", Style);
24914   verifyFormat("module foo:bar;", Style);
24915   verifyFormat("module foo.bar;", Style);
24916   verifyFormat("module;", Style);
24917 
24918   verifyFormat("export namespace hi {\n"
24919                "const char *sayhi();\n"
24920                "}",
24921                Style);
24922 
24923   verifyFormat("module :private;", Style);
24924   verifyFormat("import <foo/bar.h>;", Style);
24925   verifyFormat("import foo...bar;", Style);
24926   verifyFormat("import ..........;", Style);
24927   verifyFormat("module foo:private;", Style);
24928   verifyFormat("import a", Style);
24929   verifyFormat("module a", Style);
24930   verifyFormat("export import a", Style);
24931   verifyFormat("export module a", Style);
24932 
24933   verifyFormat("import", Style);
24934   verifyFormat("module", Style);
24935   verifyFormat("export", Style);
24936 }
24937 
TEST_F(FormatTest,CoroutineForCoawait)24938 TEST_F(FormatTest, CoroutineForCoawait) {
24939   FormatStyle Style = getLLVMStyle();
24940   verifyFormat("for co_await (auto x : range())\n  ;");
24941   verifyFormat("for (auto i : arr) {\n"
24942                "}",
24943                Style);
24944   verifyFormat("for co_await (auto i : arr) {\n"
24945                "}",
24946                Style);
24947   verifyFormat("for co_await (auto i : foo(T{})) {\n"
24948                "}",
24949                Style);
24950 }
24951 
TEST_F(FormatTest,CoroutineCoAwait)24952 TEST_F(FormatTest, CoroutineCoAwait) {
24953   verifyFormat("int x = co_await foo();");
24954   verifyFormat("int x = (co_await foo());");
24955   verifyFormat("co_await (42);");
24956   verifyFormat("void operator co_await(int);");
24957   verifyFormat("void operator co_await(a);");
24958   verifyFormat("co_await a;");
24959   verifyFormat("co_await missing_await_resume{};");
24960   verifyFormat("co_await a; // comment");
24961   verifyFormat("void test0() { co_await a; }");
24962   verifyFormat("co_await co_await co_await foo();");
24963   verifyFormat("co_await foo().bar();");
24964   verifyFormat("co_await [this]() -> Task { co_return x; }");
24965   verifyFormat("co_await [this](int a, int b) -> Task { co_return co_await "
24966                "foo(); }(x, y);");
24967 
24968   FormatStyle Style = getLLVMStyleWithColumns(40);
24969   verifyFormat("co_await [this](int a, int b) -> Task {\n"
24970                "  co_return co_await foo();\n"
24971                "}(x, y);",
24972                Style);
24973   verifyFormat("co_await;");
24974 }
24975 
TEST_F(FormatTest,CoroutineCoYield)24976 TEST_F(FormatTest, CoroutineCoYield) {
24977   verifyFormat("int x = co_yield foo();");
24978   verifyFormat("int x = (co_yield foo());");
24979   verifyFormat("co_yield (42);");
24980   verifyFormat("co_yield {42};");
24981   verifyFormat("co_yield 42;");
24982   verifyFormat("co_yield n++;");
24983   verifyFormat("co_yield ++n;");
24984   verifyFormat("co_yield;");
24985 }
24986 
TEST_F(FormatTest,CoroutineCoReturn)24987 TEST_F(FormatTest, CoroutineCoReturn) {
24988   verifyFormat("co_return (42);");
24989   verifyFormat("co_return;");
24990   verifyFormat("co_return {};");
24991   verifyFormat("co_return x;");
24992   verifyFormat("co_return co_await foo();");
24993   verifyFormat("co_return co_yield foo();");
24994 }
24995 
TEST_F(FormatTest,EmptyShortBlock)24996 TEST_F(FormatTest, EmptyShortBlock) {
24997   auto Style = getLLVMStyle();
24998   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
24999 
25000   verifyFormat("try {\n"
25001                "  doA();\n"
25002                "} catch (Exception &e) {\n"
25003                "  e.printStackTrace();\n"
25004                "}\n",
25005                Style);
25006 
25007   verifyFormat("try {\n"
25008                "  doA();\n"
25009                "} catch (Exception &e) {}\n",
25010                Style);
25011 }
25012 
TEST_F(FormatTest,ShortTemplatedArgumentLists)25013 TEST_F(FormatTest, ShortTemplatedArgumentLists) {
25014   auto Style = getLLVMStyle();
25015 
25016   verifyFormat("template <> struct S : Template<int (*)[]> {};\n", Style);
25017   verifyFormat("template <> struct S : Template<int (*)[10]> {};\n", Style);
25018   verifyFormat("struct Y : X<[] { return 0; }> {};", Style);
25019   verifyFormat("struct Y<[] { return 0; }> {};", Style);
25020 
25021   verifyFormat("struct Z : X<decltype([] { return 0; }){}> {};", Style);
25022   verifyFormat("template <int N> struct Foo<char[N]> {};", Style);
25023 }
25024 
TEST_F(FormatTest,InsertBraces)25025 TEST_F(FormatTest, InsertBraces) {
25026   FormatStyle Style = getLLVMStyle();
25027   Style.InsertBraces = true;
25028 
25029   verifyFormat("// clang-format off\n"
25030                "// comment\n"
25031                "if (a) f();\n"
25032                "// clang-format on\n"
25033                "if (b) {\n"
25034                "  g();\n"
25035                "}",
25036                "// clang-format off\n"
25037                "// comment\n"
25038                "if (a) f();\n"
25039                "// clang-format on\n"
25040                "if (b) g();",
25041                Style);
25042 
25043   verifyFormat("if (a) {\n"
25044                "  switch (b) {\n"
25045                "  case 1:\n"
25046                "    c = 0;\n"
25047                "    break;\n"
25048                "  default:\n"
25049                "    c = 1;\n"
25050                "  }\n"
25051                "}",
25052                "if (a)\n"
25053                "  switch (b) {\n"
25054                "  case 1:\n"
25055                "    c = 0;\n"
25056                "    break;\n"
25057                "  default:\n"
25058                "    c = 1;\n"
25059                "  }",
25060                Style);
25061 
25062   verifyFormat("for (auto node : nodes) {\n"
25063                "  if (node) {\n"
25064                "    break;\n"
25065                "  }\n"
25066                "}",
25067                "for (auto node : nodes)\n"
25068                "  if (node)\n"
25069                "    break;",
25070                Style);
25071 
25072   verifyFormat("for (auto node : nodes) {\n"
25073                "  if (node)\n"
25074                "}",
25075                "for (auto node : nodes)\n"
25076                "  if (node)",
25077                Style);
25078 
25079   verifyFormat("do {\n"
25080                "  --a;\n"
25081                "} while (a);",
25082                "do\n"
25083                "  --a;\n"
25084                "while (a);",
25085                Style);
25086 
25087   verifyFormat("if (i) {\n"
25088                "  ++i;\n"
25089                "} else {\n"
25090                "  --i;\n"
25091                "}",
25092                "if (i)\n"
25093                "  ++i;\n"
25094                "else {\n"
25095                "  --i;\n"
25096                "}",
25097                Style);
25098 
25099   verifyFormat("void f() {\n"
25100                "  while (j--) {\n"
25101                "    while (i) {\n"
25102                "      --i;\n"
25103                "    }\n"
25104                "  }\n"
25105                "}",
25106                "void f() {\n"
25107                "  while (j--)\n"
25108                "    while (i)\n"
25109                "      --i;\n"
25110                "}",
25111                Style);
25112 
25113   verifyFormat("f({\n"
25114                "  if (a) {\n"
25115                "    g();\n"
25116                "  }\n"
25117                "});",
25118                "f({\n"
25119                "  if (a)\n"
25120                "    g();\n"
25121                "});",
25122                Style);
25123 
25124   verifyFormat("if (a) {\n"
25125                "  f();\n"
25126                "} else if (b) {\n"
25127                "  g();\n"
25128                "} else {\n"
25129                "  h();\n"
25130                "}",
25131                "if (a)\n"
25132                "  f();\n"
25133                "else if (b)\n"
25134                "  g();\n"
25135                "else\n"
25136                "  h();",
25137                Style);
25138 
25139   verifyFormat("if (a) {\n"
25140                "  f();\n"
25141                "}\n"
25142                "// comment\n"
25143                "/* comment */",
25144                "if (a)\n"
25145                "  f();\n"
25146                "// comment\n"
25147                "/* comment */",
25148                Style);
25149 
25150   verifyFormat("if (a) {\n"
25151                "  // foo\n"
25152                "  // bar\n"
25153                "  f();\n"
25154                "}",
25155                "if (a)\n"
25156                "  // foo\n"
25157                "  // bar\n"
25158                "  f();",
25159                Style);
25160 
25161   verifyFormat("if (a) { // comment\n"
25162                "  // comment\n"
25163                "  f();\n"
25164                "}",
25165                "if (a) // comment\n"
25166                "  // comment\n"
25167                "  f();",
25168                Style);
25169 
25170   verifyFormat("if (a) {\n"
25171                "  f(); // comment\n"
25172                "}",
25173                "if (a)\n"
25174                "  f(); // comment",
25175                Style);
25176 
25177   verifyFormat("if (a) {\n"
25178                "  f();\n"
25179                "}\n"
25180                "#undef A\n"
25181                "#undef B",
25182                "if (a)\n"
25183                "  f();\n"
25184                "#undef A\n"
25185                "#undef B",
25186                Style);
25187 
25188   verifyFormat("if (a)\n"
25189                "#ifdef A\n"
25190                "  f();\n"
25191                "#else\n"
25192                "  g();\n"
25193                "#endif",
25194                Style);
25195 
25196   verifyFormat("#if 0\n"
25197                "#elif 1\n"
25198                "#endif\n"
25199                "void f() {\n"
25200                "  if (a) {\n"
25201                "    g();\n"
25202                "  }\n"
25203                "}",
25204                "#if 0\n"
25205                "#elif 1\n"
25206                "#endif\n"
25207                "void f() {\n"
25208                "  if (a) g();\n"
25209                "}",
25210                Style);
25211 
25212   Style.ColumnLimit = 15;
25213 
25214   verifyFormat("#define A     \\\n"
25215                "  if (a)      \\\n"
25216                "    f();",
25217                Style);
25218 
25219   verifyFormat("if (a + b >\n"
25220                "    c) {\n"
25221                "  f();\n"
25222                "}",
25223                "if (a + b > c)\n"
25224                "  f();",
25225                Style);
25226 }
25227 
TEST_F(FormatTest,RemoveBraces)25228 TEST_F(FormatTest, RemoveBraces) {
25229   FormatStyle Style = getLLVMStyle();
25230   Style.RemoveBracesLLVM = true;
25231 
25232   // The following test cases are fully-braced versions of the examples at
25233   // "llvm.org/docs/CodingStandards.html#don-t-use-braces-on-simple-single-
25234   // statement-bodies-of-if-else-loop-statements".
25235 
25236   // Omit the braces since the body is simple and clearly associated with the
25237   // `if`.
25238   verifyFormat("if (isa<FunctionDecl>(D))\n"
25239                "  handleFunctionDecl(D);\n"
25240                "else if (isa<VarDecl>(D))\n"
25241                "  handleVarDecl(D);",
25242                "if (isa<FunctionDecl>(D)) {\n"
25243                "  handleFunctionDecl(D);\n"
25244                "} else if (isa<VarDecl>(D)) {\n"
25245                "  handleVarDecl(D);\n"
25246                "}",
25247                Style);
25248 
25249   // Here we document the condition itself and not the body.
25250   verifyFormat("if (isa<VarDecl>(D)) {\n"
25251                "  // It is necessary that we explain the situation with this\n"
25252                "  // surprisingly long comment, so it would be unclear\n"
25253                "  // without the braces whether the following statement is in\n"
25254                "  // the scope of the `if`.\n"
25255                "  // Because the condition is documented, we can't really\n"
25256                "  // hoist this comment that applies to the body above the\n"
25257                "  // `if`.\n"
25258                "  handleOtherDecl(D);\n"
25259                "}",
25260                Style);
25261 
25262   // Use braces on the outer `if` to avoid a potential dangling `else`
25263   // situation.
25264   verifyFormat("if (isa<VarDecl>(D)) {\n"
25265                "  if (shouldProcessAttr(A))\n"
25266                "    handleAttr(A);\n"
25267                "}",
25268                "if (isa<VarDecl>(D)) {\n"
25269                "  if (shouldProcessAttr(A)) {\n"
25270                "    handleAttr(A);\n"
25271                "  }\n"
25272                "}",
25273                Style);
25274 
25275   // Use braces for the `if` block to keep it uniform with the `else` block.
25276   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25277                "  handleFunctionDecl(D);\n"
25278                "} else {\n"
25279                "  // In this `else` case, it is necessary that we explain the\n"
25280                "  // situation with this surprisingly long comment, so it\n"
25281                "  // would be unclear without the braces whether the\n"
25282                "  // following statement is in the scope of the `if`.\n"
25283                "  handleOtherDecl(D);\n"
25284                "}",
25285                Style);
25286 
25287   // This should also omit braces. The `for` loop contains only a single
25288   // statement, so it shouldn't have braces.  The `if` also only contains a
25289   // single simple statement (the `for` loop), so it also should omit braces.
25290   verifyFormat("if (isa<FunctionDecl>(D))\n"
25291                "  for (auto *A : D.attrs())\n"
25292                "    handleAttr(A);",
25293                "if (isa<FunctionDecl>(D)) {\n"
25294                "  for (auto *A : D.attrs()) {\n"
25295                "    handleAttr(A);\n"
25296                "  }\n"
25297                "}",
25298                Style);
25299 
25300   // Use braces for a `do-while` loop and its enclosing statement.
25301   verifyFormat("if (Tok->is(tok::l_brace)) {\n"
25302                "  do {\n"
25303                "    Tok = Tok->Next;\n"
25304                "  } while (Tok);\n"
25305                "}",
25306                Style);
25307 
25308   // Use braces for the outer `if` since the nested `for` is braced.
25309   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25310                "  for (auto *A : D.attrs()) {\n"
25311                "    // In this `for` loop body, it is necessary that we\n"
25312                "    // explain the situation with this surprisingly long\n"
25313                "    // comment, forcing braces on the `for` block.\n"
25314                "    handleAttr(A);\n"
25315                "  }\n"
25316                "}",
25317                Style);
25318 
25319   // Use braces on the outer block because there are more than two levels of
25320   // nesting.
25321   verifyFormat("if (isa<FunctionDecl>(D)) {\n"
25322                "  for (auto *A : D.attrs())\n"
25323                "    for (ssize_t i : llvm::seq<ssize_t>(count))\n"
25324                "      handleAttrOnDecl(D, A, i);\n"
25325                "}",
25326                "if (isa<FunctionDecl>(D)) {\n"
25327                "  for (auto *A : D.attrs()) {\n"
25328                "    for (ssize_t i : llvm::seq<ssize_t>(count)) {\n"
25329                "      handleAttrOnDecl(D, A, i);\n"
25330                "    }\n"
25331                "  }\n"
25332                "}",
25333                Style);
25334 
25335   // Use braces on the outer block because of a nested `if`; otherwise the
25336   // compiler would warn: `add explicit braces to avoid dangling else`
25337   verifyFormat("if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25338                "  if (shouldProcess(D))\n"
25339                "    handleVarDecl(D);\n"
25340                "  else\n"
25341                "    markAsIgnored(D);\n"
25342                "}",
25343                "if (auto *D = dyn_cast<FunctionDecl>(D)) {\n"
25344                "  if (shouldProcess(D)) {\n"
25345                "    handleVarDecl(D);\n"
25346                "  } else {\n"
25347                "    markAsIgnored(D);\n"
25348                "  }\n"
25349                "}",
25350                Style);
25351 
25352   verifyFormat("// clang-format off\n"
25353                "// comment\n"
25354                "while (i > 0) { --i; }\n"
25355                "// clang-format on\n"
25356                "while (j < 0)\n"
25357                "  ++j;",
25358                "// clang-format off\n"
25359                "// comment\n"
25360                "while (i > 0) { --i; }\n"
25361                "// clang-format on\n"
25362                "while (j < 0) { ++j; }",
25363                Style);
25364 
25365   verifyFormat("if (a)\n"
25366                "  b; // comment\n"
25367                "else if (c)\n"
25368                "  d; /* comment */\n"
25369                "else\n"
25370                "  e;",
25371                "if (a) {\n"
25372                "  b; // comment\n"
25373                "} else if (c) {\n"
25374                "  d; /* comment */\n"
25375                "} else {\n"
25376                "  e;\n"
25377                "}",
25378                Style);
25379 
25380   verifyFormat("if (a) {\n"
25381                "  b;\n"
25382                "  c;\n"
25383                "} else if (d) {\n"
25384                "  e;\n"
25385                "}",
25386                Style);
25387 
25388   verifyFormat("if (a) {\n"
25389                "#undef NDEBUG\n"
25390                "  b;\n"
25391                "} else {\n"
25392                "  c;\n"
25393                "}",
25394                Style);
25395 
25396   verifyFormat("if (a) {\n"
25397                "  // comment\n"
25398                "} else if (b) {\n"
25399                "  c;\n"
25400                "}",
25401                Style);
25402 
25403   verifyFormat("if (a) {\n"
25404                "  b;\n"
25405                "} else {\n"
25406                "  { c; }\n"
25407                "}",
25408                Style);
25409 
25410   verifyFormat("if (a) {\n"
25411                "  if (b) // comment\n"
25412                "    c;\n"
25413                "} else if (d) {\n"
25414                "  e;\n"
25415                "}",
25416                "if (a) {\n"
25417                "  if (b) { // comment\n"
25418                "    c;\n"
25419                "  }\n"
25420                "} else if (d) {\n"
25421                "  e;\n"
25422                "}",
25423                Style);
25424 
25425   verifyFormat("if (a) {\n"
25426                "  if (b) {\n"
25427                "    c;\n"
25428                "    // comment\n"
25429                "  } else if (d) {\n"
25430                "    e;\n"
25431                "  }\n"
25432                "}",
25433                Style);
25434 
25435   verifyFormat("if (a) {\n"
25436                "  if (b)\n"
25437                "    c;\n"
25438                "}",
25439                "if (a) {\n"
25440                "  if (b) {\n"
25441                "    c;\n"
25442                "  }\n"
25443                "}",
25444                Style);
25445 
25446   verifyFormat("if (a)\n"
25447                "  if (b)\n"
25448                "    c;\n"
25449                "  else\n"
25450                "    d;\n"
25451                "else\n"
25452                "  e;",
25453                "if (a) {\n"
25454                "  if (b) {\n"
25455                "    c;\n"
25456                "  } else {\n"
25457                "    d;\n"
25458                "  }\n"
25459                "} else {\n"
25460                "  e;\n"
25461                "}",
25462                Style);
25463 
25464   verifyFormat("if (a) {\n"
25465                "  // comment\n"
25466                "  if (b)\n"
25467                "    c;\n"
25468                "  else if (d)\n"
25469                "    e;\n"
25470                "} else {\n"
25471                "  g;\n"
25472                "}",
25473                "if (a) {\n"
25474                "  // comment\n"
25475                "  if (b) {\n"
25476                "    c;\n"
25477                "  } else if (d) {\n"
25478                "    e;\n"
25479                "  }\n"
25480                "} else {\n"
25481                "  g;\n"
25482                "}",
25483                Style);
25484 
25485   verifyFormat("if (a)\n"
25486                "  b;\n"
25487                "else if (c)\n"
25488                "  d;\n"
25489                "else\n"
25490                "  e;",
25491                "if (a) {\n"
25492                "  b;\n"
25493                "} else {\n"
25494                "  if (c) {\n"
25495                "    d;\n"
25496                "  } else {\n"
25497                "    e;\n"
25498                "  }\n"
25499                "}",
25500                Style);
25501 
25502   verifyFormat("if (a) {\n"
25503                "  if (b)\n"
25504                "    c;\n"
25505                "  else if (d)\n"
25506                "    e;\n"
25507                "} else {\n"
25508                "  g;\n"
25509                "}",
25510                "if (a) {\n"
25511                "  if (b)\n"
25512                "    c;\n"
25513                "  else {\n"
25514                "    if (d)\n"
25515                "      e;\n"
25516                "  }\n"
25517                "} else {\n"
25518                "  g;\n"
25519                "}",
25520                Style);
25521 
25522   verifyFormat("if (isa<VarDecl>(D)) {\n"
25523                "  for (auto *A : D.attrs())\n"
25524                "    if (shouldProcessAttr(A))\n"
25525                "      handleAttr(A);\n"
25526                "}",
25527                "if (isa<VarDecl>(D)) {\n"
25528                "  for (auto *A : D.attrs()) {\n"
25529                "    if (shouldProcessAttr(A)) {\n"
25530                "      handleAttr(A);\n"
25531                "    }\n"
25532                "  }\n"
25533                "}",
25534                Style);
25535 
25536   verifyFormat("do {\n"
25537                "  ++I;\n"
25538                "} while (hasMore() && Filter(*I));",
25539                "do { ++I; } while (hasMore() && Filter(*I));", Style);
25540 
25541   verifyFormat("if (a)\n"
25542                "  if (b)\n"
25543                "    c;\n"
25544                "  else {\n"
25545                "    if (d)\n"
25546                "      e;\n"
25547                "  }\n"
25548                "else\n"
25549                "  f;",
25550                Style);
25551 
25552   verifyFormat("if (a)\n"
25553                "  if (b)\n"
25554                "    c;\n"
25555                "  else {\n"
25556                "    if (d)\n"
25557                "      e;\n"
25558                "    else if (f)\n"
25559                "      g;\n"
25560                "  }\n"
25561                "else\n"
25562                "  h;",
25563                Style);
25564 
25565   verifyFormat("if (a) {\n"
25566                "  b;\n"
25567                "} else if (c) {\n"
25568                "  d;\n"
25569                "  e;\n"
25570                "}",
25571                "if (a) {\n"
25572                "  b;\n"
25573                "} else {\n"
25574                "  if (c) {\n"
25575                "    d;\n"
25576                "    e;\n"
25577                "  }\n"
25578                "}",
25579                Style);
25580 
25581   verifyFormat("if (a) {\n"
25582                "  b;\n"
25583                "  c;\n"
25584                "} else if (d) {\n"
25585                "  e;\n"
25586                "  f;\n"
25587                "}",
25588                "if (a) {\n"
25589                "  b;\n"
25590                "  c;\n"
25591                "} else {\n"
25592                "  if (d) {\n"
25593                "    e;\n"
25594                "    f;\n"
25595                "  }\n"
25596                "}",
25597                Style);
25598 
25599   verifyFormat("if (a) {\n"
25600                "  b;\n"
25601                "} else if (c) {\n"
25602                "  d;\n"
25603                "} else {\n"
25604                "  e;\n"
25605                "  f;\n"
25606                "}",
25607                "if (a) {\n"
25608                "  b;\n"
25609                "} else {\n"
25610                "  if (c) {\n"
25611                "    d;\n"
25612                "  } else {\n"
25613                "    e;\n"
25614                "    f;\n"
25615                "  }\n"
25616                "}",
25617                Style);
25618 
25619   verifyFormat("if (a) {\n"
25620                "  b;\n"
25621                "} else if (c) {\n"
25622                "  d;\n"
25623                "} else if (e) {\n"
25624                "  f;\n"
25625                "  g;\n"
25626                "}",
25627                "if (a) {\n"
25628                "  b;\n"
25629                "} else {\n"
25630                "  if (c) {\n"
25631                "    d;\n"
25632                "  } else if (e) {\n"
25633                "    f;\n"
25634                "    g;\n"
25635                "  }\n"
25636                "}",
25637                Style);
25638 
25639   verifyFormat("if (a) {\n"
25640                "  if (b)\n"
25641                "    c;\n"
25642                "  else if (d) {\n"
25643                "    e;\n"
25644                "    f;\n"
25645                "  }\n"
25646                "} else {\n"
25647                "  g;\n"
25648                "}",
25649                "if (a) {\n"
25650                "  if (b)\n"
25651                "    c;\n"
25652                "  else {\n"
25653                "    if (d) {\n"
25654                "      e;\n"
25655                "      f;\n"
25656                "    }\n"
25657                "  }\n"
25658                "} else {\n"
25659                "  g;\n"
25660                "}",
25661                Style);
25662 
25663   verifyFormat("if (a)\n"
25664                "  if (b)\n"
25665                "    c;\n"
25666                "  else {\n"
25667                "    if (d) {\n"
25668                "      e;\n"
25669                "      f;\n"
25670                "    }\n"
25671                "  }\n"
25672                "else\n"
25673                "  g;",
25674                Style);
25675 
25676   verifyFormat("if (a) {\n"
25677                "  b;\n"
25678                "  c;\n"
25679                "} else { // comment\n"
25680                "  if (d) {\n"
25681                "    e;\n"
25682                "    f;\n"
25683                "  }\n"
25684                "}",
25685                Style);
25686 
25687   verifyFormat("if (a)\n"
25688                "  b;\n"
25689                "else if (c)\n"
25690                "  while (d)\n"
25691                "    e;\n"
25692                "// comment",
25693                "if (a)\n"
25694                "{\n"
25695                "  b;\n"
25696                "} else if (c) {\n"
25697                "  while (d) {\n"
25698                "    e;\n"
25699                "  }\n"
25700                "}\n"
25701                "// comment",
25702                Style);
25703 
25704   verifyFormat("if (a) {\n"
25705                "  b;\n"
25706                "} else if (c) {\n"
25707                "  d;\n"
25708                "} else {\n"
25709                "  e;\n"
25710                "  g;\n"
25711                "}",
25712                Style);
25713 
25714   verifyFormat("if (a) {\n"
25715                "  b;\n"
25716                "} else if (c) {\n"
25717                "  d;\n"
25718                "} else {\n"
25719                "  e;\n"
25720                "} // comment",
25721                Style);
25722 
25723   verifyFormat("int abs = [](int i) {\n"
25724                "  if (i >= 0)\n"
25725                "    return i;\n"
25726                "  return -i;\n"
25727                "};",
25728                "int abs = [](int i) {\n"
25729                "  if (i >= 0) {\n"
25730                "    return i;\n"
25731                "  }\n"
25732                "  return -i;\n"
25733                "};",
25734                Style);
25735 
25736   verifyFormat("if (a)\n"
25737                "  foo();\n"
25738                "else\n"
25739                "  bar();",
25740                "if (a)\n"
25741                "{\n"
25742                "  foo();\n"
25743                "}\n"
25744                "else\n"
25745                "{\n"
25746                "  bar();\n"
25747                "}",
25748                Style);
25749 
25750   verifyFormat("if (a)\n"
25751                "  foo();\n"
25752                "// comment\n"
25753                "else\n"
25754                "  bar();",
25755                "if (a) {\n"
25756                "  foo();\n"
25757                "}\n"
25758                "// comment\n"
25759                "else {\n"
25760                "  bar();\n"
25761                "}",
25762                Style);
25763 
25764   verifyFormat("if (a) {\n"
25765                "  if (b)\n"
25766                "    c = 1; // comment\n"
25767                "}",
25768                "if (a) {\n"
25769                "  if (b) {\n"
25770                "    c = 1; // comment\n"
25771                "  }\n"
25772                "}",
25773                Style);
25774 
25775   verifyFormat("if (a) {\n"
25776                "Label:\n"
25777                "}",
25778                Style);
25779 
25780   verifyFormat("if (a) {\n"
25781                "Label:\n"
25782                "  f();\n"
25783                "}",
25784                Style);
25785 
25786   verifyFormat("if (a) {\n"
25787                "  f();\n"
25788                "Label:\n"
25789                "}",
25790                Style);
25791 
25792   verifyFormat("if consteval {\n"
25793                "  f();\n"
25794                "} else {\n"
25795                "  g();\n"
25796                "}",
25797                Style);
25798 
25799   verifyFormat("if not consteval {\n"
25800                "  f();\n"
25801                "} else if (a) {\n"
25802                "  g();\n"
25803                "}",
25804                Style);
25805 
25806   verifyFormat("if !consteval {\n"
25807                "  g();\n"
25808                "}",
25809                Style);
25810 
25811   Style.ColumnLimit = 65;
25812   verifyFormat("if (condition) {\n"
25813                "  ff(Indices,\n"
25814                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25815                "} else {\n"
25816                "  ff(Indices,\n"
25817                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25818                "}",
25819                Style);
25820 
25821   Style.ColumnLimit = 20;
25822 
25823   verifyFormat("int i;\n"
25824                "#define FOO(a, b)  \\\n"
25825                "  while (a) {      \\\n"
25826                "    b;             \\\n"
25827                "  }",
25828                Style);
25829 
25830   verifyFormat("int ab = [](int i) {\n"
25831                "  if (i > 0) {\n"
25832                "    i = 12345678 -\n"
25833                "        i;\n"
25834                "  }\n"
25835                "  return i;\n"
25836                "};",
25837                Style);
25838 
25839   verifyFormat("if (a) {\n"
25840                "  b = c + // 1 -\n"
25841                "      d;\n"
25842                "}",
25843                Style);
25844 
25845   verifyFormat("if (a) {\n"
25846                "  b = c >= 0 ? d\n"
25847                "             : e;\n"
25848                "}",
25849                "if (a) {\n"
25850                "  b = c >= 0 ? d : e;\n"
25851                "}",
25852                Style);
25853 
25854   verifyFormat("if (a)\n"
25855                "  b = c > 0 ? d : e;",
25856                "if (a) {\n"
25857                "  b = c > 0 ? d : e;\n"
25858                "}",
25859                Style);
25860 
25861   verifyFormat("if (-b >=\n"
25862                "    c) { // Keep.\n"
25863                "  foo();\n"
25864                "} else {\n"
25865                "  bar();\n"
25866                "}",
25867                "if (-b >= c) { // Keep.\n"
25868                "  foo();\n"
25869                "} else {\n"
25870                "  bar();\n"
25871                "}",
25872                Style);
25873 
25874   verifyFormat("if (a) /* Remove. */\n"
25875                "  f();\n"
25876                "else\n"
25877                "  g();",
25878                "if (a) <% /* Remove. */\n"
25879                "  f();\n"
25880                "%> else <%\n"
25881                "  g();\n"
25882                "%>",
25883                Style);
25884 
25885   verifyFormat("while (\n"
25886                "    !i--) <% // Keep.\n"
25887                "  foo();\n"
25888                "%>",
25889                "while (!i--) <% // Keep.\n"
25890                "  foo();\n"
25891                "%>",
25892                Style);
25893 
25894   verifyFormat("for (int &i : chars)\n"
25895                "  ++i;",
25896                "for (int &i :\n"
25897                "     chars) {\n"
25898                "  ++i;\n"
25899                "}",
25900                Style);
25901 
25902   verifyFormat("if (a)\n"
25903                "  b;\n"
25904                "else if (c) {\n"
25905                "  d;\n"
25906                "  e;\n"
25907                "} else\n"
25908                "  f = g(foo, bar,\n"
25909                "        baz);",
25910                "if (a)\n"
25911                "  b;\n"
25912                "else {\n"
25913                "  if (c) {\n"
25914                "    d;\n"
25915                "    e;\n"
25916                "  } else\n"
25917                "    f = g(foo, bar, baz);\n"
25918                "}",
25919                Style);
25920 
25921   Style.ColumnLimit = 0;
25922   verifyFormat("if (a)\n"
25923                "  b234567890223456789032345678904234567890 = "
25924                "c234567890223456789032345678904234567890;",
25925                "if (a) {\n"
25926                "  b234567890223456789032345678904234567890 = "
25927                "c234567890223456789032345678904234567890;\n"
25928                "}",
25929                Style);
25930 
25931   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
25932   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
25933   Style.BraceWrapping.BeforeElse = true;
25934 
25935   Style.ColumnLimit = 65;
25936 
25937   verifyFormat("if (condition)\n"
25938                "{\n"
25939                "  ff(Indices,\n"
25940                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25941                "}\n"
25942                "else\n"
25943                "{\n"
25944                "  ff(Indices,\n"
25945                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25946                "}",
25947                "if (condition) {\n"
25948                "  ff(Indices,\n"
25949                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25950                "} else {\n"
25951                "  ff(Indices,\n"
25952                "     [&](unsigned LHSI, unsigned RHSI) { return true; });\n"
25953                "}",
25954                Style);
25955 
25956   verifyFormat("if (a)\n"
25957                "{ //\n"
25958                "  foo();\n"
25959                "}",
25960                "if (a) { //\n"
25961                "  foo();\n"
25962                "}",
25963                Style);
25964 
25965   Style.ColumnLimit = 20;
25966 
25967   verifyFormat("int ab = [](int i) {\n"
25968                "  if (i > 0)\n"
25969                "  {\n"
25970                "    i = 12345678 -\n"
25971                "        i;\n"
25972                "  }\n"
25973                "  return i;\n"
25974                "};",
25975                "int ab = [](int i) {\n"
25976                "  if (i > 0) {\n"
25977                "    i = 12345678 -\n"
25978                "        i;\n"
25979                "  }\n"
25980                "  return i;\n"
25981                "};",
25982                Style);
25983 
25984   verifyFormat("if (a)\n"
25985                "{\n"
25986                "  b = c + // 1 -\n"
25987                "      d;\n"
25988                "}",
25989                "if (a) {\n"
25990                "  b = c + // 1 -\n"
25991                "      d;\n"
25992                "}",
25993                Style);
25994 
25995   verifyFormat("if (a)\n"
25996                "{\n"
25997                "  b = c >= 0 ? d\n"
25998                "             : e;\n"
25999                "}",
26000                "if (a) {\n"
26001                "  b = c >= 0 ? d : e;\n"
26002                "}",
26003                Style);
26004 
26005   verifyFormat("if (a)\n"
26006                "  b = c > 0 ? d : e;",
26007                "if (a)\n"
26008                "{\n"
26009                "  b = c > 0 ? d : e;\n"
26010                "}",
26011                Style);
26012 
26013   verifyFormat("if (foo + bar <=\n"
26014                "    baz)\n"
26015                "{\n"
26016                "  func(arg1, arg2);\n"
26017                "}",
26018                "if (foo + bar <= baz) {\n"
26019                "  func(arg1, arg2);\n"
26020                "}",
26021                Style);
26022 
26023   verifyFormat("if (foo + bar < baz)\n"
26024                "  func(arg1, arg2);\n"
26025                "else\n"
26026                "  func();",
26027                "if (foo + bar < baz)\n"
26028                "<%\n"
26029                "  func(arg1, arg2);\n"
26030                "%>\n"
26031                "else\n"
26032                "<%\n"
26033                "  func();\n"
26034                "%>",
26035                Style);
26036 
26037   verifyFormat("while (i--)\n"
26038                "<% // Keep.\n"
26039                "  foo();\n"
26040                "%>",
26041                "while (i--) <% // Keep.\n"
26042                "  foo();\n"
26043                "%>",
26044                Style);
26045 
26046   verifyFormat("for (int &i : chars)\n"
26047                "  ++i;",
26048                "for (int &i : chars)\n"
26049                "{\n"
26050                "  ++i;\n"
26051                "}",
26052                Style);
26053 }
26054 
TEST_F(FormatTest,AlignAfterOpenBracketBlockIndent)26055 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndent) {
26056   auto Style = getLLVMStyle();
26057 
26058   StringRef Short = "functionCall(paramA, paramB, paramC);\n"
26059                     "void functionDecl(int a, int b, int c);";
26060 
26061   StringRef Medium = "functionCall(paramA, paramB, paramC, paramD, paramE, "
26062                      "paramF, paramG, paramH, paramI);\n"
26063                      "void functionDecl(int argumentA, int argumentB, int "
26064                      "argumentC, int argumentD, int argumentE);";
26065 
26066   verifyFormat(Short, Style);
26067 
26068   StringRef NoBreak = "functionCall(paramA, paramB, paramC, paramD, paramE, "
26069                       "paramF, paramG, paramH,\n"
26070                       "             paramI);\n"
26071                       "void functionDecl(int argumentA, int argumentB, int "
26072                       "argumentC, int argumentD,\n"
26073                       "                  int argumentE);";
26074 
26075   verifyFormat(NoBreak, Medium, Style);
26076   verifyFormat(NoBreak,
26077                "functionCall(\n"
26078                "    paramA,\n"
26079                "    paramB,\n"
26080                "    paramC,\n"
26081                "    paramD,\n"
26082                "    paramE,\n"
26083                "    paramF,\n"
26084                "    paramG,\n"
26085                "    paramH,\n"
26086                "    paramI\n"
26087                ");\n"
26088                "void functionDecl(\n"
26089                "    int argumentA,\n"
26090                "    int argumentB,\n"
26091                "    int argumentC,\n"
26092                "    int argumentD,\n"
26093                "    int argumentE\n"
26094                ");",
26095                Style);
26096 
26097   verifyFormat("outerFunctionCall(nestedFunctionCall(argument1),\n"
26098                "                  nestedLongFunctionCall(argument1, "
26099                "argument2, argument3,\n"
26100                "                                         argument4, "
26101                "argument5));",
26102                Style);
26103 
26104   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
26105 
26106   verifyFormat(Short, Style);
26107   verifyFormat(
26108       "functionCall(\n"
26109       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
26110       "paramI\n"
26111       ");\n"
26112       "void functionDecl(\n"
26113       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
26114       "argumentE\n"
26115       ");",
26116       Medium, Style);
26117 
26118   Style.AllowAllArgumentsOnNextLine = false;
26119   Style.AllowAllParametersOfDeclarationOnNextLine = false;
26120 
26121   verifyFormat(Short, Style);
26122   verifyFormat(
26123       "functionCall(\n"
26124       "    paramA, paramB, paramC, paramD, paramE, paramF, paramG, paramH, "
26125       "paramI\n"
26126       ");\n"
26127       "void functionDecl(\n"
26128       "    int argumentA, int argumentB, int argumentC, int argumentD, int "
26129       "argumentE\n"
26130       ");",
26131       Medium, Style);
26132 
26133   Style.BinPackArguments = false;
26134   Style.BinPackParameters = false;
26135 
26136   verifyFormat(Short, Style);
26137 
26138   verifyFormat("functionCall(\n"
26139                "    paramA,\n"
26140                "    paramB,\n"
26141                "    paramC,\n"
26142                "    paramD,\n"
26143                "    paramE,\n"
26144                "    paramF,\n"
26145                "    paramG,\n"
26146                "    paramH,\n"
26147                "    paramI\n"
26148                ");\n"
26149                "void functionDecl(\n"
26150                "    int argumentA,\n"
26151                "    int argumentB,\n"
26152                "    int argumentC,\n"
26153                "    int argumentD,\n"
26154                "    int argumentE\n"
26155                ");",
26156                Medium, Style);
26157 
26158   verifyFormat("outerFunctionCall(\n"
26159                "    nestedFunctionCall(argument1),\n"
26160                "    nestedLongFunctionCall(\n"
26161                "        argument1,\n"
26162                "        argument2,\n"
26163                "        argument3,\n"
26164                "        argument4,\n"
26165                "        argument5\n"
26166                "    )\n"
26167                ");",
26168                Style);
26169 
26170   verifyFormat("int a = (int)b;", Style);
26171   verifyFormat("int a = (int)b;",
26172                "int a = (\n"
26173                "    int\n"
26174                ") b;",
26175                Style);
26176 
26177   verifyFormat("return (true);", Style);
26178   verifyFormat("return (true);",
26179                "return (\n"
26180                "    true\n"
26181                ");",
26182                Style);
26183 
26184   verifyFormat("void foo();", Style);
26185   verifyFormat("void foo();",
26186                "void foo(\n"
26187                ");",
26188                Style);
26189 
26190   verifyFormat("void foo() {}", Style);
26191   verifyFormat("void foo() {}",
26192                "void foo(\n"
26193                ") {\n"
26194                "}",
26195                Style);
26196 
26197   verifyFormat("auto string = std::string();", Style);
26198   verifyFormat("auto string = std::string();",
26199                "auto string = std::string(\n"
26200                ");",
26201                Style);
26202 
26203   verifyFormat("void (*functionPointer)() = nullptr;", Style);
26204   verifyFormat("void (*functionPointer)() = nullptr;",
26205                "void (\n"
26206                "    *functionPointer\n"
26207                ")\n"
26208                "(\n"
26209                ") = nullptr;",
26210                Style);
26211 }
26212 
TEST_F(FormatTest,AlignAfterOpenBracketBlockIndentIfStatement)26213 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentIfStatement) {
26214   auto Style = getLLVMStyle();
26215 
26216   verifyFormat("if (foo()) {\n"
26217                "  return;\n"
26218                "}",
26219                Style);
26220 
26221   verifyFormat("if (quitelongarg !=\n"
26222                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
26223                "comment\n"
26224                "  return;\n"
26225                "}",
26226                Style);
26227 
26228   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
26229 
26230   verifyFormat("if (foo()) {\n"
26231                "  return;\n"
26232                "}",
26233                Style);
26234 
26235   verifyFormat("if (quitelongarg !=\n"
26236                "    (alsolongarg - 1)) { // ABC is a very longgggggggggggg "
26237                "comment\n"
26238                "  return;\n"
26239                "}",
26240                Style);
26241 }
26242 
TEST_F(FormatTest,AlignAfterOpenBracketBlockIndentForStatement)26243 TEST_F(FormatTest, AlignAfterOpenBracketBlockIndentForStatement) {
26244   auto Style = getLLVMStyle();
26245 
26246   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
26247                "  doSomething();\n"
26248                "}",
26249                Style);
26250 
26251   verifyFormat("for (int myReallyLongCountVariable = 0; "
26252                "myReallyLongCountVariable < count;\n"
26253                "     myReallyLongCountVariable++) {\n"
26254                "  doSomething();\n"
26255                "}",
26256                Style);
26257 
26258   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
26259 
26260   verifyFormat("for (int i = 0; i < 5; ++i) {\n"
26261                "  doSomething();\n"
26262                "}",
26263                Style);
26264 
26265   verifyFormat("for (int myReallyLongCountVariable = 0; "
26266                "myReallyLongCountVariable < count;\n"
26267                "     myReallyLongCountVariable++) {\n"
26268                "  doSomething();\n"
26269                "}",
26270                Style);
26271 }
26272 
TEST_F(FormatTest,UnderstandsDigraphs)26273 TEST_F(FormatTest, UnderstandsDigraphs) {
26274   verifyFormat("int arr<:5:> = {};");
26275   verifyFormat("int arr[5] = <%%>;");
26276   verifyFormat("int arr<:::qualified_variable:> = {};");
26277   verifyFormat("int arr[::qualified_variable] = <%%>;");
26278   verifyFormat("%:include <header>");
26279   verifyFormat("%:define A x##y");
26280   verifyFormat("#define A x%:%:y");
26281 }
26282 
TEST_F(FormatTest,AlignArrayOfStructuresLeftAlignmentNonSquare)26283 TEST_F(FormatTest, AlignArrayOfStructuresLeftAlignmentNonSquare) {
26284   auto Style = getLLVMStyle();
26285   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
26286   Style.AlignConsecutiveAssignments.Enabled = true;
26287   Style.AlignConsecutiveDeclarations.Enabled = true;
26288 
26289   // The AlignArray code is incorrect for non square Arrays and can cause
26290   // crashes, these tests assert that the array is not changed but will
26291   // also act as regression tests for when it is properly fixed
26292   verifyFormat("struct test demo[] = {\n"
26293                "    {1, 2},\n"
26294                "    {3, 4, 5},\n"
26295                "    {6, 7, 8}\n"
26296                "};",
26297                Style);
26298   verifyFormat("struct test demo[] = {\n"
26299                "    {1, 2, 3, 4, 5},\n"
26300                "    {3, 4, 5},\n"
26301                "    {6, 7, 8}\n"
26302                "};",
26303                Style);
26304   verifyFormat("struct test demo[] = {\n"
26305                "    {1, 2, 3, 4, 5},\n"
26306                "    {3, 4, 5},\n"
26307                "    {6, 7, 8, 9, 10, 11, 12}\n"
26308                "};",
26309                Style);
26310   verifyFormat("struct test demo[] = {\n"
26311                "    {1, 2, 3},\n"
26312                "    {3, 4, 5},\n"
26313                "    {6, 7, 8, 9, 10, 11, 12}\n"
26314                "};",
26315                Style);
26316 
26317   verifyFormat("S{\n"
26318                "    {},\n"
26319                "    {},\n"
26320                "    {a, b}\n"
26321                "};",
26322                Style);
26323   verifyFormat("S{\n"
26324                "    {},\n"
26325                "    {},\n"
26326                "    {a, b},\n"
26327                "};",
26328                Style);
26329   verifyFormat("void foo() {\n"
26330                "  auto thing = test{\n"
26331                "      {\n"
26332                "       {13}, {something}, // A\n"
26333                "      }\n"
26334                "  };\n"
26335                "}",
26336                "void foo() {\n"
26337                "  auto thing = test{\n"
26338                "      {\n"
26339                "       {13},\n"
26340                "       {something}, // A\n"
26341                "      }\n"
26342                "  };\n"
26343                "}",
26344                Style);
26345 }
26346 
TEST_F(FormatTest,AlignArrayOfStructuresRightAlignmentNonSquare)26347 TEST_F(FormatTest, AlignArrayOfStructuresRightAlignmentNonSquare) {
26348   auto Style = getLLVMStyle();
26349   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
26350   Style.AlignConsecutiveAssignments.Enabled = true;
26351   Style.AlignConsecutiveDeclarations.Enabled = true;
26352 
26353   // The AlignArray code is incorrect for non square Arrays and can cause
26354   // crashes, these tests assert that the array is not changed but will
26355   // also act as regression tests for when it is properly fixed
26356   verifyFormat("struct test demo[] = {\n"
26357                "    {1, 2},\n"
26358                "    {3, 4, 5},\n"
26359                "    {6, 7, 8}\n"
26360                "};",
26361                Style);
26362   verifyFormat("struct test demo[] = {\n"
26363                "    {1, 2, 3, 4, 5},\n"
26364                "    {3, 4, 5},\n"
26365                "    {6, 7, 8}\n"
26366                "};",
26367                Style);
26368   verifyFormat("struct test demo[] = {\n"
26369                "    {1, 2, 3, 4, 5},\n"
26370                "    {3, 4, 5},\n"
26371                "    {6, 7, 8, 9, 10, 11, 12}\n"
26372                "};",
26373                Style);
26374   verifyFormat("struct test demo[] = {\n"
26375                "    {1, 2, 3},\n"
26376                "    {3, 4, 5},\n"
26377                "    {6, 7, 8, 9, 10, 11, 12}\n"
26378                "};",
26379                Style);
26380 
26381   verifyFormat("S{\n"
26382                "    {},\n"
26383                "    {},\n"
26384                "    {a, b}\n"
26385                "};",
26386                Style);
26387   verifyFormat("S{\n"
26388                "    {},\n"
26389                "    {},\n"
26390                "    {a, b},\n"
26391                "};",
26392                Style);
26393   verifyFormat("void foo() {\n"
26394                "  auto thing = test{\n"
26395                "      {\n"
26396                "       {13}, {something}, // A\n"
26397                "      }\n"
26398                "  };\n"
26399                "}",
26400                "void foo() {\n"
26401                "  auto thing = test{\n"
26402                "      {\n"
26403                "       {13},\n"
26404                "       {something}, // A\n"
26405                "      }\n"
26406                "  };\n"
26407                "}",
26408                Style);
26409 }
26410 
TEST_F(FormatTest,FormatsVariableTemplates)26411 TEST_F(FormatTest, FormatsVariableTemplates) {
26412   verifyFormat("inline bool var = is_integral_v<int> && is_signed_v<int>;");
26413   verifyFormat("template <typename T> "
26414                "inline bool var = is_integral_v<T> && is_signed_v<T>;");
26415 }
26416 
26417 } // namespace
26418 } // namespace format
26419 } // namespace clang
26420