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 = clang::format::getLLVMStyle();
266   CustomStyle.BreakBeforeBraces = clang::format::FormatStyle::BS_Custom;
267   CustomStyle.BraceWrapping.AfterNamespace = true;
268   CustomStyle.KeepEmptyLinesAtTheStartOfBlocks = false;
269   EXPECT_EQ("namespace N\n"
270             "{\n"
271             "\n"
272             "int i;\n"
273             "}",
274             format("namespace N\n"
275                    "{\n"
276                    "\n"
277                    "\n"
278                    "int    i;\n"
279                    "}",
280                    CustomStyle));
281   EXPECT_EQ("/* something */ namespace N\n"
282             "{\n"
283             "\n"
284             "int i;\n"
285             "}",
286             format("/* something */ namespace N {\n"
287                    "\n"
288                    "\n"
289                    "int    i;\n"
290                    "}",
291                    CustomStyle));
292   EXPECT_EQ("inline namespace N\n"
293             "{\n"
294             "\n"
295             "int i;\n"
296             "}",
297             format("inline namespace N\n"
298                    "{\n"
299                    "\n"
300                    "\n"
301                    "int    i;\n"
302                    "}",
303                    CustomStyle));
304   EXPECT_EQ("/* something */ inline namespace N\n"
305             "{\n"
306             "\n"
307             "int i;\n"
308             "}",
309             format("/* something */ inline namespace N\n"
310                    "{\n"
311                    "\n"
312                    "int    i;\n"
313                    "}",
314                    CustomStyle));
315   EXPECT_EQ("export namespace N\n"
316             "{\n"
317             "\n"
318             "int i;\n"
319             "}",
320             format("export namespace N\n"
321                    "{\n"
322                    "\n"
323                    "int    i;\n"
324                    "}",
325                    CustomStyle));
326   EXPECT_EQ("namespace a\n"
327             "{\n"
328             "namespace b\n"
329             "{\n"
330             "\n"
331             "class AA {};\n"
332             "\n"
333             "} // namespace b\n"
334             "} // namespace a\n",
335             format("namespace a\n"
336                    "{\n"
337                    "namespace b\n"
338                    "{\n"
339                    "\n"
340                    "\n"
341                    "class AA {};\n"
342                    "\n"
343                    "\n"
344                    "}\n"
345                    "}\n",
346                    CustomStyle));
347   EXPECT_EQ("namespace A /* comment */\n"
348             "{\n"
349             "class B {}\n"
350             "} // namespace A",
351             format("namespace A /* comment */ { class B {} }", CustomStyle));
352   EXPECT_EQ("namespace A\n"
353             "{ /* comment */\n"
354             "class B {}\n"
355             "} // namespace A",
356             format("namespace A {/* comment */ class B {} }", CustomStyle));
357   EXPECT_EQ("namespace A\n"
358             "{ /* comment */\n"
359             "\n"
360             "class B {}\n"
361             "\n"
362             ""
363             "} // namespace A",
364             format("namespace A { /* comment */\n"
365                    "\n"
366                    "\n"
367                    "class B {}\n"
368                    "\n"
369                    "\n"
370                    "}",
371                    CustomStyle));
372   EXPECT_EQ("namespace A /* comment */\n"
373             "{\n"
374             "\n"
375             "class B {}\n"
376             "\n"
377             "} // namespace A",
378             format("namespace A/* comment */ {\n"
379                    "\n"
380                    "\n"
381                    "class B {}\n"
382                    "\n"
383                    "\n"
384                    "}",
385                    CustomStyle));
386 
387   // ...but do keep inlining and removing empty lines for non-block extern "C"
388   // functions.
389   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
390   EXPECT_EQ("extern \"C\" int f() {\n"
391             "  int i = 42;\n"
392             "  return i;\n"
393             "}",
394             format("extern \"C\" int f() {\n"
395                    "\n"
396                    "  int i = 42;\n"
397                    "  return i;\n"
398                    "}",
399                    getGoogleStyle()));
400 
401   // Remove empty lines at the beginning and end of blocks.
402   EXPECT_EQ("void f() {\n"
403             "\n"
404             "  if (a) {\n"
405             "\n"
406             "    f();\n"
407             "  }\n"
408             "}",
409             format("void f() {\n"
410                    "\n"
411                    "  if (a) {\n"
412                    "\n"
413                    "    f();\n"
414                    "\n"
415                    "  }\n"
416                    "\n"
417                    "}",
418                    getLLVMStyle()));
419   EXPECT_EQ("void f() {\n"
420             "  if (a) {\n"
421             "    f();\n"
422             "  }\n"
423             "}",
424             format("void f() {\n"
425                    "\n"
426                    "  if (a) {\n"
427                    "\n"
428                    "    f();\n"
429                    "\n"
430                    "  }\n"
431                    "\n"
432                    "}",
433                    getGoogleStyle()));
434 
435   // Don't remove empty lines in more complex control statements.
436   EXPECT_EQ("void f() {\n"
437             "  if (a) {\n"
438             "    f();\n"
439             "\n"
440             "  } else if (b) {\n"
441             "    f();\n"
442             "  }\n"
443             "}",
444             format("void f() {\n"
445                    "  if (a) {\n"
446                    "    f();\n"
447                    "\n"
448                    "  } else if (b) {\n"
449                    "    f();\n"
450                    "\n"
451                    "  }\n"
452                    "\n"
453                    "}"));
454 
455   // Don't remove empty lines before namespace endings.
456   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
457   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
458   EXPECT_EQ("namespace {\n"
459             "int i;\n"
460             "\n"
461             "}",
462             format("namespace {\n"
463                    "int i;\n"
464                    "\n"
465                    "}",
466                    LLVMWithNoNamespaceFix));
467   EXPECT_EQ("namespace {\n"
468             "int i;\n"
469             "}",
470             format("namespace {\n"
471                    "int i;\n"
472                    "}",
473                    LLVMWithNoNamespaceFix));
474   EXPECT_EQ("namespace {\n"
475             "int i;\n"
476             "\n"
477             "};",
478             format("namespace {\n"
479                    "int i;\n"
480                    "\n"
481                    "};",
482                    LLVMWithNoNamespaceFix));
483   EXPECT_EQ("namespace {\n"
484             "int i;\n"
485             "};",
486             format("namespace {\n"
487                    "int i;\n"
488                    "};",
489                    LLVMWithNoNamespaceFix));
490   EXPECT_EQ("namespace {\n"
491             "int i;\n"
492             "\n"
493             "}",
494             format("namespace {\n"
495                    "int i;\n"
496                    "\n"
497                    "}"));
498   EXPECT_EQ("namespace {\n"
499             "int i;\n"
500             "\n"
501             "} // namespace",
502             format("namespace {\n"
503                    "int i;\n"
504                    "\n"
505                    "}  // namespace"));
506 
507   FormatStyle Style = getLLVMStyle();
508   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
509   Style.MaxEmptyLinesToKeep = 2;
510   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
511   Style.BraceWrapping.AfterClass = true;
512   Style.BraceWrapping.AfterFunction = true;
513   Style.KeepEmptyLinesAtTheStartOfBlocks = false;
514 
515   EXPECT_EQ("class Foo\n"
516             "{\n"
517             "  Foo() {}\n"
518             "\n"
519             "  void funk() {}\n"
520             "};",
521             format("class Foo\n"
522                    "{\n"
523                    "  Foo()\n"
524                    "  {\n"
525                    "  }\n"
526                    "\n"
527                    "  void funk() {}\n"
528                    "};",
529                    Style));
530 }
531 
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 (a)\n"
587                "  g();");
588   verifyFormat("if (a) {\n"
589                "  g()\n"
590                "};");
591   verifyFormat("if (a)\n"
592                "  g();\n"
593                "else\n"
594                "  g();");
595   verifyFormat("if (a) {\n"
596                "  g();\n"
597                "} else\n"
598                "  g();");
599   verifyFormat("if (a)\n"
600                "  g();\n"
601                "else {\n"
602                "  g();\n"
603                "}");
604   verifyFormat("if (a) {\n"
605                "  g();\n"
606                "} else {\n"
607                "  g();\n"
608                "}");
609   verifyFormat("if (a)\n"
610                "  g();\n"
611                "else if (b)\n"
612                "  g();\n"
613                "else\n"
614                "  g();");
615   verifyFormat("if (a) {\n"
616                "  g();\n"
617                "} else if (b)\n"
618                "  g();\n"
619                "else\n"
620                "  g();");
621   verifyFormat("if (a)\n"
622                "  g();\n"
623                "else if (b) {\n"
624                "  g();\n"
625                "} else\n"
626                "  g();");
627   verifyFormat("if (a)\n"
628                "  g();\n"
629                "else if (b)\n"
630                "  g();\n"
631                "else {\n"
632                "  g();\n"
633                "}");
634   verifyFormat("if (a)\n"
635                "  g();\n"
636                "else if (b) {\n"
637                "  g();\n"
638                "} else {\n"
639                "  g();\n"
640                "}");
641   verifyFormat("if (a) {\n"
642                "  g();\n"
643                "} else if (b) {\n"
644                "  g();\n"
645                "} else {\n"
646                "  g();\n"
647                "}");
648 
649   FormatStyle AllowsMergedIf = getLLVMStyle();
650   AllowsMergedIf.IfMacros.push_back("MYIF");
651   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
652   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
653       FormatStyle::SIS_WithoutElse;
654   verifyFormat("if (a)\n"
655                "  // comment\n"
656                "  f();",
657                AllowsMergedIf);
658   verifyFormat("{\n"
659                "  if (a)\n"
660                "  label:\n"
661                "    f();\n"
662                "}",
663                AllowsMergedIf);
664   verifyFormat("#define A \\\n"
665                "  if (a)  \\\n"
666                "  label:  \\\n"
667                "    f()",
668                AllowsMergedIf);
669   verifyFormat("if (a)\n"
670                "  ;",
671                AllowsMergedIf);
672   verifyFormat("if (a)\n"
673                "  if (b) return;",
674                AllowsMergedIf);
675 
676   verifyFormat("if (a) // Can't merge this\n"
677                "  f();\n",
678                AllowsMergedIf);
679   verifyFormat("if (a) /* still don't merge */\n"
680                "  f();",
681                AllowsMergedIf);
682   verifyFormat("if (a) { // Never merge this\n"
683                "  f();\n"
684                "}",
685                AllowsMergedIf);
686   verifyFormat("if (a) { /* Never merge this */\n"
687                "  f();\n"
688                "}",
689                AllowsMergedIf);
690   verifyFormat("MYIF (a)\n"
691                "  // comment\n"
692                "  f();",
693                AllowsMergedIf);
694   verifyFormat("{\n"
695                "  MYIF (a)\n"
696                "  label:\n"
697                "    f();\n"
698                "}",
699                AllowsMergedIf);
700   verifyFormat("#define A  \\\n"
701                "  MYIF (a) \\\n"
702                "  label:   \\\n"
703                "    f()",
704                AllowsMergedIf);
705   verifyFormat("MYIF (a)\n"
706                "  ;",
707                AllowsMergedIf);
708   verifyFormat("MYIF (a)\n"
709                "  MYIF (b) return;",
710                AllowsMergedIf);
711 
712   verifyFormat("MYIF (a) // Can't merge this\n"
713                "  f();\n",
714                AllowsMergedIf);
715   verifyFormat("MYIF (a) /* still don't merge */\n"
716                "  f();",
717                AllowsMergedIf);
718   verifyFormat("MYIF (a) { // Never merge this\n"
719                "  f();\n"
720                "}",
721                AllowsMergedIf);
722   verifyFormat("MYIF (a) { /* Never merge this */\n"
723                "  f();\n"
724                "}",
725                AllowsMergedIf);
726 
727   AllowsMergedIf.ColumnLimit = 14;
728   // Where line-lengths matter, a 2-letter synonym that maintains line length.
729   // Not IF to avoid any confusion that IF is somehow special.
730   AllowsMergedIf.IfMacros.push_back("FI");
731   verifyFormat("if (a) return;", AllowsMergedIf);
732   verifyFormat("if (aaaaaaaaa)\n"
733                "  return;",
734                AllowsMergedIf);
735   verifyFormat("FI (a) return;", AllowsMergedIf);
736   verifyFormat("FI (aaaaaaaaa)\n"
737                "  return;",
738                AllowsMergedIf);
739 
740   AllowsMergedIf.ColumnLimit = 13;
741   verifyFormat("if (a)\n  return;", AllowsMergedIf);
742   verifyFormat("FI (a)\n  return;", AllowsMergedIf);
743 
744   FormatStyle AllowsMergedIfElse = getLLVMStyle();
745   AllowsMergedIfElse.IfMacros.push_back("MYIF");
746   AllowsMergedIfElse.AllowShortIfStatementsOnASingleLine =
747       FormatStyle::SIS_AllIfsAndElse;
748   verifyFormat("if (a)\n"
749                "  // comment\n"
750                "  f();\n"
751                "else\n"
752                "  // comment\n"
753                "  f();",
754                AllowsMergedIfElse);
755   verifyFormat("{\n"
756                "  if (a)\n"
757                "  label:\n"
758                "    f();\n"
759                "  else\n"
760                "  label:\n"
761                "    f();\n"
762                "}",
763                AllowsMergedIfElse);
764   verifyFormat("if (a)\n"
765                "  ;\n"
766                "else\n"
767                "  ;",
768                AllowsMergedIfElse);
769   verifyFormat("if (a) {\n"
770                "} else {\n"
771                "}",
772                AllowsMergedIfElse);
773   verifyFormat("if (a) return;\n"
774                "else if (b) return;\n"
775                "else return;",
776                AllowsMergedIfElse);
777   verifyFormat("if (a) {\n"
778                "} else return;",
779                AllowsMergedIfElse);
780   verifyFormat("if (a) {\n"
781                "} else if (b) return;\n"
782                "else return;",
783                AllowsMergedIfElse);
784   verifyFormat("if (a) return;\n"
785                "else if (b) {\n"
786                "} else return;",
787                AllowsMergedIfElse);
788   verifyFormat("if (a)\n"
789                "  if (b) return;\n"
790                "  else return;",
791                AllowsMergedIfElse);
792   verifyFormat("if constexpr (a)\n"
793                "  if constexpr (b) return;\n"
794                "  else if constexpr (c) return;\n"
795                "  else return;",
796                AllowsMergedIfElse);
797   verifyFormat("MYIF (a)\n"
798                "  // comment\n"
799                "  f();\n"
800                "else\n"
801                "  // comment\n"
802                "  f();",
803                AllowsMergedIfElse);
804   verifyFormat("{\n"
805                "  MYIF (a)\n"
806                "  label:\n"
807                "    f();\n"
808                "  else\n"
809                "  label:\n"
810                "    f();\n"
811                "}",
812                AllowsMergedIfElse);
813   verifyFormat("MYIF (a)\n"
814                "  ;\n"
815                "else\n"
816                "  ;",
817                AllowsMergedIfElse);
818   verifyFormat("MYIF (a) {\n"
819                "} else {\n"
820                "}",
821                AllowsMergedIfElse);
822   verifyFormat("MYIF (a) return;\n"
823                "else MYIF (b) return;\n"
824                "else return;",
825                AllowsMergedIfElse);
826   verifyFormat("MYIF (a) {\n"
827                "} else return;",
828                AllowsMergedIfElse);
829   verifyFormat("MYIF (a) {\n"
830                "} else MYIF (b) return;\n"
831                "else return;",
832                AllowsMergedIfElse);
833   verifyFormat("MYIF (a) return;\n"
834                "else MYIF (b) {\n"
835                "} else return;",
836                AllowsMergedIfElse);
837   verifyFormat("MYIF (a)\n"
838                "  MYIF (b) return;\n"
839                "  else return;",
840                AllowsMergedIfElse);
841   verifyFormat("MYIF constexpr (a)\n"
842                "  MYIF constexpr (b) return;\n"
843                "  else MYIF constexpr (c) return;\n"
844                "  else return;",
845                AllowsMergedIfElse);
846 }
847 
TEST_F(FormatTest,FormatIfWithoutCompoundStatementButElseWith)848 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
849   FormatStyle AllowsMergedIf = getLLVMStyle();
850   AllowsMergedIf.IfMacros.push_back("MYIF");
851   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
852   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
853       FormatStyle::SIS_WithoutElse;
854   verifyFormat("if (a)\n"
855                "  f();\n"
856                "else {\n"
857                "  g();\n"
858                "}",
859                AllowsMergedIf);
860   verifyFormat("if (a)\n"
861                "  f();\n"
862                "else\n"
863                "  g();\n",
864                AllowsMergedIf);
865 
866   verifyFormat("if (a) g();", AllowsMergedIf);
867   verifyFormat("if (a) {\n"
868                "  g()\n"
869                "};",
870                AllowsMergedIf);
871   verifyFormat("if (a)\n"
872                "  g();\n"
873                "else\n"
874                "  g();",
875                AllowsMergedIf);
876   verifyFormat("if (a) {\n"
877                "  g();\n"
878                "} else\n"
879                "  g();",
880                AllowsMergedIf);
881   verifyFormat("if (a)\n"
882                "  g();\n"
883                "else {\n"
884                "  g();\n"
885                "}",
886                AllowsMergedIf);
887   verifyFormat("if (a) {\n"
888                "  g();\n"
889                "} else {\n"
890                "  g();\n"
891                "}",
892                AllowsMergedIf);
893   verifyFormat("if (a)\n"
894                "  g();\n"
895                "else if (b)\n"
896                "  g();\n"
897                "else\n"
898                "  g();",
899                AllowsMergedIf);
900   verifyFormat("if (a) {\n"
901                "  g();\n"
902                "} else if (b)\n"
903                "  g();\n"
904                "else\n"
905                "  g();",
906                AllowsMergedIf);
907   verifyFormat("if (a)\n"
908                "  g();\n"
909                "else if (b) {\n"
910                "  g();\n"
911                "} else\n"
912                "  g();",
913                AllowsMergedIf);
914   verifyFormat("if (a)\n"
915                "  g();\n"
916                "else if (b)\n"
917                "  g();\n"
918                "else {\n"
919                "  g();\n"
920                "}",
921                AllowsMergedIf);
922   verifyFormat("if (a)\n"
923                "  g();\n"
924                "else if (b) {\n"
925                "  g();\n"
926                "} else {\n"
927                "  g();\n"
928                "}",
929                AllowsMergedIf);
930   verifyFormat("if (a) {\n"
931                "  g();\n"
932                "} else if (b) {\n"
933                "  g();\n"
934                "} else {\n"
935                "  g();\n"
936                "}",
937                AllowsMergedIf);
938   verifyFormat("MYIF (a)\n"
939                "  f();\n"
940                "else {\n"
941                "  g();\n"
942                "}",
943                AllowsMergedIf);
944   verifyFormat("MYIF (a)\n"
945                "  f();\n"
946                "else\n"
947                "  g();\n",
948                AllowsMergedIf);
949 
950   verifyFormat("MYIF (a) g();", AllowsMergedIf);
951   verifyFormat("MYIF (a) {\n"
952                "  g()\n"
953                "};",
954                AllowsMergedIf);
955   verifyFormat("MYIF (a)\n"
956                "  g();\n"
957                "else\n"
958                "  g();",
959                AllowsMergedIf);
960   verifyFormat("MYIF (a) {\n"
961                "  g();\n"
962                "} else\n"
963                "  g();",
964                AllowsMergedIf);
965   verifyFormat("MYIF (a)\n"
966                "  g();\n"
967                "else {\n"
968                "  g();\n"
969                "}",
970                AllowsMergedIf);
971   verifyFormat("MYIF (a) {\n"
972                "  g();\n"
973                "} else {\n"
974                "  g();\n"
975                "}",
976                AllowsMergedIf);
977   verifyFormat("MYIF (a)\n"
978                "  g();\n"
979                "else MYIF (b)\n"
980                "  g();\n"
981                "else\n"
982                "  g();",
983                AllowsMergedIf);
984   verifyFormat("MYIF (a)\n"
985                "  g();\n"
986                "else if (b)\n"
987                "  g();\n"
988                "else\n"
989                "  g();",
990                AllowsMergedIf);
991   verifyFormat("MYIF (a) {\n"
992                "  g();\n"
993                "} else MYIF (b)\n"
994                "  g();\n"
995                "else\n"
996                "  g();",
997                AllowsMergedIf);
998   verifyFormat("MYIF (a) {\n"
999                "  g();\n"
1000                "} else if (b)\n"
1001                "  g();\n"
1002                "else\n"
1003                "  g();",
1004                AllowsMergedIf);
1005   verifyFormat("MYIF (a)\n"
1006                "  g();\n"
1007                "else MYIF (b) {\n"
1008                "  g();\n"
1009                "} else\n"
1010                "  g();",
1011                AllowsMergedIf);
1012   verifyFormat("MYIF (a)\n"
1013                "  g();\n"
1014                "else if (b) {\n"
1015                "  g();\n"
1016                "} else\n"
1017                "  g();",
1018                AllowsMergedIf);
1019   verifyFormat("MYIF (a)\n"
1020                "  g();\n"
1021                "else MYIF (b)\n"
1022                "  g();\n"
1023                "else {\n"
1024                "  g();\n"
1025                "}",
1026                AllowsMergedIf);
1027   verifyFormat("MYIF (a)\n"
1028                "  g();\n"
1029                "else if (b)\n"
1030                "  g();\n"
1031                "else {\n"
1032                "  g();\n"
1033                "}",
1034                AllowsMergedIf);
1035   verifyFormat("MYIF (a)\n"
1036                "  g();\n"
1037                "else MYIF (b) {\n"
1038                "  g();\n"
1039                "} else {\n"
1040                "  g();\n"
1041                "}",
1042                AllowsMergedIf);
1043   verifyFormat("MYIF (a)\n"
1044                "  g();\n"
1045                "else if (b) {\n"
1046                "  g();\n"
1047                "} else {\n"
1048                "  g();\n"
1049                "}",
1050                AllowsMergedIf);
1051   verifyFormat("MYIF (a) {\n"
1052                "  g();\n"
1053                "} else MYIF (b) {\n"
1054                "  g();\n"
1055                "} else {\n"
1056                "  g();\n"
1057                "}",
1058                AllowsMergedIf);
1059   verifyFormat("MYIF (a) {\n"
1060                "  g();\n"
1061                "} else if (b) {\n"
1062                "  g();\n"
1063                "} else {\n"
1064                "  g();\n"
1065                "}",
1066                AllowsMergedIf);
1067 
1068   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1069       FormatStyle::SIS_OnlyFirstIf;
1070 
1071   verifyFormat("if (a) f();\n"
1072                "else {\n"
1073                "  g();\n"
1074                "}",
1075                AllowsMergedIf);
1076   verifyFormat("if (a) f();\n"
1077                "else {\n"
1078                "  if (a) f();\n"
1079                "  else {\n"
1080                "    g();\n"
1081                "  }\n"
1082                "  g();\n"
1083                "}",
1084                AllowsMergedIf);
1085 
1086   verifyFormat("if (a) g();", AllowsMergedIf);
1087   verifyFormat("if (a) {\n"
1088                "  g()\n"
1089                "};",
1090                AllowsMergedIf);
1091   verifyFormat("if (a) g();\n"
1092                "else\n"
1093                "  g();",
1094                AllowsMergedIf);
1095   verifyFormat("if (a) {\n"
1096                "  g();\n"
1097                "} else\n"
1098                "  g();",
1099                AllowsMergedIf);
1100   verifyFormat("if (a) g();\n"
1101                "else {\n"
1102                "  g();\n"
1103                "}",
1104                AllowsMergedIf);
1105   verifyFormat("if (a) {\n"
1106                "  g();\n"
1107                "} else {\n"
1108                "  g();\n"
1109                "}",
1110                AllowsMergedIf);
1111   verifyFormat("if (a) g();\n"
1112                "else if (b)\n"
1113                "  g();\n"
1114                "else\n"
1115                "  g();",
1116                AllowsMergedIf);
1117   verifyFormat("if (a) {\n"
1118                "  g();\n"
1119                "} else if (b)\n"
1120                "  g();\n"
1121                "else\n"
1122                "  g();",
1123                AllowsMergedIf);
1124   verifyFormat("if (a) g();\n"
1125                "else if (b) {\n"
1126                "  g();\n"
1127                "} else\n"
1128                "  g();",
1129                AllowsMergedIf);
1130   verifyFormat("if (a) g();\n"
1131                "else if (b)\n"
1132                "  g();\n"
1133                "else {\n"
1134                "  g();\n"
1135                "}",
1136                AllowsMergedIf);
1137   verifyFormat("if (a) g();\n"
1138                "else if (b) {\n"
1139                "  g();\n"
1140                "} else {\n"
1141                "  g();\n"
1142                "}",
1143                AllowsMergedIf);
1144   verifyFormat("if (a) {\n"
1145                "  g();\n"
1146                "} else if (b) {\n"
1147                "  g();\n"
1148                "} else {\n"
1149                "  g();\n"
1150                "}",
1151                AllowsMergedIf);
1152   verifyFormat("MYIF (a) f();\n"
1153                "else {\n"
1154                "  g();\n"
1155                "}",
1156                AllowsMergedIf);
1157   verifyFormat("MYIF (a) f();\n"
1158                "else {\n"
1159                "  if (a) f();\n"
1160                "  else {\n"
1161                "    g();\n"
1162                "  }\n"
1163                "  g();\n"
1164                "}",
1165                AllowsMergedIf);
1166 
1167   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1168   verifyFormat("MYIF (a) {\n"
1169                "  g()\n"
1170                "};",
1171                AllowsMergedIf);
1172   verifyFormat("MYIF (a) g();\n"
1173                "else\n"
1174                "  g();",
1175                AllowsMergedIf);
1176   verifyFormat("MYIF (a) {\n"
1177                "  g();\n"
1178                "} else\n"
1179                "  g();",
1180                AllowsMergedIf);
1181   verifyFormat("MYIF (a) g();\n"
1182                "else {\n"
1183                "  g();\n"
1184                "}",
1185                AllowsMergedIf);
1186   verifyFormat("MYIF (a) {\n"
1187                "  g();\n"
1188                "} else {\n"
1189                "  g();\n"
1190                "}",
1191                AllowsMergedIf);
1192   verifyFormat("MYIF (a) g();\n"
1193                "else MYIF (b)\n"
1194                "  g();\n"
1195                "else\n"
1196                "  g();",
1197                AllowsMergedIf);
1198   verifyFormat("MYIF (a) g();\n"
1199                "else if (b)\n"
1200                "  g();\n"
1201                "else\n"
1202                "  g();",
1203                AllowsMergedIf);
1204   verifyFormat("MYIF (a) {\n"
1205                "  g();\n"
1206                "} else MYIF (b)\n"
1207                "  g();\n"
1208                "else\n"
1209                "  g();",
1210                AllowsMergedIf);
1211   verifyFormat("MYIF (a) {\n"
1212                "  g();\n"
1213                "} else if (b)\n"
1214                "  g();\n"
1215                "else\n"
1216                "  g();",
1217                AllowsMergedIf);
1218   verifyFormat("MYIF (a) g();\n"
1219                "else MYIF (b) {\n"
1220                "  g();\n"
1221                "} else\n"
1222                "  g();",
1223                AllowsMergedIf);
1224   verifyFormat("MYIF (a) g();\n"
1225                "else if (b) {\n"
1226                "  g();\n"
1227                "} else\n"
1228                "  g();",
1229                AllowsMergedIf);
1230   verifyFormat("MYIF (a) g();\n"
1231                "else MYIF (b)\n"
1232                "  g();\n"
1233                "else {\n"
1234                "  g();\n"
1235                "}",
1236                AllowsMergedIf);
1237   verifyFormat("MYIF (a) g();\n"
1238                "else if (b)\n"
1239                "  g();\n"
1240                "else {\n"
1241                "  g();\n"
1242                "}",
1243                AllowsMergedIf);
1244   verifyFormat("MYIF (a) g();\n"
1245                "else MYIF (b) {\n"
1246                "  g();\n"
1247                "} else {\n"
1248                "  g();\n"
1249                "}",
1250                AllowsMergedIf);
1251   verifyFormat("MYIF (a) g();\n"
1252                "else if (b) {\n"
1253                "  g();\n"
1254                "} else {\n"
1255                "  g();\n"
1256                "}",
1257                AllowsMergedIf);
1258   verifyFormat("MYIF (a) {\n"
1259                "  g();\n"
1260                "} else MYIF (b) {\n"
1261                "  g();\n"
1262                "} else {\n"
1263                "  g();\n"
1264                "}",
1265                AllowsMergedIf);
1266   verifyFormat("MYIF (a) {\n"
1267                "  g();\n"
1268                "} else if (b) {\n"
1269                "  g();\n"
1270                "} else {\n"
1271                "  g();\n"
1272                "}",
1273                AllowsMergedIf);
1274 
1275   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
1276       FormatStyle::SIS_AllIfsAndElse;
1277 
1278   verifyFormat("if (a) f();\n"
1279                "else {\n"
1280                "  g();\n"
1281                "}",
1282                AllowsMergedIf);
1283   verifyFormat("if (a) f();\n"
1284                "else {\n"
1285                "  if (a) f();\n"
1286                "  else {\n"
1287                "    g();\n"
1288                "  }\n"
1289                "  g();\n"
1290                "}",
1291                AllowsMergedIf);
1292 
1293   verifyFormat("if (a) g();", AllowsMergedIf);
1294   verifyFormat("if (a) {\n"
1295                "  g()\n"
1296                "};",
1297                AllowsMergedIf);
1298   verifyFormat("if (a) g();\n"
1299                "else g();",
1300                AllowsMergedIf);
1301   verifyFormat("if (a) {\n"
1302                "  g();\n"
1303                "} else g();",
1304                AllowsMergedIf);
1305   verifyFormat("if (a) g();\n"
1306                "else {\n"
1307                "  g();\n"
1308                "}",
1309                AllowsMergedIf);
1310   verifyFormat("if (a) {\n"
1311                "  g();\n"
1312                "} else {\n"
1313                "  g();\n"
1314                "}",
1315                AllowsMergedIf);
1316   verifyFormat("if (a) g();\n"
1317                "else if (b) g();\n"
1318                "else g();",
1319                AllowsMergedIf);
1320   verifyFormat("if (a) {\n"
1321                "  g();\n"
1322                "} else if (b) g();\n"
1323                "else g();",
1324                AllowsMergedIf);
1325   verifyFormat("if (a) g();\n"
1326                "else if (b) {\n"
1327                "  g();\n"
1328                "} else g();",
1329                AllowsMergedIf);
1330   verifyFormat("if (a) g();\n"
1331                "else if (b) g();\n"
1332                "else {\n"
1333                "  g();\n"
1334                "}",
1335                AllowsMergedIf);
1336   verifyFormat("if (a) g();\n"
1337                "else if (b) {\n"
1338                "  g();\n"
1339                "} else {\n"
1340                "  g();\n"
1341                "}",
1342                AllowsMergedIf);
1343   verifyFormat("if (a) {\n"
1344                "  g();\n"
1345                "} else if (b) {\n"
1346                "  g();\n"
1347                "} else {\n"
1348                "  g();\n"
1349                "}",
1350                AllowsMergedIf);
1351   verifyFormat("MYIF (a) f();\n"
1352                "else {\n"
1353                "  g();\n"
1354                "}",
1355                AllowsMergedIf);
1356   verifyFormat("MYIF (a) f();\n"
1357                "else {\n"
1358                "  if (a) f();\n"
1359                "  else {\n"
1360                "    g();\n"
1361                "  }\n"
1362                "  g();\n"
1363                "}",
1364                AllowsMergedIf);
1365 
1366   verifyFormat("MYIF (a) g();", AllowsMergedIf);
1367   verifyFormat("MYIF (a) {\n"
1368                "  g()\n"
1369                "};",
1370                AllowsMergedIf);
1371   verifyFormat("MYIF (a) g();\n"
1372                "else g();",
1373                AllowsMergedIf);
1374   verifyFormat("MYIF (a) {\n"
1375                "  g();\n"
1376                "} else g();",
1377                AllowsMergedIf);
1378   verifyFormat("MYIF (a) g();\n"
1379                "else {\n"
1380                "  g();\n"
1381                "}",
1382                AllowsMergedIf);
1383   verifyFormat("MYIF (a) {\n"
1384                "  g();\n"
1385                "} else {\n"
1386                "  g();\n"
1387                "}",
1388                AllowsMergedIf);
1389   verifyFormat("MYIF (a) g();\n"
1390                "else MYIF (b) g();\n"
1391                "else g();",
1392                AllowsMergedIf);
1393   verifyFormat("MYIF (a) g();\n"
1394                "else if (b) g();\n"
1395                "else g();",
1396                AllowsMergedIf);
1397   verifyFormat("MYIF (a) {\n"
1398                "  g();\n"
1399                "} else MYIF (b) g();\n"
1400                "else g();",
1401                AllowsMergedIf);
1402   verifyFormat("MYIF (a) {\n"
1403                "  g();\n"
1404                "} else if (b) g();\n"
1405                "else g();",
1406                AllowsMergedIf);
1407   verifyFormat("MYIF (a) g();\n"
1408                "else MYIF (b) {\n"
1409                "  g();\n"
1410                "} else g();",
1411                AllowsMergedIf);
1412   verifyFormat("MYIF (a) g();\n"
1413                "else if (b) {\n"
1414                "  g();\n"
1415                "} else g();",
1416                AllowsMergedIf);
1417   verifyFormat("MYIF (a) g();\n"
1418                "else MYIF (b) g();\n"
1419                "else {\n"
1420                "  g();\n"
1421                "}",
1422                AllowsMergedIf);
1423   verifyFormat("MYIF (a) g();\n"
1424                "else if (b) g();\n"
1425                "else {\n"
1426                "  g();\n"
1427                "}",
1428                AllowsMergedIf);
1429   verifyFormat("MYIF (a) g();\n"
1430                "else MYIF (b) {\n"
1431                "  g();\n"
1432                "} else {\n"
1433                "  g();\n"
1434                "}",
1435                AllowsMergedIf);
1436   verifyFormat("MYIF (a) g();\n"
1437                "else if (b) {\n"
1438                "  g();\n"
1439                "} else {\n"
1440                "  g();\n"
1441                "}",
1442                AllowsMergedIf);
1443   verifyFormat("MYIF (a) {\n"
1444                "  g();\n"
1445                "} else MYIF (b) {\n"
1446                "  g();\n"
1447                "} else {\n"
1448                "  g();\n"
1449                "}",
1450                AllowsMergedIf);
1451   verifyFormat("MYIF (a) {\n"
1452                "  g();\n"
1453                "} else if (b) {\n"
1454                "  g();\n"
1455                "} else {\n"
1456                "  g();\n"
1457                "}",
1458                AllowsMergedIf);
1459 }
1460 
TEST_F(FormatTest,FormatLoopsWithoutCompoundStatement)1461 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
1462   FormatStyle AllowsMergedLoops = getLLVMStyle();
1463   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
1464   verifyFormat("while (true) continue;", AllowsMergedLoops);
1465   verifyFormat("for (;;) continue;", AllowsMergedLoops);
1466   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
1467   verifyFormat("while (true)\n"
1468                "  ;",
1469                AllowsMergedLoops);
1470   verifyFormat("for (;;)\n"
1471                "  ;",
1472                AllowsMergedLoops);
1473   verifyFormat("for (;;)\n"
1474                "  for (;;) continue;",
1475                AllowsMergedLoops);
1476   verifyFormat("for (;;) // Can't merge this\n"
1477                "  continue;",
1478                AllowsMergedLoops);
1479   verifyFormat("for (;;) /* still don't merge */\n"
1480                "  continue;",
1481                AllowsMergedLoops);
1482   verifyFormat("do a++;\n"
1483                "while (true);",
1484                AllowsMergedLoops);
1485   verifyFormat("do /* Don't merge */\n"
1486                "  a++;\n"
1487                "while (true);",
1488                AllowsMergedLoops);
1489   verifyFormat("do // Don't merge\n"
1490                "  a++;\n"
1491                "while (true);",
1492                AllowsMergedLoops);
1493   verifyFormat("do\n"
1494                "  // Don't merge\n"
1495                "  a++;\n"
1496                "while (true);",
1497                AllowsMergedLoops);
1498   // Without braces labels are interpreted differently.
1499   verifyFormat("{\n"
1500                "  do\n"
1501                "  label:\n"
1502                "    a++;\n"
1503                "  while (true);\n"
1504                "}",
1505                AllowsMergedLoops);
1506 }
1507 
TEST_F(FormatTest,FormatShortBracedStatements)1508 TEST_F(FormatTest, FormatShortBracedStatements) {
1509   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
1510   AllowSimpleBracedStatements.IfMacros.push_back("MYIF");
1511   // Where line-lengths matter, a 2-letter synonym that maintains line length.
1512   // Not IF to avoid any confusion that IF is somehow special.
1513   AllowSimpleBracedStatements.IfMacros.push_back("FI");
1514   AllowSimpleBracedStatements.ColumnLimit = 40;
1515   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
1516       FormatStyle::SBS_Always;
1517 
1518   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1519       FormatStyle::SIS_WithoutElse;
1520   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1521 
1522   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
1523   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
1524   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
1525 
1526   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1527   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1528   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1529   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1530   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1531   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1532   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1533   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1534   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1535   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1536   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1537   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1538   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1539   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1540   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1541   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1542   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1543                AllowSimpleBracedStatements);
1544   verifyFormat("if (true) {\n"
1545                "  ffffffffffffffffffffffff();\n"
1546                "}",
1547                AllowSimpleBracedStatements);
1548   verifyFormat("if (true) {\n"
1549                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1550                "}",
1551                AllowSimpleBracedStatements);
1552   verifyFormat("if (true) { //\n"
1553                "  f();\n"
1554                "}",
1555                AllowSimpleBracedStatements);
1556   verifyFormat("if (true) {\n"
1557                "  f();\n"
1558                "  f();\n"
1559                "}",
1560                AllowSimpleBracedStatements);
1561   verifyFormat("if (true) {\n"
1562                "  f();\n"
1563                "} else {\n"
1564                "  f();\n"
1565                "}",
1566                AllowSimpleBracedStatements);
1567   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1568                AllowSimpleBracedStatements);
1569   verifyFormat("MYIF (true) {\n"
1570                "  ffffffffffffffffffffffff();\n"
1571                "}",
1572                AllowSimpleBracedStatements);
1573   verifyFormat("MYIF (true) {\n"
1574                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1575                "}",
1576                AllowSimpleBracedStatements);
1577   verifyFormat("MYIF (true) { //\n"
1578                "  f();\n"
1579                "}",
1580                AllowSimpleBracedStatements);
1581   verifyFormat("MYIF (true) {\n"
1582                "  f();\n"
1583                "  f();\n"
1584                "}",
1585                AllowSimpleBracedStatements);
1586   verifyFormat("MYIF (true) {\n"
1587                "  f();\n"
1588                "} else {\n"
1589                "  f();\n"
1590                "}",
1591                AllowSimpleBracedStatements);
1592 
1593   verifyFormat("struct A2 {\n"
1594                "  int X;\n"
1595                "};",
1596                AllowSimpleBracedStatements);
1597   verifyFormat("typedef struct A2 {\n"
1598                "  int X;\n"
1599                "} A2_t;",
1600                AllowSimpleBracedStatements);
1601   verifyFormat("template <int> struct A2 {\n"
1602                "  struct B {};\n"
1603                "};",
1604                AllowSimpleBracedStatements);
1605 
1606   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1607       FormatStyle::SIS_Never;
1608   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1609   verifyFormat("if (true) {\n"
1610                "  f();\n"
1611                "}",
1612                AllowSimpleBracedStatements);
1613   verifyFormat("if (true) {\n"
1614                "  f();\n"
1615                "} else {\n"
1616                "  f();\n"
1617                "}",
1618                AllowSimpleBracedStatements);
1619   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1620   verifyFormat("MYIF (true) {\n"
1621                "  f();\n"
1622                "}",
1623                AllowSimpleBracedStatements);
1624   verifyFormat("MYIF (true) {\n"
1625                "  f();\n"
1626                "} else {\n"
1627                "  f();\n"
1628                "}",
1629                AllowSimpleBracedStatements);
1630 
1631   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1632   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1633   verifyFormat("while (true) {\n"
1634                "  f();\n"
1635                "}",
1636                AllowSimpleBracedStatements);
1637   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1638   verifyFormat("for (;;) {\n"
1639                "  f();\n"
1640                "}",
1641                AllowSimpleBracedStatements);
1642 
1643   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1644       FormatStyle::SIS_WithoutElse;
1645   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
1646   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
1647       FormatStyle::BWACS_Always;
1648 
1649   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1650   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
1651   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1652   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1653   verifyFormat("MYIF constexpr (true) {}", AllowSimpleBracedStatements);
1654   verifyFormat("MYIF CONSTEXPR (true) {}", AllowSimpleBracedStatements);
1655   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1656   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1657   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
1658   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
1659   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1660   verifyFormat("MYIF (true) { f(); }", AllowSimpleBracedStatements);
1661   verifyFormat("MYIF constexpr (true) { f(); }", AllowSimpleBracedStatements);
1662   verifyFormat("MYIF CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
1663   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
1664   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
1665   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
1666                AllowSimpleBracedStatements);
1667   verifyFormat("if (true)\n"
1668                "{\n"
1669                "  ffffffffffffffffffffffff();\n"
1670                "}",
1671                AllowSimpleBracedStatements);
1672   verifyFormat("if (true)\n"
1673                "{\n"
1674                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1675                "}",
1676                AllowSimpleBracedStatements);
1677   verifyFormat("if (true)\n"
1678                "{ //\n"
1679                "  f();\n"
1680                "}",
1681                AllowSimpleBracedStatements);
1682   verifyFormat("if (true)\n"
1683                "{\n"
1684                "  f();\n"
1685                "  f();\n"
1686                "}",
1687                AllowSimpleBracedStatements);
1688   verifyFormat("if (true)\n"
1689                "{\n"
1690                "  f();\n"
1691                "} else\n"
1692                "{\n"
1693                "  f();\n"
1694                "}",
1695                AllowSimpleBracedStatements);
1696   verifyFormat("FI (true) { fffffffffffffffffffffff(); }",
1697                AllowSimpleBracedStatements);
1698   verifyFormat("MYIF (true)\n"
1699                "{\n"
1700                "  ffffffffffffffffffffffff();\n"
1701                "}",
1702                AllowSimpleBracedStatements);
1703   verifyFormat("MYIF (true)\n"
1704                "{\n"
1705                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
1706                "}",
1707                AllowSimpleBracedStatements);
1708   verifyFormat("MYIF (true)\n"
1709                "{ //\n"
1710                "  f();\n"
1711                "}",
1712                AllowSimpleBracedStatements);
1713   verifyFormat("MYIF (true)\n"
1714                "{\n"
1715                "  f();\n"
1716                "  f();\n"
1717                "}",
1718                AllowSimpleBracedStatements);
1719   verifyFormat("MYIF (true)\n"
1720                "{\n"
1721                "  f();\n"
1722                "} else\n"
1723                "{\n"
1724                "  f();\n"
1725                "}",
1726                AllowSimpleBracedStatements);
1727 
1728   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
1729       FormatStyle::SIS_Never;
1730   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
1731   verifyFormat("if (true)\n"
1732                "{\n"
1733                "  f();\n"
1734                "}",
1735                AllowSimpleBracedStatements);
1736   verifyFormat("if (true)\n"
1737                "{\n"
1738                "  f();\n"
1739                "} else\n"
1740                "{\n"
1741                "  f();\n"
1742                "}",
1743                AllowSimpleBracedStatements);
1744   verifyFormat("MYIF (true) {}", AllowSimpleBracedStatements);
1745   verifyFormat("MYIF (true)\n"
1746                "{\n"
1747                "  f();\n"
1748                "}",
1749                AllowSimpleBracedStatements);
1750   verifyFormat("MYIF (true)\n"
1751                "{\n"
1752                "  f();\n"
1753                "} else\n"
1754                "{\n"
1755                "  f();\n"
1756                "}",
1757                AllowSimpleBracedStatements);
1758 
1759   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
1760   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
1761   verifyFormat("while (true)\n"
1762                "{\n"
1763                "  f();\n"
1764                "}",
1765                AllowSimpleBracedStatements);
1766   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
1767   verifyFormat("for (;;)\n"
1768                "{\n"
1769                "  f();\n"
1770                "}",
1771                AllowSimpleBracedStatements);
1772 }
1773 
TEST_F(FormatTest,ShortBlocksInMacrosDontMergeWithCodeAfterMacro)1774 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
1775   FormatStyle Style = getLLVMStyleWithColumns(60);
1776   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
1777   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
1778   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
1779   EXPECT_EQ("#define A                                                  \\\n"
1780             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
1781             "  {                                                        \\\n"
1782             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
1783             "  }\n"
1784             "X;",
1785             format("#define A \\\n"
1786                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
1787                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
1788                    "   }\n"
1789                    "X;",
1790                    Style));
1791 }
1792 
TEST_F(FormatTest,ParseIfElse)1793 TEST_F(FormatTest, ParseIfElse) {
1794   verifyFormat("if (true)\n"
1795                "  if (true)\n"
1796                "    if (true)\n"
1797                "      f();\n"
1798                "    else\n"
1799                "      g();\n"
1800                "  else\n"
1801                "    h();\n"
1802                "else\n"
1803                "  i();");
1804   verifyFormat("if (true)\n"
1805                "  if (true)\n"
1806                "    if (true) {\n"
1807                "      if (true)\n"
1808                "        f();\n"
1809                "    } else {\n"
1810                "      g();\n"
1811                "    }\n"
1812                "  else\n"
1813                "    h();\n"
1814                "else {\n"
1815                "  i();\n"
1816                "}");
1817   verifyFormat("if (true)\n"
1818                "  if constexpr (true)\n"
1819                "    if (true) {\n"
1820                "      if constexpr (true)\n"
1821                "        f();\n"
1822                "    } else {\n"
1823                "      g();\n"
1824                "    }\n"
1825                "  else\n"
1826                "    h();\n"
1827                "else {\n"
1828                "  i();\n"
1829                "}");
1830   verifyFormat("if (true)\n"
1831                "  if CONSTEXPR (true)\n"
1832                "    if (true) {\n"
1833                "      if CONSTEXPR (true)\n"
1834                "        f();\n"
1835                "    } else {\n"
1836                "      g();\n"
1837                "    }\n"
1838                "  else\n"
1839                "    h();\n"
1840                "else {\n"
1841                "  i();\n"
1842                "}");
1843   verifyFormat("void f() {\n"
1844                "  if (a) {\n"
1845                "  } else {\n"
1846                "  }\n"
1847                "}");
1848 }
1849 
TEST_F(FormatTest,ElseIf)1850 TEST_F(FormatTest, ElseIf) {
1851   verifyFormat("if (a) {\n} else if (b) {\n}");
1852   verifyFormat("if (a)\n"
1853                "  f();\n"
1854                "else if (b)\n"
1855                "  g();\n"
1856                "else\n"
1857                "  h();");
1858   verifyFormat("if (a)\n"
1859                "  f();\n"
1860                "else // comment\n"
1861                "  if (b) {\n"
1862                "    g();\n"
1863                "    h();\n"
1864                "  }");
1865   verifyFormat("if constexpr (a)\n"
1866                "  f();\n"
1867                "else if constexpr (b)\n"
1868                "  g();\n"
1869                "else\n"
1870                "  h();");
1871   verifyFormat("if CONSTEXPR (a)\n"
1872                "  f();\n"
1873                "else if CONSTEXPR (b)\n"
1874                "  g();\n"
1875                "else\n"
1876                "  h();");
1877   verifyFormat("if (a) {\n"
1878                "  f();\n"
1879                "}\n"
1880                "// or else ..\n"
1881                "else {\n"
1882                "  g()\n"
1883                "}");
1884 
1885   verifyFormat("if (a) {\n"
1886                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1887                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1888                "}");
1889   verifyFormat("if (a) {\n"
1890                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1891                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1892                "}");
1893   verifyFormat("if (a) {\n"
1894                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
1895                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
1896                "}");
1897   verifyFormat("if (a) {\n"
1898                "} else if (\n"
1899                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1900                "}",
1901                getLLVMStyleWithColumns(62));
1902   verifyFormat("if (a) {\n"
1903                "} else if constexpr (\n"
1904                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1905                "}",
1906                getLLVMStyleWithColumns(62));
1907   verifyFormat("if (a) {\n"
1908                "} else if CONSTEXPR (\n"
1909                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
1910                "}",
1911                getLLVMStyleWithColumns(62));
1912 }
1913 
TEST_F(FormatTest,SeparatePointerReferenceAlignment)1914 TEST_F(FormatTest, SeparatePointerReferenceAlignment) {
1915   FormatStyle Style = getLLVMStyle();
1916   // Check first the default LLVM style
1917   // Style.PointerAlignment = FormatStyle::PAS_Right;
1918   // Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1919   verifyFormat("int *f1(int *a, int &b, int &&c);", Style);
1920   verifyFormat("int &f2(int &&c, int *a, int &b);", Style);
1921   verifyFormat("int &&f3(int &b, int &&c, int *a);", Style);
1922   verifyFormat("int *f1(int &a) const &;", Style);
1923   verifyFormat("int *f1(int &a) const & = 0;", Style);
1924   verifyFormat("int *a = f1();", Style);
1925   verifyFormat("int &b = f2();", Style);
1926   verifyFormat("int &&c = f3();", Style);
1927 
1928   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1929   verifyFormat("Const unsigned int *c;\n"
1930                "const unsigned int *d;\n"
1931                "Const unsigned int &e;\n"
1932                "const unsigned int &f;\n"
1933                "const unsigned    &&g;\n"
1934                "Const unsigned      h;",
1935                Style);
1936 
1937   Style.PointerAlignment = FormatStyle::PAS_Left;
1938   Style.ReferenceAlignment = FormatStyle::RAS_Pointer;
1939   verifyFormat("int* f1(int* a, int& b, int&& c);", Style);
1940   verifyFormat("int& f2(int&& c, int* a, int& b);", Style);
1941   verifyFormat("int&& f3(int& b, int&& c, int* a);", Style);
1942   verifyFormat("int* f1(int& a) const& = 0;", Style);
1943   verifyFormat("int* a = f1();", Style);
1944   verifyFormat("int& b = f2();", Style);
1945   verifyFormat("int&& c = f3();", Style);
1946 
1947   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1948   verifyFormat("Const unsigned int* c;\n"
1949                "const unsigned int* d;\n"
1950                "Const unsigned int& e;\n"
1951                "const unsigned int& f;\n"
1952                "const unsigned&&    g;\n"
1953                "Const unsigned      h;",
1954                Style);
1955 
1956   Style.PointerAlignment = FormatStyle::PAS_Right;
1957   Style.ReferenceAlignment = FormatStyle::RAS_Left;
1958   verifyFormat("int *f1(int *a, int& b, int&& c);", Style);
1959   verifyFormat("int& f2(int&& c, int *a, int& b);", Style);
1960   verifyFormat("int&& f3(int& b, int&& c, int *a);", Style);
1961   verifyFormat("int *a = f1();", Style);
1962   verifyFormat("int& b = f2();", Style);
1963   verifyFormat("int&& c = f3();", Style);
1964 
1965   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1966   verifyFormat("Const unsigned int *c;\n"
1967                "const unsigned int *d;\n"
1968                "Const unsigned int& e;\n"
1969                "const unsigned int& f;\n"
1970                "const unsigned      g;\n"
1971                "Const unsigned      h;",
1972                Style);
1973 
1974   Style.PointerAlignment = FormatStyle::PAS_Left;
1975   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
1976   verifyFormat("int* f1(int* a, int & b, int && c);", Style);
1977   verifyFormat("int & f2(int && c, int* a, int & b);", Style);
1978   verifyFormat("int && f3(int & b, int && c, int* a);", Style);
1979   verifyFormat("int* a = f1();", Style);
1980   verifyFormat("int & b = f2();", Style);
1981   verifyFormat("int && c = f3();", Style);
1982 
1983   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
1984   verifyFormat("Const unsigned int*  c;\n"
1985                "const unsigned int*  d;\n"
1986                "Const unsigned int & e;\n"
1987                "const unsigned int & f;\n"
1988                "const unsigned &&    g;\n"
1989                "Const unsigned       h;",
1990                Style);
1991 
1992   Style.PointerAlignment = FormatStyle::PAS_Middle;
1993   Style.ReferenceAlignment = FormatStyle::RAS_Right;
1994   verifyFormat("int * f1(int * a, int &b, int &&c);", Style);
1995   verifyFormat("int &f2(int &&c, int * a, int &b);", Style);
1996   verifyFormat("int &&f3(int &b, int &&c, int * a);", Style);
1997   verifyFormat("int * a = f1();", Style);
1998   verifyFormat("int &b = f2();", Style);
1999   verifyFormat("int &&c = f3();", Style);
2000 
2001   // FIXME: we don't handle this yet, so output may be arbitrary until it's
2002   // specifically handled
2003   // verifyFormat("int Add2(BTree * &Root, char * szToAdd)", Style);
2004 }
2005 
TEST_F(FormatTest,FormatsForLoop)2006 TEST_F(FormatTest, FormatsForLoop) {
2007   verifyFormat(
2008       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
2009       "     ++VeryVeryLongLoopVariable)\n"
2010       "  ;");
2011   verifyFormat("for (;;)\n"
2012                "  f();");
2013   verifyFormat("for (;;) {\n}");
2014   verifyFormat("for (;;) {\n"
2015                "  f();\n"
2016                "}");
2017   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
2018 
2019   verifyFormat(
2020       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2021       "                                          E = UnwrappedLines.end();\n"
2022       "     I != E; ++I) {\n}");
2023 
2024   verifyFormat(
2025       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
2026       "     ++IIIII) {\n}");
2027   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
2028                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
2029                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
2030   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
2031                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
2032                "         E = FD->getDeclsInPrototypeScope().end();\n"
2033                "     I != E; ++I) {\n}");
2034   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
2035                "         I = Container.begin(),\n"
2036                "         E = Container.end();\n"
2037                "     I != E; ++I) {\n}",
2038                getLLVMStyleWithColumns(76));
2039 
2040   verifyFormat(
2041       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
2042       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
2043       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2044       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2045       "     ++aaaaaaaaaaa) {\n}");
2046   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
2047                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
2048                "     ++i) {\n}");
2049   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
2050                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2051                "}");
2052   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
2053                "         aaaaaaaaaa);\n"
2054                "     iter; ++iter) {\n"
2055                "}");
2056   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
2057                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
2058                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
2059                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
2060 
2061   // These should not be formatted as Objective-C for-in loops.
2062   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
2063   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
2064   verifyFormat("Foo *x;\nfor (x in y) {\n}");
2065   verifyFormat(
2066       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
2067 
2068   FormatStyle NoBinPacking = getLLVMStyle();
2069   NoBinPacking.BinPackParameters = false;
2070   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
2071                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
2072                "                                           aaaaaaaaaaaaaaaa,\n"
2073                "                                           aaaaaaaaaaaaaaaa,\n"
2074                "                                           aaaaaaaaaaaaaaaa);\n"
2075                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
2076                "}",
2077                NoBinPacking);
2078   verifyFormat(
2079       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
2080       "                                          E = UnwrappedLines.end();\n"
2081       "     I != E;\n"
2082       "     ++I) {\n}",
2083       NoBinPacking);
2084 
2085   FormatStyle AlignLeft = getLLVMStyle();
2086   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
2087   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
2088 }
2089 
TEST_F(FormatTest,RangeBasedForLoops)2090 TEST_F(FormatTest, RangeBasedForLoops) {
2091   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
2092                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2093   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
2094                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
2095   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
2096                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
2097   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
2098                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
2099 }
2100 
TEST_F(FormatTest,ForEachLoops)2101 TEST_F(FormatTest, ForEachLoops) {
2102   verifyFormat("void f() {\n"
2103                "  foreach (Item *item, itemlist) {}\n"
2104                "  Q_FOREACH (Item *item, itemlist) {}\n"
2105                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
2106                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
2107                "}");
2108 
2109   FormatStyle Style = getLLVMStyle();
2110   Style.SpaceBeforeParens =
2111       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
2112   verifyFormat("void f() {\n"
2113                "  foreach(Item *item, itemlist) {}\n"
2114                "  Q_FOREACH(Item *item, itemlist) {}\n"
2115                "  BOOST_FOREACH(Item *item, itemlist) {}\n"
2116                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
2117                "}",
2118                Style);
2119 
2120   // As function-like macros.
2121   verifyFormat("#define foreach(x, y)\n"
2122                "#define Q_FOREACH(x, y)\n"
2123                "#define BOOST_FOREACH(x, y)\n"
2124                "#define UNKNOWN_FOREACH(x, y)\n");
2125 
2126   // Not as function-like macros.
2127   verifyFormat("#define foreach (x, y)\n"
2128                "#define Q_FOREACH (x, y)\n"
2129                "#define BOOST_FOREACH (x, y)\n"
2130                "#define UNKNOWN_FOREACH (x, y)\n");
2131 
2132   // handle microsoft non standard extension
2133   verifyFormat("for each (char c in x->MyStringProperty)");
2134 }
2135 
TEST_F(FormatTest,FormatsWhileLoop)2136 TEST_F(FormatTest, FormatsWhileLoop) {
2137   verifyFormat("while (true) {\n}");
2138   verifyFormat("while (true)\n"
2139                "  f();");
2140   verifyFormat("while () {\n}");
2141   verifyFormat("while () {\n"
2142                "  f();\n"
2143                "}");
2144 }
2145 
TEST_F(FormatTest,FormatsDoWhile)2146 TEST_F(FormatTest, FormatsDoWhile) {
2147   verifyFormat("do {\n"
2148                "  do_something();\n"
2149                "} while (something());");
2150   verifyFormat("do\n"
2151                "  do_something();\n"
2152                "while (something());");
2153 }
2154 
TEST_F(FormatTest,FormatsSwitchStatement)2155 TEST_F(FormatTest, FormatsSwitchStatement) {
2156   verifyFormat("switch (x) {\n"
2157                "case 1:\n"
2158                "  f();\n"
2159                "  break;\n"
2160                "case kFoo:\n"
2161                "case ns::kBar:\n"
2162                "case kBaz:\n"
2163                "  break;\n"
2164                "default:\n"
2165                "  g();\n"
2166                "  break;\n"
2167                "}");
2168   verifyFormat("switch (x) {\n"
2169                "case 1: {\n"
2170                "  f();\n"
2171                "  break;\n"
2172                "}\n"
2173                "case 2: {\n"
2174                "  break;\n"
2175                "}\n"
2176                "}");
2177   verifyFormat("switch (x) {\n"
2178                "case 1: {\n"
2179                "  f();\n"
2180                "  {\n"
2181                "    g();\n"
2182                "    h();\n"
2183                "  }\n"
2184                "  break;\n"
2185                "}\n"
2186                "}");
2187   verifyFormat("switch (x) {\n"
2188                "case 1: {\n"
2189                "  f();\n"
2190                "  if (foo) {\n"
2191                "    g();\n"
2192                "    h();\n"
2193                "  }\n"
2194                "  break;\n"
2195                "}\n"
2196                "}");
2197   verifyFormat("switch (x) {\n"
2198                "case 1: {\n"
2199                "  f();\n"
2200                "  g();\n"
2201                "} break;\n"
2202                "}");
2203   verifyFormat("switch (test)\n"
2204                "  ;");
2205   verifyFormat("switch (x) {\n"
2206                "default: {\n"
2207                "  // Do nothing.\n"
2208                "}\n"
2209                "}");
2210   verifyFormat("switch (x) {\n"
2211                "// comment\n"
2212                "// if 1, do f()\n"
2213                "case 1:\n"
2214                "  f();\n"
2215                "}");
2216   verifyFormat("switch (x) {\n"
2217                "case 1:\n"
2218                "  // Do amazing stuff\n"
2219                "  {\n"
2220                "    f();\n"
2221                "    g();\n"
2222                "  }\n"
2223                "  break;\n"
2224                "}");
2225   verifyFormat("#define A          \\\n"
2226                "  switch (x) {     \\\n"
2227                "  case a:          \\\n"
2228                "    foo = b;       \\\n"
2229                "  }",
2230                getLLVMStyleWithColumns(20));
2231   verifyFormat("#define OPERATION_CASE(name)           \\\n"
2232                "  case OP_name:                        \\\n"
2233                "    return operations::Operation##name\n",
2234                getLLVMStyleWithColumns(40));
2235   verifyFormat("switch (x) {\n"
2236                "case 1:;\n"
2237                "default:;\n"
2238                "  int i;\n"
2239                "}");
2240 
2241   verifyGoogleFormat("switch (x) {\n"
2242                      "  case 1:\n"
2243                      "    f();\n"
2244                      "    break;\n"
2245                      "  case kFoo:\n"
2246                      "  case ns::kBar:\n"
2247                      "  case kBaz:\n"
2248                      "    break;\n"
2249                      "  default:\n"
2250                      "    g();\n"
2251                      "    break;\n"
2252                      "}");
2253   verifyGoogleFormat("switch (x) {\n"
2254                      "  case 1: {\n"
2255                      "    f();\n"
2256                      "    break;\n"
2257                      "  }\n"
2258                      "}");
2259   verifyGoogleFormat("switch (test)\n"
2260                      "  ;");
2261 
2262   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
2263                      "  case OP_name:              \\\n"
2264                      "    return operations::Operation##name\n");
2265   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
2266                      "  // Get the correction operation class.\n"
2267                      "  switch (OpCode) {\n"
2268                      "    CASE(Add);\n"
2269                      "    CASE(Subtract);\n"
2270                      "    default:\n"
2271                      "      return operations::Unknown;\n"
2272                      "  }\n"
2273                      "#undef OPERATION_CASE\n"
2274                      "}");
2275   verifyFormat("DEBUG({\n"
2276                "  switch (x) {\n"
2277                "  case A:\n"
2278                "    f();\n"
2279                "    break;\n"
2280                "    // fallthrough\n"
2281                "  case B:\n"
2282                "    g();\n"
2283                "    break;\n"
2284                "  }\n"
2285                "});");
2286   EXPECT_EQ("DEBUG({\n"
2287             "  switch (x) {\n"
2288             "  case A:\n"
2289             "    f();\n"
2290             "    break;\n"
2291             "  // On B:\n"
2292             "  case B:\n"
2293             "    g();\n"
2294             "    break;\n"
2295             "  }\n"
2296             "});",
2297             format("DEBUG({\n"
2298                    "  switch (x) {\n"
2299                    "  case A:\n"
2300                    "    f();\n"
2301                    "    break;\n"
2302                    "  // On B:\n"
2303                    "  case B:\n"
2304                    "    g();\n"
2305                    "    break;\n"
2306                    "  }\n"
2307                    "});",
2308                    getLLVMStyle()));
2309   EXPECT_EQ("switch (n) {\n"
2310             "case 0: {\n"
2311             "  return false;\n"
2312             "}\n"
2313             "default: {\n"
2314             "  return true;\n"
2315             "}\n"
2316             "}",
2317             format("switch (n)\n"
2318                    "{\n"
2319                    "case 0: {\n"
2320                    "  return false;\n"
2321                    "}\n"
2322                    "default: {\n"
2323                    "  return true;\n"
2324                    "}\n"
2325                    "}",
2326                    getLLVMStyle()));
2327   verifyFormat("switch (a) {\n"
2328                "case (b):\n"
2329                "  return;\n"
2330                "}");
2331 
2332   verifyFormat("switch (a) {\n"
2333                "case some_namespace::\n"
2334                "    some_constant:\n"
2335                "  return;\n"
2336                "}",
2337                getLLVMStyleWithColumns(34));
2338 
2339   FormatStyle Style = getLLVMStyle();
2340   Style.IndentCaseLabels = true;
2341   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
2342   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2343   Style.BraceWrapping.AfterCaseLabel = true;
2344   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2345   EXPECT_EQ("switch (n)\n"
2346             "{\n"
2347             "  case 0:\n"
2348             "  {\n"
2349             "    return false;\n"
2350             "  }\n"
2351             "  default:\n"
2352             "  {\n"
2353             "    return true;\n"
2354             "  }\n"
2355             "}",
2356             format("switch (n) {\n"
2357                    "  case 0: {\n"
2358                    "    return false;\n"
2359                    "  }\n"
2360                    "  default: {\n"
2361                    "    return true;\n"
2362                    "  }\n"
2363                    "}",
2364                    Style));
2365   Style.BraceWrapping.AfterCaseLabel = false;
2366   EXPECT_EQ("switch (n)\n"
2367             "{\n"
2368             "  case 0: {\n"
2369             "    return false;\n"
2370             "  }\n"
2371             "  default: {\n"
2372             "    return true;\n"
2373             "  }\n"
2374             "}",
2375             format("switch (n) {\n"
2376                    "  case 0:\n"
2377                    "  {\n"
2378                    "    return false;\n"
2379                    "  }\n"
2380                    "  default:\n"
2381                    "  {\n"
2382                    "    return true;\n"
2383                    "  }\n"
2384                    "}",
2385                    Style));
2386   Style.IndentCaseLabels = false;
2387   Style.IndentCaseBlocks = true;
2388   EXPECT_EQ("switch (n)\n"
2389             "{\n"
2390             "case 0:\n"
2391             "  {\n"
2392             "    return false;\n"
2393             "  }\n"
2394             "case 1:\n"
2395             "  break;\n"
2396             "default:\n"
2397             "  {\n"
2398             "    return true;\n"
2399             "  }\n"
2400             "}",
2401             format("switch (n) {\n"
2402                    "case 0: {\n"
2403                    "  return false;\n"
2404                    "}\n"
2405                    "case 1:\n"
2406                    "  break;\n"
2407                    "default: {\n"
2408                    "  return true;\n"
2409                    "}\n"
2410                    "}",
2411                    Style));
2412   Style.IndentCaseLabels = true;
2413   Style.IndentCaseBlocks = true;
2414   EXPECT_EQ("switch (n)\n"
2415             "{\n"
2416             "  case 0:\n"
2417             "    {\n"
2418             "      return false;\n"
2419             "    }\n"
2420             "  case 1:\n"
2421             "    break;\n"
2422             "  default:\n"
2423             "    {\n"
2424             "      return true;\n"
2425             "    }\n"
2426             "}",
2427             format("switch (n) {\n"
2428                    "case 0: {\n"
2429                    "  return false;\n"
2430                    "}\n"
2431                    "case 1:\n"
2432                    "  break;\n"
2433                    "default: {\n"
2434                    "  return true;\n"
2435                    "}\n"
2436                    "}",
2437                    Style));
2438 }
2439 
TEST_F(FormatTest,CaseRanges)2440 TEST_F(FormatTest, CaseRanges) {
2441   verifyFormat("switch (x) {\n"
2442                "case 'A' ... 'Z':\n"
2443                "case 1 ... 5:\n"
2444                "case a ... b:\n"
2445                "  break;\n"
2446                "}");
2447 }
2448 
TEST_F(FormatTest,ShortEnums)2449 TEST_F(FormatTest, ShortEnums) {
2450   FormatStyle Style = getLLVMStyle();
2451   Style.AllowShortEnumsOnASingleLine = true;
2452   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
2453   Style.AllowShortEnumsOnASingleLine = false;
2454   verifyFormat("enum {\n"
2455                "  A,\n"
2456                "  B,\n"
2457                "  C\n"
2458                "} ShortEnum1, ShortEnum2;",
2459                Style);
2460   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2461   Style.BraceWrapping.AfterEnum = true;
2462   verifyFormat("enum\n"
2463                "{\n"
2464                "  A,\n"
2465                "  B,\n"
2466                "  C\n"
2467                "} ShortEnum1, ShortEnum2;",
2468                Style);
2469 }
2470 
TEST_F(FormatTest,ShortCaseLabels)2471 TEST_F(FormatTest, ShortCaseLabels) {
2472   FormatStyle Style = getLLVMStyle();
2473   Style.AllowShortCaseLabelsOnASingleLine = true;
2474   verifyFormat("switch (a) {\n"
2475                "case 1: x = 1; break;\n"
2476                "case 2: return;\n"
2477                "case 3:\n"
2478                "case 4:\n"
2479                "case 5: return;\n"
2480                "case 6: // comment\n"
2481                "  return;\n"
2482                "case 7:\n"
2483                "  // comment\n"
2484                "  return;\n"
2485                "case 8:\n"
2486                "  x = 8; // comment\n"
2487                "  break;\n"
2488                "default: y = 1; break;\n"
2489                "}",
2490                Style);
2491   verifyFormat("switch (a) {\n"
2492                "case 0: return; // comment\n"
2493                "case 1: break;  // comment\n"
2494                "case 2: return;\n"
2495                "// comment\n"
2496                "case 3: return;\n"
2497                "// comment 1\n"
2498                "// comment 2\n"
2499                "// comment 3\n"
2500                "case 4: break; /* comment */\n"
2501                "case 5:\n"
2502                "  // comment\n"
2503                "  break;\n"
2504                "case 6: /* comment */ x = 1; break;\n"
2505                "case 7: x = /* comment */ 1; break;\n"
2506                "case 8:\n"
2507                "  x = 1; /* comment */\n"
2508                "  break;\n"
2509                "case 9:\n"
2510                "  break; // comment line 1\n"
2511                "         // comment line 2\n"
2512                "}",
2513                Style);
2514   EXPECT_EQ("switch (a) {\n"
2515             "case 1:\n"
2516             "  x = 8;\n"
2517             "  // fall through\n"
2518             "case 2: x = 8;\n"
2519             "// comment\n"
2520             "case 3:\n"
2521             "  return; /* comment line 1\n"
2522             "           * comment line 2 */\n"
2523             "case 4: i = 8;\n"
2524             "// something else\n"
2525             "#if FOO\n"
2526             "case 5: break;\n"
2527             "#endif\n"
2528             "}",
2529             format("switch (a) {\n"
2530                    "case 1: x = 8;\n"
2531                    "  // fall through\n"
2532                    "case 2:\n"
2533                    "  x = 8;\n"
2534                    "// comment\n"
2535                    "case 3:\n"
2536                    "  return; /* comment line 1\n"
2537                    "           * comment line 2 */\n"
2538                    "case 4:\n"
2539                    "  i = 8;\n"
2540                    "// something else\n"
2541                    "#if FOO\n"
2542                    "case 5: break;\n"
2543                    "#endif\n"
2544                    "}",
2545                    Style));
2546   EXPECT_EQ("switch (a) {\n"
2547             "case 0:\n"
2548             "  return; // long long long long long long long long long long "
2549             "long long comment\n"
2550             "          // line\n"
2551             "}",
2552             format("switch (a) {\n"
2553                    "case 0: return; // long long long long long long long long "
2554                    "long long long long comment line\n"
2555                    "}",
2556                    Style));
2557   EXPECT_EQ("switch (a) {\n"
2558             "case 0:\n"
2559             "  return; /* long long long long long long long long long long "
2560             "long long comment\n"
2561             "             line */\n"
2562             "}",
2563             format("switch (a) {\n"
2564                    "case 0: return; /* long long long long long long long long "
2565                    "long long long long comment line */\n"
2566                    "}",
2567                    Style));
2568   verifyFormat("switch (a) {\n"
2569                "#if FOO\n"
2570                "case 0: return 0;\n"
2571                "#endif\n"
2572                "}",
2573                Style);
2574   verifyFormat("switch (a) {\n"
2575                "case 1: {\n"
2576                "}\n"
2577                "case 2: {\n"
2578                "  return;\n"
2579                "}\n"
2580                "case 3: {\n"
2581                "  x = 1;\n"
2582                "  return;\n"
2583                "}\n"
2584                "case 4:\n"
2585                "  if (x)\n"
2586                "    return;\n"
2587                "}",
2588                Style);
2589   Style.ColumnLimit = 21;
2590   verifyFormat("switch (a) {\n"
2591                "case 1: x = 1; break;\n"
2592                "case 2: return;\n"
2593                "case 3:\n"
2594                "case 4:\n"
2595                "case 5: return;\n"
2596                "default:\n"
2597                "  y = 1;\n"
2598                "  break;\n"
2599                "}",
2600                Style);
2601   Style.ColumnLimit = 80;
2602   Style.AllowShortCaseLabelsOnASingleLine = false;
2603   Style.IndentCaseLabels = true;
2604   EXPECT_EQ("switch (n) {\n"
2605             "  default /*comments*/:\n"
2606             "    return true;\n"
2607             "  case 0:\n"
2608             "    return false;\n"
2609             "}",
2610             format("switch (n) {\n"
2611                    "default/*comments*/:\n"
2612                    "  return true;\n"
2613                    "case 0:\n"
2614                    "  return false;\n"
2615                    "}",
2616                    Style));
2617   Style.AllowShortCaseLabelsOnASingleLine = true;
2618   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2619   Style.BraceWrapping.AfterCaseLabel = true;
2620   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
2621   EXPECT_EQ("switch (n)\n"
2622             "{\n"
2623             "  case 0:\n"
2624             "  {\n"
2625             "    return false;\n"
2626             "  }\n"
2627             "  default:\n"
2628             "  {\n"
2629             "    return true;\n"
2630             "  }\n"
2631             "}",
2632             format("switch (n) {\n"
2633                    "  case 0: {\n"
2634                    "    return false;\n"
2635                    "  }\n"
2636                    "  default:\n"
2637                    "  {\n"
2638                    "    return true;\n"
2639                    "  }\n"
2640                    "}",
2641                    Style));
2642 }
2643 
TEST_F(FormatTest,FormatsLabels)2644 TEST_F(FormatTest, FormatsLabels) {
2645   verifyFormat("void f() {\n"
2646                "  some_code();\n"
2647                "test_label:\n"
2648                "  some_other_code();\n"
2649                "  {\n"
2650                "    some_more_code();\n"
2651                "  another_label:\n"
2652                "    some_more_code();\n"
2653                "  }\n"
2654                "}");
2655   verifyFormat("{\n"
2656                "  some_code();\n"
2657                "test_label:\n"
2658                "  some_other_code();\n"
2659                "}");
2660   verifyFormat("{\n"
2661                "  some_code();\n"
2662                "test_label:;\n"
2663                "  int i = 0;\n"
2664                "}");
2665   FormatStyle Style = getLLVMStyle();
2666   Style.IndentGotoLabels = false;
2667   verifyFormat("void f() {\n"
2668                "  some_code();\n"
2669                "test_label:\n"
2670                "  some_other_code();\n"
2671                "  {\n"
2672                "    some_more_code();\n"
2673                "another_label:\n"
2674                "    some_more_code();\n"
2675                "  }\n"
2676                "}",
2677                Style);
2678   verifyFormat("{\n"
2679                "  some_code();\n"
2680                "test_label:\n"
2681                "  some_other_code();\n"
2682                "}",
2683                Style);
2684   verifyFormat("{\n"
2685                "  some_code();\n"
2686                "test_label:;\n"
2687                "  int i = 0;\n"
2688                "}");
2689 }
2690 
TEST_F(FormatTest,MultiLineControlStatements)2691 TEST_F(FormatTest, MultiLineControlStatements) {
2692   FormatStyle Style = getLLVMStyle();
2693   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2694   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
2695   Style.ColumnLimit = 20;
2696   // Short lines should keep opening brace on same line.
2697   EXPECT_EQ("if (foo) {\n"
2698             "  bar();\n"
2699             "}",
2700             format("if(foo){bar();}", Style));
2701   EXPECT_EQ("if (foo) {\n"
2702             "  bar();\n"
2703             "} else {\n"
2704             "  baz();\n"
2705             "}",
2706             format("if(foo){bar();}else{baz();}", Style));
2707   EXPECT_EQ("if (foo && bar) {\n"
2708             "  baz();\n"
2709             "}",
2710             format("if(foo&&bar){baz();}", Style));
2711   EXPECT_EQ("if (foo) {\n"
2712             "  bar();\n"
2713             "} else if (baz) {\n"
2714             "  quux();\n"
2715             "}",
2716             format("if(foo){bar();}else if(baz){quux();}", Style));
2717   EXPECT_EQ(
2718       "if (foo) {\n"
2719       "  bar();\n"
2720       "} else if (baz) {\n"
2721       "  quux();\n"
2722       "} else {\n"
2723       "  foobar();\n"
2724       "}",
2725       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
2726   EXPECT_EQ("for (;;) {\n"
2727             "  foo();\n"
2728             "}",
2729             format("for(;;){foo();}"));
2730   EXPECT_EQ("while (1) {\n"
2731             "  foo();\n"
2732             "}",
2733             format("while(1){foo();}", Style));
2734   EXPECT_EQ("switch (foo) {\n"
2735             "case bar:\n"
2736             "  return;\n"
2737             "}",
2738             format("switch(foo){case bar:return;}", Style));
2739   EXPECT_EQ("try {\n"
2740             "  foo();\n"
2741             "} catch (...) {\n"
2742             "  bar();\n"
2743             "}",
2744             format("try{foo();}catch(...){bar();}", Style));
2745   EXPECT_EQ("do {\n"
2746             "  foo();\n"
2747             "} while (bar &&\n"
2748             "         baz);",
2749             format("do{foo();}while(bar&&baz);", Style));
2750   // Long lines should put opening brace on new line.
2751   EXPECT_EQ("if (foo && bar &&\n"
2752             "    baz)\n"
2753             "{\n"
2754             "  quux();\n"
2755             "}",
2756             format("if(foo&&bar&&baz){quux();}", Style));
2757   EXPECT_EQ("if (foo && bar &&\n"
2758             "    baz)\n"
2759             "{\n"
2760             "  quux();\n"
2761             "}",
2762             format("if (foo && bar &&\n"
2763                    "    baz) {\n"
2764                    "  quux();\n"
2765                    "}",
2766                    Style));
2767   EXPECT_EQ("if (foo) {\n"
2768             "  bar();\n"
2769             "} else if (baz ||\n"
2770             "           quux)\n"
2771             "{\n"
2772             "  foobar();\n"
2773             "}",
2774             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
2775   EXPECT_EQ(
2776       "if (foo) {\n"
2777       "  bar();\n"
2778       "} else if (baz ||\n"
2779       "           quux)\n"
2780       "{\n"
2781       "  foobar();\n"
2782       "} else {\n"
2783       "  barbaz();\n"
2784       "}",
2785       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2786              Style));
2787   EXPECT_EQ("for (int i = 0;\n"
2788             "     i < 10; ++i)\n"
2789             "{\n"
2790             "  foo();\n"
2791             "}",
2792             format("for(int i=0;i<10;++i){foo();}", Style));
2793   EXPECT_EQ("foreach (int i,\n"
2794             "         list)\n"
2795             "{\n"
2796             "  foo();\n"
2797             "}",
2798             format("foreach(int i, list){foo();}", Style));
2799   Style.ColumnLimit =
2800       40; // to concentrate at brace wrapping, not line wrap due to column limit
2801   EXPECT_EQ("foreach (int i, list) {\n"
2802             "  foo();\n"
2803             "}",
2804             format("foreach(int i, list){foo();}", Style));
2805   Style.ColumnLimit =
2806       20; // to concentrate at brace wrapping, not line wrap due to column limit
2807   EXPECT_EQ("while (foo || bar ||\n"
2808             "       baz)\n"
2809             "{\n"
2810             "  quux();\n"
2811             "}",
2812             format("while(foo||bar||baz){quux();}", Style));
2813   EXPECT_EQ("switch (\n"
2814             "    foo = barbaz)\n"
2815             "{\n"
2816             "case quux:\n"
2817             "  return;\n"
2818             "}",
2819             format("switch(foo=barbaz){case quux:return;}", Style));
2820   EXPECT_EQ("try {\n"
2821             "  foo();\n"
2822             "} catch (\n"
2823             "    Exception &bar)\n"
2824             "{\n"
2825             "  baz();\n"
2826             "}",
2827             format("try{foo();}catch(Exception&bar){baz();}", Style));
2828   Style.ColumnLimit =
2829       40; // to concentrate at brace wrapping, not line wrap due to column limit
2830   EXPECT_EQ("try {\n"
2831             "  foo();\n"
2832             "} catch (Exception &bar) {\n"
2833             "  baz();\n"
2834             "}",
2835             format("try{foo();}catch(Exception&bar){baz();}", Style));
2836   Style.ColumnLimit =
2837       20; // to concentrate at brace wrapping, not line wrap due to column limit
2838 
2839   Style.BraceWrapping.BeforeElse = true;
2840   EXPECT_EQ(
2841       "if (foo) {\n"
2842       "  bar();\n"
2843       "}\n"
2844       "else if (baz ||\n"
2845       "         quux)\n"
2846       "{\n"
2847       "  foobar();\n"
2848       "}\n"
2849       "else {\n"
2850       "  barbaz();\n"
2851       "}",
2852       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
2853              Style));
2854 
2855   Style.BraceWrapping.BeforeCatch = true;
2856   EXPECT_EQ("try {\n"
2857             "  foo();\n"
2858             "}\n"
2859             "catch (...) {\n"
2860             "  baz();\n"
2861             "}",
2862             format("try{foo();}catch(...){baz();}", Style));
2863 }
2864 
TEST_F(FormatTest,BeforeWhile)2865 TEST_F(FormatTest, BeforeWhile) {
2866   FormatStyle Style = getLLVMStyle();
2867   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
2868 
2869   verifyFormat("do {\n"
2870                "  foo();\n"
2871                "} while (1);",
2872                Style);
2873   Style.BraceWrapping.BeforeWhile = true;
2874   verifyFormat("do {\n"
2875                "  foo();\n"
2876                "}\n"
2877                "while (1);",
2878                Style);
2879 }
2880 
2881 //===----------------------------------------------------------------------===//
2882 // Tests for classes, namespaces, etc.
2883 //===----------------------------------------------------------------------===//
2884 
TEST_F(FormatTest,DoesNotBreakSemiAfterClassDecl)2885 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
2886   verifyFormat("class A {};");
2887 }
2888 
TEST_F(FormatTest,UnderstandsAccessSpecifiers)2889 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
2890   verifyFormat("class A {\n"
2891                "public:\n"
2892                "public: // comment\n"
2893                "protected:\n"
2894                "private:\n"
2895                "  void f() {}\n"
2896                "};");
2897   verifyFormat("export class A {\n"
2898                "public:\n"
2899                "public: // comment\n"
2900                "protected:\n"
2901                "private:\n"
2902                "  void f() {}\n"
2903                "};");
2904   verifyGoogleFormat("class A {\n"
2905                      " public:\n"
2906                      " protected:\n"
2907                      " private:\n"
2908                      "  void f() {}\n"
2909                      "};");
2910   verifyGoogleFormat("export class A {\n"
2911                      " public:\n"
2912                      " protected:\n"
2913                      " private:\n"
2914                      "  void f() {}\n"
2915                      "};");
2916   verifyFormat("class A {\n"
2917                "public slots:\n"
2918                "  void f1() {}\n"
2919                "public Q_SLOTS:\n"
2920                "  void f2() {}\n"
2921                "protected slots:\n"
2922                "  void f3() {}\n"
2923                "protected Q_SLOTS:\n"
2924                "  void f4() {}\n"
2925                "private slots:\n"
2926                "  void f5() {}\n"
2927                "private Q_SLOTS:\n"
2928                "  void f6() {}\n"
2929                "signals:\n"
2930                "  void g1();\n"
2931                "Q_SIGNALS:\n"
2932                "  void g2();\n"
2933                "};");
2934 
2935   // Don't interpret 'signals' the wrong way.
2936   verifyFormat("signals.set();");
2937   verifyFormat("for (Signals signals : f()) {\n}");
2938   verifyFormat("{\n"
2939                "  signals.set(); // This needs indentation.\n"
2940                "}");
2941   verifyFormat("void f() {\n"
2942                "label:\n"
2943                "  signals.baz();\n"
2944                "}");
2945 }
2946 
TEST_F(FormatTest,SeparatesLogicalBlocks)2947 TEST_F(FormatTest, SeparatesLogicalBlocks) {
2948   EXPECT_EQ("class A {\n"
2949             "public:\n"
2950             "  void f();\n"
2951             "\n"
2952             "private:\n"
2953             "  void g() {}\n"
2954             "  // test\n"
2955             "protected:\n"
2956             "  int h;\n"
2957             "};",
2958             format("class A {\n"
2959                    "public:\n"
2960                    "void f();\n"
2961                    "private:\n"
2962                    "void g() {}\n"
2963                    "// test\n"
2964                    "protected:\n"
2965                    "int h;\n"
2966                    "};"));
2967   EXPECT_EQ("class A {\n"
2968             "protected:\n"
2969             "public:\n"
2970             "  void f();\n"
2971             "};",
2972             format("class A {\n"
2973                    "protected:\n"
2974                    "\n"
2975                    "public:\n"
2976                    "\n"
2977                    "  void f();\n"
2978                    "};"));
2979 
2980   // Even ensure proper spacing inside macros.
2981   EXPECT_EQ("#define B     \\\n"
2982             "  class A {   \\\n"
2983             "   protected: \\\n"
2984             "   public:    \\\n"
2985             "    void f(); \\\n"
2986             "  };",
2987             format("#define B     \\\n"
2988                    "  class A {   \\\n"
2989                    "   protected: \\\n"
2990                    "              \\\n"
2991                    "   public:    \\\n"
2992                    "              \\\n"
2993                    "    void f(); \\\n"
2994                    "  };",
2995                    getGoogleStyle()));
2996   // But don't remove empty lines after macros ending in access specifiers.
2997   EXPECT_EQ("#define A private:\n"
2998             "\n"
2999             "int i;",
3000             format("#define A         private:\n"
3001                    "\n"
3002                    "int              i;"));
3003 }
3004 
TEST_F(FormatTest,FormatsClasses)3005 TEST_F(FormatTest, FormatsClasses) {
3006   verifyFormat("class A : public B {};");
3007   verifyFormat("class A : public ::B {};");
3008 
3009   verifyFormat(
3010       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3011       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3012   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3013                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3014                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
3015   verifyFormat(
3016       "class A : public B, public C, public D, public E, public F {};");
3017   verifyFormat("class AAAAAAAAAAAA : public B,\n"
3018                "                     public C,\n"
3019                "                     public D,\n"
3020                "                     public E,\n"
3021                "                     public F,\n"
3022                "                     public G {};");
3023 
3024   verifyFormat("class\n"
3025                "    ReallyReallyLongClassName {\n"
3026                "  int i;\n"
3027                "};",
3028                getLLVMStyleWithColumns(32));
3029   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3030                "                           aaaaaaaaaaaaaaaa> {};");
3031   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
3032                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
3033                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
3034   verifyFormat("template <class R, class C>\n"
3035                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
3036                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
3037   verifyFormat("class ::A::B {};");
3038 }
3039 
TEST_F(FormatTest,BreakInheritanceStyle)3040 TEST_F(FormatTest, BreakInheritanceStyle) {
3041   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
3042   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
3043       FormatStyle::BILS_BeforeComma;
3044   verifyFormat("class MyClass : public X {};",
3045                StyleWithInheritanceBreakBeforeComma);
3046   verifyFormat("class MyClass\n"
3047                "    : public X\n"
3048                "    , public Y {};",
3049                StyleWithInheritanceBreakBeforeComma);
3050   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
3051                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
3052                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3053                StyleWithInheritanceBreakBeforeComma);
3054   verifyFormat("struct aaaaaaaaaaaaa\n"
3055                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
3056                "          aaaaaaaaaaaaaaaa> {};",
3057                StyleWithInheritanceBreakBeforeComma);
3058 
3059   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
3060   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
3061       FormatStyle::BILS_AfterColon;
3062   verifyFormat("class MyClass : public X {};",
3063                StyleWithInheritanceBreakAfterColon);
3064   verifyFormat("class MyClass : public X, public Y {};",
3065                StyleWithInheritanceBreakAfterColon);
3066   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
3067                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3068                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
3069                StyleWithInheritanceBreakAfterColon);
3070   verifyFormat("struct aaaaaaaaaaaaa :\n"
3071                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
3072                "        aaaaaaaaaaaaaaaa> {};",
3073                StyleWithInheritanceBreakAfterColon);
3074 
3075   FormatStyle StyleWithInheritanceBreakAfterComma = getLLVMStyle();
3076   StyleWithInheritanceBreakAfterComma.BreakInheritanceList =
3077       FormatStyle::BILS_AfterComma;
3078   verifyFormat("class MyClass : public X {};",
3079                StyleWithInheritanceBreakAfterComma);
3080   verifyFormat("class MyClass : public X,\n"
3081                "                public Y {};",
3082                StyleWithInheritanceBreakAfterComma);
3083   verifyFormat(
3084       "class AAAAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
3085       "                               public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC "
3086       "{};",
3087       StyleWithInheritanceBreakAfterComma);
3088   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
3089                "                           aaaaaaaaaaaaaaaa> {};",
3090                StyleWithInheritanceBreakAfterComma);
3091   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
3092                "    : public OnceBreak,\n"
3093                "      public AlwaysBreak,\n"
3094                "      EvenBasesFitInOneLine {};",
3095                StyleWithInheritanceBreakAfterComma);
3096 }
3097 
TEST_F(FormatTest,FormatsVariableDeclarationsAfterStructOrClass)3098 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
3099   verifyFormat("class A {\n} a, b;");
3100   verifyFormat("struct A {\n} a, b;");
3101   verifyFormat("union A {\n} a;");
3102 }
3103 
TEST_F(FormatTest,FormatsEnum)3104 TEST_F(FormatTest, FormatsEnum) {
3105   verifyFormat("enum {\n"
3106                "  Zero,\n"
3107                "  One = 1,\n"
3108                "  Two = One + 1,\n"
3109                "  Three = (One + Two),\n"
3110                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3111                "  Five = (One, Two, Three, Four, 5)\n"
3112                "};");
3113   verifyGoogleFormat("enum {\n"
3114                      "  Zero,\n"
3115                      "  One = 1,\n"
3116                      "  Two = One + 1,\n"
3117                      "  Three = (One + Two),\n"
3118                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3119                      "  Five = (One, Two, Three, Four, 5)\n"
3120                      "};");
3121   verifyFormat("enum Enum {};");
3122   verifyFormat("enum {};");
3123   verifyFormat("enum X E {} d;");
3124   verifyFormat("enum __attribute__((...)) E {} d;");
3125   verifyFormat("enum __declspec__((...)) E {} d;");
3126   verifyFormat("enum {\n"
3127                "  Bar = Foo<int, int>::value\n"
3128                "};",
3129                getLLVMStyleWithColumns(30));
3130 
3131   verifyFormat("enum ShortEnum { A, B, C };");
3132   verifyGoogleFormat("enum ShortEnum { A, B, C };");
3133 
3134   EXPECT_EQ("enum KeepEmptyLines {\n"
3135             "  ONE,\n"
3136             "\n"
3137             "  TWO,\n"
3138             "\n"
3139             "  THREE\n"
3140             "}",
3141             format("enum KeepEmptyLines {\n"
3142                    "  ONE,\n"
3143                    "\n"
3144                    "  TWO,\n"
3145                    "\n"
3146                    "\n"
3147                    "  THREE\n"
3148                    "}"));
3149   verifyFormat("enum E { // comment\n"
3150                "  ONE,\n"
3151                "  TWO\n"
3152                "};\n"
3153                "int i;");
3154 
3155   FormatStyle EightIndent = getLLVMStyle();
3156   EightIndent.IndentWidth = 8;
3157   verifyFormat("enum {\n"
3158                "        VOID,\n"
3159                "        CHAR,\n"
3160                "        SHORT,\n"
3161                "        INT,\n"
3162                "        LONG,\n"
3163                "        SIGNED,\n"
3164                "        UNSIGNED,\n"
3165                "        BOOL,\n"
3166                "        FLOAT,\n"
3167                "        DOUBLE,\n"
3168                "        COMPLEX\n"
3169                "};",
3170                EightIndent);
3171 
3172   // Not enums.
3173   verifyFormat("enum X f() {\n"
3174                "  a();\n"
3175                "  return 42;\n"
3176                "}");
3177   verifyFormat("enum X Type::f() {\n"
3178                "  a();\n"
3179                "  return 42;\n"
3180                "}");
3181   verifyFormat("enum ::X f() {\n"
3182                "  a();\n"
3183                "  return 42;\n"
3184                "}");
3185   verifyFormat("enum ns::X f() {\n"
3186                "  a();\n"
3187                "  return 42;\n"
3188                "}");
3189 }
3190 
TEST_F(FormatTest,FormatsEnumsWithErrors)3191 TEST_F(FormatTest, FormatsEnumsWithErrors) {
3192   verifyFormat("enum Type {\n"
3193                "  One = 0; // These semicolons should be commas.\n"
3194                "  Two = 1;\n"
3195                "};");
3196   verifyFormat("namespace n {\n"
3197                "enum Type {\n"
3198                "  One,\n"
3199                "  Two, // missing };\n"
3200                "  int i;\n"
3201                "}\n"
3202                "void g() {}");
3203 }
3204 
TEST_F(FormatTest,FormatsEnumStruct)3205 TEST_F(FormatTest, FormatsEnumStruct) {
3206   verifyFormat("enum struct {\n"
3207                "  Zero,\n"
3208                "  One = 1,\n"
3209                "  Two = One + 1,\n"
3210                "  Three = (One + Two),\n"
3211                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3212                "  Five = (One, Two, Three, Four, 5)\n"
3213                "};");
3214   verifyFormat("enum struct Enum {};");
3215   verifyFormat("enum struct {};");
3216   verifyFormat("enum struct X E {} d;");
3217   verifyFormat("enum struct __attribute__((...)) E {} d;");
3218   verifyFormat("enum struct __declspec__((...)) E {} d;");
3219   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
3220 }
3221 
TEST_F(FormatTest,FormatsEnumClass)3222 TEST_F(FormatTest, FormatsEnumClass) {
3223   verifyFormat("enum class {\n"
3224                "  Zero,\n"
3225                "  One = 1,\n"
3226                "  Two = One + 1,\n"
3227                "  Three = (One + Two),\n"
3228                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
3229                "  Five = (One, Two, Three, Four, 5)\n"
3230                "};");
3231   verifyFormat("enum class Enum {};");
3232   verifyFormat("enum class {};");
3233   verifyFormat("enum class X E {} d;");
3234   verifyFormat("enum class __attribute__((...)) E {} d;");
3235   verifyFormat("enum class __declspec__((...)) E {} d;");
3236   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
3237 }
3238 
TEST_F(FormatTest,FormatsEnumTypes)3239 TEST_F(FormatTest, FormatsEnumTypes) {
3240   verifyFormat("enum X : int {\n"
3241                "  A, // Force multiple lines.\n"
3242                "  B\n"
3243                "};");
3244   verifyFormat("enum X : int { A, B };");
3245   verifyFormat("enum X : std::uint32_t { A, B };");
3246 }
3247 
TEST_F(FormatTest,FormatsTypedefEnum)3248 TEST_F(FormatTest, FormatsTypedefEnum) {
3249   FormatStyle Style = getLLVMStyle();
3250   Style.ColumnLimit = 40;
3251   verifyFormat("typedef enum {} EmptyEnum;");
3252   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3253   verifyFormat("typedef enum {\n"
3254                "  ZERO = 0,\n"
3255                "  ONE = 1,\n"
3256                "  TWO = 2,\n"
3257                "  THREE = 3\n"
3258                "} LongEnum;",
3259                Style);
3260   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3261   Style.BraceWrapping.AfterEnum = true;
3262   verifyFormat("typedef enum {} EmptyEnum;");
3263   verifyFormat("typedef enum { A, B, C } ShortEnum;");
3264   verifyFormat("typedef enum\n"
3265                "{\n"
3266                "  ZERO = 0,\n"
3267                "  ONE = 1,\n"
3268                "  TWO = 2,\n"
3269                "  THREE = 3\n"
3270                "} LongEnum;",
3271                Style);
3272 }
3273 
TEST_F(FormatTest,FormatsNSEnums)3274 TEST_F(FormatTest, FormatsNSEnums) {
3275   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
3276   verifyGoogleFormat(
3277       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
3278   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
3279                      "  // Information about someDecentlyLongValue.\n"
3280                      "  someDecentlyLongValue,\n"
3281                      "  // Information about anotherDecentlyLongValue.\n"
3282                      "  anotherDecentlyLongValue,\n"
3283                      "  // Information about aThirdDecentlyLongValue.\n"
3284                      "  aThirdDecentlyLongValue\n"
3285                      "};");
3286   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
3287                      "  // Information about someDecentlyLongValue.\n"
3288                      "  someDecentlyLongValue,\n"
3289                      "  // Information about anotherDecentlyLongValue.\n"
3290                      "  anotherDecentlyLongValue,\n"
3291                      "  // Information about aThirdDecentlyLongValue.\n"
3292                      "  aThirdDecentlyLongValue\n"
3293                      "};");
3294   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
3295                      "  a = 1,\n"
3296                      "  b = 2,\n"
3297                      "  c = 3,\n"
3298                      "};");
3299   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
3300                      "  a = 1,\n"
3301                      "  b = 2,\n"
3302                      "  c = 3,\n"
3303                      "};");
3304   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
3305                      "  a = 1,\n"
3306                      "  b = 2,\n"
3307                      "  c = 3,\n"
3308                      "};");
3309   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
3310                      "  a = 1,\n"
3311                      "  b = 2,\n"
3312                      "  c = 3,\n"
3313                      "};");
3314 }
3315 
TEST_F(FormatTest,FormatsBitfields)3316 TEST_F(FormatTest, FormatsBitfields) {
3317   verifyFormat("struct Bitfields {\n"
3318                "  unsigned sClass : 8;\n"
3319                "  unsigned ValueKind : 2;\n"
3320                "};");
3321   verifyFormat("struct A {\n"
3322                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
3323                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
3324                "};");
3325   verifyFormat("struct MyStruct {\n"
3326                "  uchar data;\n"
3327                "  uchar : 8;\n"
3328                "  uchar : 8;\n"
3329                "  uchar other;\n"
3330                "};");
3331   FormatStyle Style = getLLVMStyle();
3332   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
3333   verifyFormat("struct Bitfields {\n"
3334                "  unsigned sClass:8;\n"
3335                "  unsigned ValueKind:2;\n"
3336                "  uchar other;\n"
3337                "};",
3338                Style);
3339   verifyFormat("struct A {\n"
3340                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
3341                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
3342                "};",
3343                Style);
3344   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
3345   verifyFormat("struct Bitfields {\n"
3346                "  unsigned sClass :8;\n"
3347                "  unsigned ValueKind :2;\n"
3348                "  uchar other;\n"
3349                "};",
3350                Style);
3351   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
3352   verifyFormat("struct Bitfields {\n"
3353                "  unsigned sClass: 8;\n"
3354                "  unsigned ValueKind: 2;\n"
3355                "  uchar other;\n"
3356                "};",
3357                Style);
3358 }
3359 
TEST_F(FormatTest,FormatsNamespaces)3360 TEST_F(FormatTest, FormatsNamespaces) {
3361   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
3362   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
3363 
3364   verifyFormat("namespace some_namespace {\n"
3365                "class A {};\n"
3366                "void f() { f(); }\n"
3367                "}",
3368                LLVMWithNoNamespaceFix);
3369   verifyFormat("namespace N::inline D {\n"
3370                "class A {};\n"
3371                "void f() { f(); }\n"
3372                "}",
3373                LLVMWithNoNamespaceFix);
3374   verifyFormat("namespace N::inline D::E {\n"
3375                "class A {};\n"
3376                "void f() { f(); }\n"
3377                "}",
3378                LLVMWithNoNamespaceFix);
3379   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
3380                "class A {};\n"
3381                "void f() { f(); }\n"
3382                "}",
3383                LLVMWithNoNamespaceFix);
3384   verifyFormat("/* something */ namespace some_namespace {\n"
3385                "class A {};\n"
3386                "void f() { f(); }\n"
3387                "}",
3388                LLVMWithNoNamespaceFix);
3389   verifyFormat("namespace {\n"
3390                "class A {};\n"
3391                "void f() { f(); }\n"
3392                "}",
3393                LLVMWithNoNamespaceFix);
3394   verifyFormat("/* something */ namespace {\n"
3395                "class A {};\n"
3396                "void f() { f(); }\n"
3397                "}",
3398                LLVMWithNoNamespaceFix);
3399   verifyFormat("inline namespace X {\n"
3400                "class A {};\n"
3401                "void f() { f(); }\n"
3402                "}",
3403                LLVMWithNoNamespaceFix);
3404   verifyFormat("/* something */ inline namespace X {\n"
3405                "class A {};\n"
3406                "void f() { f(); }\n"
3407                "}",
3408                LLVMWithNoNamespaceFix);
3409   verifyFormat("export namespace X {\n"
3410                "class A {};\n"
3411                "void f() { f(); }\n"
3412                "}",
3413                LLVMWithNoNamespaceFix);
3414   verifyFormat("using namespace some_namespace;\n"
3415                "class A {};\n"
3416                "void f() { f(); }",
3417                LLVMWithNoNamespaceFix);
3418 
3419   // This code is more common than we thought; if we
3420   // layout this correctly the semicolon will go into
3421   // its own line, which is undesirable.
3422   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
3423   verifyFormat("namespace {\n"
3424                "class A {};\n"
3425                "};",
3426                LLVMWithNoNamespaceFix);
3427 
3428   verifyFormat("namespace {\n"
3429                "int SomeVariable = 0; // comment\n"
3430                "} // namespace",
3431                LLVMWithNoNamespaceFix);
3432   EXPECT_EQ("#ifndef HEADER_GUARD\n"
3433             "#define HEADER_GUARD\n"
3434             "namespace my_namespace {\n"
3435             "int i;\n"
3436             "} // my_namespace\n"
3437             "#endif // HEADER_GUARD",
3438             format("#ifndef HEADER_GUARD\n"
3439                    " #define HEADER_GUARD\n"
3440                    "   namespace my_namespace {\n"
3441                    "int i;\n"
3442                    "}    // my_namespace\n"
3443                    "#endif    // HEADER_GUARD",
3444                    LLVMWithNoNamespaceFix));
3445 
3446   EXPECT_EQ("namespace A::B {\n"
3447             "class C {};\n"
3448             "}",
3449             format("namespace A::B {\n"
3450                    "class C {};\n"
3451                    "}",
3452                    LLVMWithNoNamespaceFix));
3453 
3454   FormatStyle Style = getLLVMStyle();
3455   Style.NamespaceIndentation = FormatStyle::NI_All;
3456   EXPECT_EQ("namespace out {\n"
3457             "  int i;\n"
3458             "  namespace in {\n"
3459             "    int i;\n"
3460             "  } // namespace in\n"
3461             "} // namespace out",
3462             format("namespace out {\n"
3463                    "int i;\n"
3464                    "namespace in {\n"
3465                    "int i;\n"
3466                    "} // namespace in\n"
3467                    "} // namespace out",
3468                    Style));
3469 
3470   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3471   EXPECT_EQ("namespace out {\n"
3472             "int i;\n"
3473             "namespace in {\n"
3474             "  int i;\n"
3475             "} // namespace in\n"
3476             "} // namespace out",
3477             format("namespace out {\n"
3478                    "int i;\n"
3479                    "namespace in {\n"
3480                    "int i;\n"
3481                    "} // namespace in\n"
3482                    "} // namespace out",
3483                    Style));
3484 }
3485 
TEST_F(FormatTest,NamespaceMacros)3486 TEST_F(FormatTest, NamespaceMacros) {
3487   FormatStyle Style = getLLVMStyle();
3488   Style.NamespaceMacros.push_back("TESTSUITE");
3489 
3490   verifyFormat("TESTSUITE(A) {\n"
3491                "int foo();\n"
3492                "} // TESTSUITE(A)",
3493                Style);
3494 
3495   verifyFormat("TESTSUITE(A, B) {\n"
3496                "int foo();\n"
3497                "} // TESTSUITE(A)",
3498                Style);
3499 
3500   // Properly indent according to NamespaceIndentation style
3501   Style.NamespaceIndentation = FormatStyle::NI_All;
3502   verifyFormat("TESTSUITE(A) {\n"
3503                "  int foo();\n"
3504                "} // TESTSUITE(A)",
3505                Style);
3506   verifyFormat("TESTSUITE(A) {\n"
3507                "  namespace B {\n"
3508                "    int foo();\n"
3509                "  } // namespace B\n"
3510                "} // TESTSUITE(A)",
3511                Style);
3512   verifyFormat("namespace A {\n"
3513                "  TESTSUITE(B) {\n"
3514                "    int foo();\n"
3515                "  } // TESTSUITE(B)\n"
3516                "} // namespace A",
3517                Style);
3518 
3519   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3520   verifyFormat("TESTSUITE(A) {\n"
3521                "TESTSUITE(B) {\n"
3522                "  int foo();\n"
3523                "} // TESTSUITE(B)\n"
3524                "} // TESTSUITE(A)",
3525                Style);
3526   verifyFormat("TESTSUITE(A) {\n"
3527                "namespace B {\n"
3528                "  int foo();\n"
3529                "} // namespace B\n"
3530                "} // TESTSUITE(A)",
3531                Style);
3532   verifyFormat("namespace A {\n"
3533                "TESTSUITE(B) {\n"
3534                "  int foo();\n"
3535                "} // TESTSUITE(B)\n"
3536                "} // namespace A",
3537                Style);
3538 
3539   // Properly merge namespace-macros blocks in CompactNamespaces mode
3540   Style.NamespaceIndentation = FormatStyle::NI_None;
3541   Style.CompactNamespaces = true;
3542   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
3543                "}} // TESTSUITE(A::B)",
3544                Style);
3545 
3546   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3547             "}} // TESTSUITE(out::in)",
3548             format("TESTSUITE(out) {\n"
3549                    "TESTSUITE(in) {\n"
3550                    "} // TESTSUITE(in)\n"
3551                    "} // TESTSUITE(out)",
3552                    Style));
3553 
3554   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
3555             "}} // TESTSUITE(out::in)",
3556             format("TESTSUITE(out) {\n"
3557                    "TESTSUITE(in) {\n"
3558                    "} // TESTSUITE(in)\n"
3559                    "} // TESTSUITE(out)",
3560                    Style));
3561 
3562   // Do not merge different namespaces/macros
3563   EXPECT_EQ("namespace out {\n"
3564             "TESTSUITE(in) {\n"
3565             "} // TESTSUITE(in)\n"
3566             "} // namespace out",
3567             format("namespace out {\n"
3568                    "TESTSUITE(in) {\n"
3569                    "} // TESTSUITE(in)\n"
3570                    "} // namespace out",
3571                    Style));
3572   EXPECT_EQ("TESTSUITE(out) {\n"
3573             "namespace in {\n"
3574             "} // namespace in\n"
3575             "} // TESTSUITE(out)",
3576             format("TESTSUITE(out) {\n"
3577                    "namespace in {\n"
3578                    "} // namespace in\n"
3579                    "} // TESTSUITE(out)",
3580                    Style));
3581   Style.NamespaceMacros.push_back("FOOBAR");
3582   EXPECT_EQ("TESTSUITE(out) {\n"
3583             "FOOBAR(in) {\n"
3584             "} // FOOBAR(in)\n"
3585             "} // TESTSUITE(out)",
3586             format("TESTSUITE(out) {\n"
3587                    "FOOBAR(in) {\n"
3588                    "} // FOOBAR(in)\n"
3589                    "} // TESTSUITE(out)",
3590                    Style));
3591 }
3592 
TEST_F(FormatTest,FormatsCompactNamespaces)3593 TEST_F(FormatTest, FormatsCompactNamespaces) {
3594   FormatStyle Style = getLLVMStyle();
3595   Style.CompactNamespaces = true;
3596   Style.NamespaceMacros.push_back("TESTSUITE");
3597 
3598   verifyFormat("namespace A { namespace B {\n"
3599                "}} // namespace A::B",
3600                Style);
3601 
3602   EXPECT_EQ("namespace out { namespace in {\n"
3603             "}} // namespace out::in",
3604             format("namespace out {\n"
3605                    "namespace in {\n"
3606                    "} // namespace in\n"
3607                    "} // namespace out",
3608                    Style));
3609 
3610   // Only namespaces which have both consecutive opening and end get compacted
3611   EXPECT_EQ("namespace out {\n"
3612             "namespace in1 {\n"
3613             "} // namespace in1\n"
3614             "namespace in2 {\n"
3615             "} // namespace in2\n"
3616             "} // namespace out",
3617             format("namespace out {\n"
3618                    "namespace in1 {\n"
3619                    "} // namespace in1\n"
3620                    "namespace in2 {\n"
3621                    "} // namespace in2\n"
3622                    "} // namespace out",
3623                    Style));
3624 
3625   EXPECT_EQ("namespace out {\n"
3626             "int i;\n"
3627             "namespace in {\n"
3628             "int j;\n"
3629             "} // namespace in\n"
3630             "int k;\n"
3631             "} // namespace out",
3632             format("namespace out { int i;\n"
3633                    "namespace in { int j; } // namespace in\n"
3634                    "int k; } // namespace out",
3635                    Style));
3636 
3637   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
3638             "}}} // namespace A::B::C\n",
3639             format("namespace A { namespace B {\n"
3640                    "namespace C {\n"
3641                    "}} // namespace B::C\n"
3642                    "} // namespace A\n",
3643                    Style));
3644 
3645   Style.ColumnLimit = 40;
3646   EXPECT_EQ("namespace aaaaaaaaaa {\n"
3647             "namespace bbbbbbbbbb {\n"
3648             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
3649             format("namespace aaaaaaaaaa {\n"
3650                    "namespace bbbbbbbbbb {\n"
3651                    "} // namespace bbbbbbbbbb\n"
3652                    "} // namespace aaaaaaaaaa",
3653                    Style));
3654 
3655   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
3656             "namespace cccccc {\n"
3657             "}}} // namespace aaaaaa::bbbbbb::cccccc",
3658             format("namespace aaaaaa {\n"
3659                    "namespace bbbbbb {\n"
3660                    "namespace cccccc {\n"
3661                    "} // namespace cccccc\n"
3662                    "} // namespace bbbbbb\n"
3663                    "} // namespace aaaaaa",
3664                    Style));
3665   Style.ColumnLimit = 80;
3666 
3667   // Extra semicolon after 'inner' closing brace prevents merging
3668   EXPECT_EQ("namespace out { namespace in {\n"
3669             "}; } // namespace out::in",
3670             format("namespace out {\n"
3671                    "namespace in {\n"
3672                    "}; // namespace in\n"
3673                    "} // namespace out",
3674                    Style));
3675 
3676   // Extra semicolon after 'outer' closing brace is conserved
3677   EXPECT_EQ("namespace out { namespace in {\n"
3678             "}}; // namespace out::in",
3679             format("namespace out {\n"
3680                    "namespace in {\n"
3681                    "} // namespace in\n"
3682                    "}; // namespace out",
3683                    Style));
3684 
3685   Style.NamespaceIndentation = FormatStyle::NI_All;
3686   EXPECT_EQ("namespace out { namespace in {\n"
3687             "  int i;\n"
3688             "}} // namespace out::in",
3689             format("namespace out {\n"
3690                    "namespace in {\n"
3691                    "int i;\n"
3692                    "} // namespace in\n"
3693                    "} // namespace out",
3694                    Style));
3695   EXPECT_EQ("namespace out { namespace mid {\n"
3696             "  namespace in {\n"
3697             "    int j;\n"
3698             "  } // namespace in\n"
3699             "  int k;\n"
3700             "}} // namespace out::mid",
3701             format("namespace out { namespace mid {\n"
3702                    "namespace in { int j; } // namespace in\n"
3703                    "int k; }} // namespace out::mid",
3704                    Style));
3705 
3706   Style.NamespaceIndentation = FormatStyle::NI_Inner;
3707   EXPECT_EQ("namespace out { namespace in {\n"
3708             "  int i;\n"
3709             "}} // namespace out::in",
3710             format("namespace out {\n"
3711                    "namespace in {\n"
3712                    "int i;\n"
3713                    "} // namespace in\n"
3714                    "} // namespace out",
3715                    Style));
3716   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
3717             "  int i;\n"
3718             "}}} // namespace out::mid::in",
3719             format("namespace out {\n"
3720                    "namespace mid {\n"
3721                    "namespace in {\n"
3722                    "int i;\n"
3723                    "} // namespace in\n"
3724                    "} // namespace mid\n"
3725                    "} // namespace out",
3726                    Style));
3727 }
3728 
TEST_F(FormatTest,FormatsExternC)3729 TEST_F(FormatTest, FormatsExternC) {
3730   verifyFormat("extern \"C\" {\nint a;");
3731   verifyFormat("extern \"C\" {}");
3732   verifyFormat("extern \"C\" {\n"
3733                "int foo();\n"
3734                "}");
3735   verifyFormat("extern \"C\" int foo() {}");
3736   verifyFormat("extern \"C\" int foo();");
3737   verifyFormat("extern \"C\" int foo() {\n"
3738                "  int i = 42;\n"
3739                "  return i;\n"
3740                "}");
3741 
3742   FormatStyle Style = getLLVMStyle();
3743   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3744   Style.BraceWrapping.AfterFunction = true;
3745   verifyFormat("extern \"C\" int foo() {}", Style);
3746   verifyFormat("extern \"C\" int foo();", Style);
3747   verifyFormat("extern \"C\" int foo()\n"
3748                "{\n"
3749                "  int i = 42;\n"
3750                "  return i;\n"
3751                "}",
3752                Style);
3753 
3754   Style.BraceWrapping.AfterExternBlock = true;
3755   Style.BraceWrapping.SplitEmptyRecord = false;
3756   verifyFormat("extern \"C\"\n"
3757                "{}",
3758                Style);
3759   verifyFormat("extern \"C\"\n"
3760                "{\n"
3761                "  int foo();\n"
3762                "}",
3763                Style);
3764 }
3765 
TEST_F(FormatTest,IndentExternBlockStyle)3766 TEST_F(FormatTest, IndentExternBlockStyle) {
3767   FormatStyle Style = getLLVMStyle();
3768   Style.IndentWidth = 2;
3769 
3770   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
3771   verifyFormat("extern \"C\" { /*9*/\n}", Style);
3772   verifyFormat("extern \"C\" {\n"
3773                "  int foo10();\n"
3774                "}",
3775                Style);
3776 
3777   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
3778   verifyFormat("extern \"C\" { /*11*/\n}", Style);
3779   verifyFormat("extern \"C\" {\n"
3780                "int foo12();\n"
3781                "}",
3782                Style);
3783 
3784   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
3785   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3786   Style.BraceWrapping.AfterExternBlock = true;
3787   verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
3788   verifyFormat("extern \"C\"\n{\n"
3789                "  int foo14();\n"
3790                "}",
3791                Style);
3792 
3793   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
3794   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3795   Style.BraceWrapping.AfterExternBlock = false;
3796   verifyFormat("extern \"C\" { /*15*/\n}", Style);
3797   verifyFormat("extern \"C\" {\n"
3798                "int foo16();\n"
3799                "}",
3800                Style);
3801 }
3802 
TEST_F(FormatTest,FormatsInlineASM)3803 TEST_F(FormatTest, FormatsInlineASM) {
3804   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
3805   verifyFormat("asm(\"nop\" ::: \"memory\");");
3806   verifyFormat(
3807       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
3808       "    \"cpuid\\n\\t\"\n"
3809       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
3810       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
3811       "    : \"a\"(value));");
3812   EXPECT_EQ(
3813       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
3814       "  __asm {\n"
3815       "        mov     edx,[that] // vtable in edx\n"
3816       "        mov     eax,methodIndex\n"
3817       "        call    [edx][eax*4] // stdcall\n"
3818       "  }\n"
3819       "}",
3820       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
3821              "    __asm {\n"
3822              "        mov     edx,[that] // vtable in edx\n"
3823              "        mov     eax,methodIndex\n"
3824              "        call    [edx][eax*4] // stdcall\n"
3825              "    }\n"
3826              "}"));
3827   EXPECT_EQ("_asm {\n"
3828             "  xor eax, eax;\n"
3829             "  cpuid;\n"
3830             "}",
3831             format("_asm {\n"
3832                    "  xor eax, eax;\n"
3833                    "  cpuid;\n"
3834                    "}"));
3835   verifyFormat("void function() {\n"
3836                "  // comment\n"
3837                "  asm(\"\");\n"
3838                "}");
3839   EXPECT_EQ("__asm {\n"
3840             "}\n"
3841             "int i;",
3842             format("__asm   {\n"
3843                    "}\n"
3844                    "int   i;"));
3845 }
3846 
TEST_F(FormatTest,FormatTryCatch)3847 TEST_F(FormatTest, FormatTryCatch) {
3848   verifyFormat("try {\n"
3849                "  throw a * b;\n"
3850                "} catch (int a) {\n"
3851                "  // Do nothing.\n"
3852                "} catch (...) {\n"
3853                "  exit(42);\n"
3854                "}");
3855 
3856   // Function-level try statements.
3857   verifyFormat("int f() try { return 4; } catch (...) {\n"
3858                "  return 5;\n"
3859                "}");
3860   verifyFormat("class A {\n"
3861                "  int a;\n"
3862                "  A() try : a(0) {\n"
3863                "  } catch (...) {\n"
3864                "    throw;\n"
3865                "  }\n"
3866                "};\n");
3867   verifyFormat("class A {\n"
3868                "  int a;\n"
3869                "  A() try : a(0), b{1} {\n"
3870                "  } catch (...) {\n"
3871                "    throw;\n"
3872                "  }\n"
3873                "};\n");
3874   verifyFormat("class A {\n"
3875                "  int a;\n"
3876                "  A() try : a(0), b{1}, c{2} {\n"
3877                "  } catch (...) {\n"
3878                "    throw;\n"
3879                "  }\n"
3880                "};\n");
3881   verifyFormat("class A {\n"
3882                "  int a;\n"
3883                "  A() try : a(0), b{1}, c{2} {\n"
3884                "    { // New scope.\n"
3885                "    }\n"
3886                "  } catch (...) {\n"
3887                "    throw;\n"
3888                "  }\n"
3889                "};\n");
3890 
3891   // Incomplete try-catch blocks.
3892   verifyIncompleteFormat("try {} catch (");
3893 }
3894 
TEST_F(FormatTest,FormatTryAsAVariable)3895 TEST_F(FormatTest, FormatTryAsAVariable) {
3896   verifyFormat("int try;");
3897   verifyFormat("int try, size;");
3898   verifyFormat("try = foo();");
3899   verifyFormat("if (try < size) {\n  return true;\n}");
3900 
3901   verifyFormat("int catch;");
3902   verifyFormat("int catch, size;");
3903   verifyFormat("catch = foo();");
3904   verifyFormat("if (catch < size) {\n  return true;\n}");
3905 
3906   FormatStyle Style = getLLVMStyle();
3907   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3908   Style.BraceWrapping.AfterFunction = true;
3909   Style.BraceWrapping.BeforeCatch = true;
3910   verifyFormat("try {\n"
3911                "  int bar = 1;\n"
3912                "}\n"
3913                "catch (...) {\n"
3914                "  int bar = 1;\n"
3915                "}",
3916                Style);
3917   verifyFormat("#if NO_EX\n"
3918                "try\n"
3919                "#endif\n"
3920                "{\n"
3921                "}\n"
3922                "#if NO_EX\n"
3923                "catch (...) {\n"
3924                "}",
3925                Style);
3926   verifyFormat("try /* abc */ {\n"
3927                "  int bar = 1;\n"
3928                "}\n"
3929                "catch (...) {\n"
3930                "  int bar = 1;\n"
3931                "}",
3932                Style);
3933   verifyFormat("try\n"
3934                "// abc\n"
3935                "{\n"
3936                "  int bar = 1;\n"
3937                "}\n"
3938                "catch (...) {\n"
3939                "  int bar = 1;\n"
3940                "}",
3941                Style);
3942 }
3943 
TEST_F(FormatTest,FormatSEHTryCatch)3944 TEST_F(FormatTest, FormatSEHTryCatch) {
3945   verifyFormat("__try {\n"
3946                "  int a = b * c;\n"
3947                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
3948                "  // Do nothing.\n"
3949                "}");
3950 
3951   verifyFormat("__try {\n"
3952                "  int a = b * c;\n"
3953                "} __finally {\n"
3954                "  // Do nothing.\n"
3955                "}");
3956 
3957   verifyFormat("DEBUG({\n"
3958                "  __try {\n"
3959                "  } __finally {\n"
3960                "  }\n"
3961                "});\n");
3962 }
3963 
TEST_F(FormatTest,IncompleteTryCatchBlocks)3964 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
3965   verifyFormat("try {\n"
3966                "  f();\n"
3967                "} catch {\n"
3968                "  g();\n"
3969                "}");
3970   verifyFormat("try {\n"
3971                "  f();\n"
3972                "} catch (A a) MACRO(x) {\n"
3973                "  g();\n"
3974                "} catch (B b) MACRO(x) {\n"
3975                "  g();\n"
3976                "}");
3977 }
3978 
TEST_F(FormatTest,FormatTryCatchBraceStyles)3979 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
3980   FormatStyle Style = getLLVMStyle();
3981   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
3982                           FormatStyle::BS_WebKit}) {
3983     Style.BreakBeforeBraces = BraceStyle;
3984     verifyFormat("try {\n"
3985                  "  // something\n"
3986                  "} catch (...) {\n"
3987                  "  // something\n"
3988                  "}",
3989                  Style);
3990   }
3991   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
3992   verifyFormat("try {\n"
3993                "  // something\n"
3994                "}\n"
3995                "catch (...) {\n"
3996                "  // something\n"
3997                "}",
3998                Style);
3999   verifyFormat("__try {\n"
4000                "  // something\n"
4001                "}\n"
4002                "__finally {\n"
4003                "  // something\n"
4004                "}",
4005                Style);
4006   verifyFormat("@try {\n"
4007                "  // something\n"
4008                "}\n"
4009                "@finally {\n"
4010                "  // something\n"
4011                "}",
4012                Style);
4013   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
4014   verifyFormat("try\n"
4015                "{\n"
4016                "  // something\n"
4017                "}\n"
4018                "catch (...)\n"
4019                "{\n"
4020                "  // something\n"
4021                "}",
4022                Style);
4023   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
4024   verifyFormat("try\n"
4025                "  {\n"
4026                "  // something white\n"
4027                "  }\n"
4028                "catch (...)\n"
4029                "  {\n"
4030                "  // something white\n"
4031                "  }",
4032                Style);
4033   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
4034   verifyFormat("try\n"
4035                "  {\n"
4036                "    // something\n"
4037                "  }\n"
4038                "catch (...)\n"
4039                "  {\n"
4040                "    // something\n"
4041                "  }",
4042                Style);
4043   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4044   Style.BraceWrapping.BeforeCatch = true;
4045   verifyFormat("try {\n"
4046                "  // something\n"
4047                "}\n"
4048                "catch (...) {\n"
4049                "  // something\n"
4050                "}",
4051                Style);
4052 }
4053 
TEST_F(FormatTest,StaticInitializers)4054 TEST_F(FormatTest, StaticInitializers) {
4055   verifyFormat("static SomeClass SC = {1, 'a'};");
4056 
4057   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
4058                "    100000000, "
4059                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
4060 
4061   // Here, everything other than the "}" would fit on a line.
4062   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
4063                "    10000000000000000000000000};");
4064   EXPECT_EQ("S s = {a,\n"
4065             "\n"
4066             "       b};",
4067             format("S s = {\n"
4068                    "  a,\n"
4069                    "\n"
4070                    "  b\n"
4071                    "};"));
4072 
4073   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
4074   // line. However, the formatting looks a bit off and this probably doesn't
4075   // happen often in practice.
4076   verifyFormat("static int Variable[1] = {\n"
4077                "    {1000000000000000000000000000000000000}};",
4078                getLLVMStyleWithColumns(40));
4079 }
4080 
TEST_F(FormatTest,DesignatedInitializers)4081 TEST_F(FormatTest, DesignatedInitializers) {
4082   verifyFormat("const struct A a = {.a = 1, .b = 2};");
4083   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
4084                "                    .bbbbbbbbbb = 2,\n"
4085                "                    .cccccccccc = 3,\n"
4086                "                    .dddddddddd = 4,\n"
4087                "                    .eeeeeeeeee = 5};");
4088   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4089                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
4090                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
4091                "    .ccccccccccccccccccccccccccc = 3,\n"
4092                "    .ddddddddddddddddddddddddddd = 4,\n"
4093                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
4094 
4095   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
4096 
4097   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
4098   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
4099                "                    [2] = bbbbbbbbbb,\n"
4100                "                    [3] = cccccccccc,\n"
4101                "                    [4] = dddddddddd,\n"
4102                "                    [5] = eeeeeeeeee};");
4103   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
4104                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4105                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4106                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
4107                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
4108                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
4109 }
4110 
TEST_F(FormatTest,NestedStaticInitializers)4111 TEST_F(FormatTest, NestedStaticInitializers) {
4112   verifyFormat("static A x = {{{}}};\n");
4113   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
4114                "               {init1, init2, init3, init4}}};",
4115                getLLVMStyleWithColumns(50));
4116 
4117   verifyFormat("somes Status::global_reps[3] = {\n"
4118                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4119                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4120                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
4121                getLLVMStyleWithColumns(60));
4122   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
4123                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
4124                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
4125                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
4126   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
4127                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
4128                "rect.fTop}};");
4129 
4130   verifyFormat(
4131       "SomeArrayOfSomeType a = {\n"
4132       "    {{1, 2, 3},\n"
4133       "     {1, 2, 3},\n"
4134       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
4135       "      333333333333333333333333333333},\n"
4136       "     {1, 2, 3},\n"
4137       "     {1, 2, 3}}};");
4138   verifyFormat(
4139       "SomeArrayOfSomeType a = {\n"
4140       "    {{1, 2, 3}},\n"
4141       "    {{1, 2, 3}},\n"
4142       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
4143       "      333333333333333333333333333333}},\n"
4144       "    {{1, 2, 3}},\n"
4145       "    {{1, 2, 3}}};");
4146 
4147   verifyFormat("struct {\n"
4148                "  unsigned bit;\n"
4149                "  const char *const name;\n"
4150                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
4151                "                 {kOsWin, \"Windows\"},\n"
4152                "                 {kOsLinux, \"Linux\"},\n"
4153                "                 {kOsCrOS, \"Chrome OS\"}};");
4154   verifyFormat("struct {\n"
4155                "  unsigned bit;\n"
4156                "  const char *const name;\n"
4157                "} kBitsToOs[] = {\n"
4158                "    {kOsMac, \"Mac\"},\n"
4159                "    {kOsWin, \"Windows\"},\n"
4160                "    {kOsLinux, \"Linux\"},\n"
4161                "    {kOsCrOS, \"Chrome OS\"},\n"
4162                "};");
4163 }
4164 
TEST_F(FormatTest,FormatsSmallMacroDefinitionsInSingleLine)4165 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
4166   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
4167                "                      \\\n"
4168                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
4169 }
4170 
TEST_F(FormatTest,DoesNotBreakPureVirtualFunctionDefinition)4171 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
4172   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
4173                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
4174 
4175   // Do break defaulted and deleted functions.
4176   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4177                "    default;",
4178                getLLVMStyleWithColumns(40));
4179   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
4180                "    delete;",
4181                getLLVMStyleWithColumns(40));
4182 }
4183 
TEST_F(FormatTest,BreaksStringLiteralsOnlyInDefine)4184 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
4185   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
4186                getLLVMStyleWithColumns(40));
4187   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4188                getLLVMStyleWithColumns(40));
4189   EXPECT_EQ("#define Q                              \\\n"
4190             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
4191             "  \"aaaaaaaa.cpp\"",
4192             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
4193                    getLLVMStyleWithColumns(40)));
4194 }
4195 
TEST_F(FormatTest,UnderstandsLinePPDirective)4196 TEST_F(FormatTest, UnderstandsLinePPDirective) {
4197   EXPECT_EQ("# 123 \"A string literal\"",
4198             format("   #     123    \"A string literal\""));
4199 }
4200 
TEST_F(FormatTest,LayoutUnknownPPDirective)4201 TEST_F(FormatTest, LayoutUnknownPPDirective) {
4202   EXPECT_EQ("#;", format("#;"));
4203   verifyFormat("#\n;\n;\n;");
4204 }
4205 
TEST_F(FormatTest,UnescapedEndOfLineEndsPPDirective)4206 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
4207   EXPECT_EQ("#line 42 \"test\"\n",
4208             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
4209   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
4210                                     getLLVMStyleWithColumns(12)));
4211 }
4212 
TEST_F(FormatTest,EndOfFileEndsPPDirective)4213 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
4214   EXPECT_EQ("#line 42 \"test\"",
4215             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
4216   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
4217 }
4218 
TEST_F(FormatTest,DoesntRemoveUnknownTokens)4219 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
4220   verifyFormat("#define A \\x20");
4221   verifyFormat("#define A \\ x20");
4222   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
4223   verifyFormat("#define A ''");
4224   verifyFormat("#define A ''qqq");
4225   verifyFormat("#define A `qqq");
4226   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
4227   EXPECT_EQ("const char *c = STRINGIFY(\n"
4228             "\\na : b);",
4229             format("const char * c = STRINGIFY(\n"
4230                    "\\na : b);"));
4231 
4232   verifyFormat("a\r\\");
4233   verifyFormat("a\v\\");
4234   verifyFormat("a\f\\");
4235 }
4236 
TEST_F(FormatTest,IndentsPPDirectiveWithPPIndentWidth)4237 TEST_F(FormatTest, IndentsPPDirectiveWithPPIndentWidth) {
4238   FormatStyle style = getChromiumStyle(FormatStyle::LK_Cpp);
4239   style.IndentWidth = 4;
4240   style.PPIndentWidth = 1;
4241 
4242   style.IndentPPDirectives = FormatStyle::PPDIS_None;
4243   verifyFormat("#ifdef __linux__\n"
4244                "void foo() {\n"
4245                "    int x = 0;\n"
4246                "}\n"
4247                "#define FOO\n"
4248                "#endif\n"
4249                "void bar() {\n"
4250                "    int y = 0;\n"
4251                "}\n",
4252                style);
4253 
4254   style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4255   verifyFormat("#ifdef __linux__\n"
4256                "void foo() {\n"
4257                "    int x = 0;\n"
4258                "}\n"
4259                "# define FOO foo\n"
4260                "#endif\n"
4261                "void bar() {\n"
4262                "    int y = 0;\n"
4263                "}\n",
4264                style);
4265 
4266   style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4267   verifyFormat("#ifdef __linux__\n"
4268                "void foo() {\n"
4269                "    int x = 0;\n"
4270                "}\n"
4271                " #define FOO foo\n"
4272                "#endif\n"
4273                "void bar() {\n"
4274                "    int y = 0;\n"
4275                "}\n",
4276                style);
4277 }
4278 
TEST_F(FormatTest,IndentsPPDirectiveInReducedSpace)4279 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
4280   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
4281   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
4282   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
4283   // FIXME: We never break before the macro name.
4284   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
4285 
4286   verifyFormat("#define A A\n#define A A");
4287   verifyFormat("#define A(X) A\n#define A A");
4288 
4289   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
4290   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
4291 }
4292 
TEST_F(FormatTest,HandlePreprocessorDirectiveContext)4293 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
4294   EXPECT_EQ("// somecomment\n"
4295             "#include \"a.h\"\n"
4296             "#define A(  \\\n"
4297             "    A, B)\n"
4298             "#include \"b.h\"\n"
4299             "// somecomment\n",
4300             format("  // somecomment\n"
4301                    "  #include \"a.h\"\n"
4302                    "#define A(A,\\\n"
4303                    "    B)\n"
4304                    "    #include \"b.h\"\n"
4305                    " // somecomment\n",
4306                    getLLVMStyleWithColumns(13)));
4307 }
4308 
TEST_F(FormatTest,LayoutSingleHash)4309 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
4310 
TEST_F(FormatTest,LayoutCodeInMacroDefinitions)4311 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
4312   EXPECT_EQ("#define A    \\\n"
4313             "  c;         \\\n"
4314             "  e;\n"
4315             "f;",
4316             format("#define A c; e;\n"
4317                    "f;",
4318                    getLLVMStyleWithColumns(14)));
4319 }
4320 
TEST_F(FormatTest,LayoutRemainingTokens)4321 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
4322 
TEST_F(FormatTest,MacroDefinitionInsideStatement)4323 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
4324   EXPECT_EQ("int x,\n"
4325             "#define A\n"
4326             "    y;",
4327             format("int x,\n#define A\ny;"));
4328 }
4329 
TEST_F(FormatTest,HashInMacroDefinition)4330 TEST_F(FormatTest, HashInMacroDefinition) {
4331   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
4332   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
4333   verifyFormat("#define A  \\\n"
4334                "  {        \\\n"
4335                "    f(#c); \\\n"
4336                "  }",
4337                getLLVMStyleWithColumns(11));
4338 
4339   verifyFormat("#define A(X)         \\\n"
4340                "  void function##X()",
4341                getLLVMStyleWithColumns(22));
4342 
4343   verifyFormat("#define A(a, b, c)   \\\n"
4344                "  void a##b##c()",
4345                getLLVMStyleWithColumns(22));
4346 
4347   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
4348 }
4349 
TEST_F(FormatTest,RespectWhitespaceInMacroDefinitions)4350 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
4351   EXPECT_EQ("#define A (x)", format("#define A (x)"));
4352   EXPECT_EQ("#define A(x)", format("#define A(x)"));
4353 
4354   FormatStyle Style = getLLVMStyle();
4355   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
4356   verifyFormat("#define true ((foo)1)", Style);
4357   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
4358   verifyFormat("#define false((foo)0)", Style);
4359 }
4360 
TEST_F(FormatTest,EmptyLinesInMacroDefinitions)4361 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
4362   EXPECT_EQ("#define A b;", format("#define A \\\n"
4363                                    "          \\\n"
4364                                    "  b;",
4365                                    getLLVMStyleWithColumns(25)));
4366   EXPECT_EQ("#define A \\\n"
4367             "          \\\n"
4368             "  a;      \\\n"
4369             "  b;",
4370             format("#define A \\\n"
4371                    "          \\\n"
4372                    "  a;      \\\n"
4373                    "  b;",
4374                    getLLVMStyleWithColumns(11)));
4375   EXPECT_EQ("#define A \\\n"
4376             "  a;      \\\n"
4377             "          \\\n"
4378             "  b;",
4379             format("#define A \\\n"
4380                    "  a;      \\\n"
4381                    "          \\\n"
4382                    "  b;",
4383                    getLLVMStyleWithColumns(11)));
4384 }
4385 
TEST_F(FormatTest,MacroDefinitionsWithIncompleteCode)4386 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
4387   verifyIncompleteFormat("#define A :");
4388   verifyFormat("#define SOMECASES  \\\n"
4389                "  case 1:          \\\n"
4390                "  case 2\n",
4391                getLLVMStyleWithColumns(20));
4392   verifyFormat("#define MACRO(a) \\\n"
4393                "  if (a)         \\\n"
4394                "    f();         \\\n"
4395                "  else           \\\n"
4396                "    g()",
4397                getLLVMStyleWithColumns(18));
4398   verifyFormat("#define A template <typename T>");
4399   verifyIncompleteFormat("#define STR(x) #x\n"
4400                          "f(STR(this_is_a_string_literal{));");
4401   verifyFormat("#pragma omp threadprivate( \\\n"
4402                "    y)), // expected-warning",
4403                getLLVMStyleWithColumns(28));
4404   verifyFormat("#d, = };");
4405   verifyFormat("#if \"a");
4406   verifyIncompleteFormat("({\n"
4407                          "#define b     \\\n"
4408                          "  }           \\\n"
4409                          "  a\n"
4410                          "a",
4411                          getLLVMStyleWithColumns(15));
4412   verifyFormat("#define A     \\\n"
4413                "  {           \\\n"
4414                "    {\n"
4415                "#define B     \\\n"
4416                "  }           \\\n"
4417                "  }",
4418                getLLVMStyleWithColumns(15));
4419   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
4420   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
4421   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
4422   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
4423 }
4424 
TEST_F(FormatTest,MacrosWithoutTrailingSemicolon)4425 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
4426   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
4427   EXPECT_EQ("class A : public QObject {\n"
4428             "  Q_OBJECT\n"
4429             "\n"
4430             "  A() {}\n"
4431             "};",
4432             format("class A  :  public QObject {\n"
4433                    "     Q_OBJECT\n"
4434                    "\n"
4435                    "  A() {\n}\n"
4436                    "}  ;"));
4437   EXPECT_EQ("MACRO\n"
4438             "/*static*/ int i;",
4439             format("MACRO\n"
4440                    " /*static*/ int   i;"));
4441   EXPECT_EQ("SOME_MACRO\n"
4442             "namespace {\n"
4443             "void f();\n"
4444             "} // namespace",
4445             format("SOME_MACRO\n"
4446                    "  namespace    {\n"
4447                    "void   f(  );\n"
4448                    "} // namespace"));
4449   // Only if the identifier contains at least 5 characters.
4450   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
4451   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
4452   // Only if everything is upper case.
4453   EXPECT_EQ("class A : public QObject {\n"
4454             "  Q_Object A() {}\n"
4455             "};",
4456             format("class A  :  public QObject {\n"
4457                    "     Q_Object\n"
4458                    "  A() {\n}\n"
4459                    "}  ;"));
4460 
4461   // Only if the next line can actually start an unwrapped line.
4462   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
4463             format("SOME_WEIRD_LOG_MACRO\n"
4464                    "<< SomeThing;"));
4465 
4466   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
4467                "(n, buffers))\n",
4468                getChromiumStyle(FormatStyle::LK_Cpp));
4469 
4470   // See PR41483
4471   EXPECT_EQ("/**/ FOO(a)\n"
4472             "FOO(b)",
4473             format("/**/ FOO(a)\n"
4474                    "FOO(b)"));
4475 }
4476 
TEST_F(FormatTest,MacroCallsWithoutTrailingSemicolon)4477 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
4478   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4479             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4480             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4481             "class X {};\n"
4482             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4483             "int *createScopDetectionPass() { return 0; }",
4484             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
4485                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
4486                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
4487                    "  class X {};\n"
4488                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
4489                    "  int *createScopDetectionPass() { return 0; }"));
4490   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
4491   // braces, so that inner block is indented one level more.
4492   EXPECT_EQ("int q() {\n"
4493             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4494             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4495             "  IPC_END_MESSAGE_MAP()\n"
4496             "}",
4497             format("int q() {\n"
4498                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
4499                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
4500                    "  IPC_END_MESSAGE_MAP()\n"
4501                    "}"));
4502 
4503   // Same inside macros.
4504   EXPECT_EQ("#define LIST(L) \\\n"
4505             "  L(A)          \\\n"
4506             "  L(B)          \\\n"
4507             "  L(C)",
4508             format("#define LIST(L) \\\n"
4509                    "  L(A) \\\n"
4510                    "  L(B) \\\n"
4511                    "  L(C)",
4512                    getGoogleStyle()));
4513 
4514   // These must not be recognized as macros.
4515   EXPECT_EQ("int q() {\n"
4516             "  f(x);\n"
4517             "  f(x) {}\n"
4518             "  f(x)->g();\n"
4519             "  f(x)->*g();\n"
4520             "  f(x).g();\n"
4521             "  f(x) = x;\n"
4522             "  f(x) += x;\n"
4523             "  f(x) -= x;\n"
4524             "  f(x) *= x;\n"
4525             "  f(x) /= x;\n"
4526             "  f(x) %= x;\n"
4527             "  f(x) &= x;\n"
4528             "  f(x) |= x;\n"
4529             "  f(x) ^= x;\n"
4530             "  f(x) >>= x;\n"
4531             "  f(x) <<= x;\n"
4532             "  f(x)[y].z();\n"
4533             "  LOG(INFO) << x;\n"
4534             "  ifstream(x) >> x;\n"
4535             "}\n",
4536             format("int q() {\n"
4537                    "  f(x)\n;\n"
4538                    "  f(x)\n {}\n"
4539                    "  f(x)\n->g();\n"
4540                    "  f(x)\n->*g();\n"
4541                    "  f(x)\n.g();\n"
4542                    "  f(x)\n = x;\n"
4543                    "  f(x)\n += x;\n"
4544                    "  f(x)\n -= x;\n"
4545                    "  f(x)\n *= x;\n"
4546                    "  f(x)\n /= x;\n"
4547                    "  f(x)\n %= x;\n"
4548                    "  f(x)\n &= x;\n"
4549                    "  f(x)\n |= x;\n"
4550                    "  f(x)\n ^= x;\n"
4551                    "  f(x)\n >>= x;\n"
4552                    "  f(x)\n <<= x;\n"
4553                    "  f(x)\n[y].z();\n"
4554                    "  LOG(INFO)\n << x;\n"
4555                    "  ifstream(x)\n >> x;\n"
4556                    "}\n"));
4557   EXPECT_EQ("int q() {\n"
4558             "  F(x)\n"
4559             "  if (1) {\n"
4560             "  }\n"
4561             "  F(x)\n"
4562             "  while (1) {\n"
4563             "  }\n"
4564             "  F(x)\n"
4565             "  G(x);\n"
4566             "  F(x)\n"
4567             "  try {\n"
4568             "    Q();\n"
4569             "  } catch (...) {\n"
4570             "  }\n"
4571             "}\n",
4572             format("int q() {\n"
4573                    "F(x)\n"
4574                    "if (1) {}\n"
4575                    "F(x)\n"
4576                    "while (1) {}\n"
4577                    "F(x)\n"
4578                    "G(x);\n"
4579                    "F(x)\n"
4580                    "try { Q(); } catch (...) {}\n"
4581                    "}\n"));
4582   EXPECT_EQ("class A {\n"
4583             "  A() : t(0) {}\n"
4584             "  A(int i) noexcept() : {}\n"
4585             "  A(X x)\n" // FIXME: function-level try blocks are broken.
4586             "  try : t(0) {\n"
4587             "  } catch (...) {\n"
4588             "  }\n"
4589             "};",
4590             format("class A {\n"
4591                    "  A()\n : t(0) {}\n"
4592                    "  A(int i)\n noexcept() : {}\n"
4593                    "  A(X x)\n"
4594                    "  try : t(0) {} catch (...) {}\n"
4595                    "};"));
4596   FormatStyle Style = getLLVMStyle();
4597   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
4598   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
4599   Style.BraceWrapping.AfterFunction = true;
4600   EXPECT_EQ("void f()\n"
4601             "try\n"
4602             "{\n"
4603             "}",
4604             format("void f() try {\n"
4605                    "}",
4606                    Style));
4607   EXPECT_EQ("class SomeClass {\n"
4608             "public:\n"
4609             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4610             "};",
4611             format("class SomeClass {\n"
4612                    "public:\n"
4613                    "  SomeClass()\n"
4614                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4615                    "};"));
4616   EXPECT_EQ("class SomeClass {\n"
4617             "public:\n"
4618             "  SomeClass()\n"
4619             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4620             "};",
4621             format("class SomeClass {\n"
4622                    "public:\n"
4623                    "  SomeClass()\n"
4624                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
4625                    "};",
4626                    getLLVMStyleWithColumns(40)));
4627 
4628   verifyFormat("MACRO(>)");
4629 
4630   // Some macros contain an implicit semicolon.
4631   Style = getLLVMStyle();
4632   Style.StatementMacros.push_back("FOO");
4633   verifyFormat("FOO(a) int b = 0;");
4634   verifyFormat("FOO(a)\n"
4635                "int b = 0;",
4636                Style);
4637   verifyFormat("FOO(a);\n"
4638                "int b = 0;",
4639                Style);
4640   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
4641                "int b = 0;",
4642                Style);
4643   verifyFormat("FOO()\n"
4644                "int b = 0;",
4645                Style);
4646   verifyFormat("FOO\n"
4647                "int b = 0;",
4648                Style);
4649   verifyFormat("void f() {\n"
4650                "  FOO(a)\n"
4651                "  return a;\n"
4652                "}",
4653                Style);
4654   verifyFormat("FOO(a)\n"
4655                "FOO(b)",
4656                Style);
4657   verifyFormat("int a = 0;\n"
4658                "FOO(b)\n"
4659                "int c = 0;",
4660                Style);
4661   verifyFormat("int a = 0;\n"
4662                "int x = FOO(a)\n"
4663                "int b = 0;",
4664                Style);
4665   verifyFormat("void foo(int a) { FOO(a) }\n"
4666                "uint32_t bar() {}",
4667                Style);
4668 }
4669 
TEST_F(FormatTest,LayoutMacroDefinitionsStatementsSpanningBlocks)4670 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
4671   verifyFormat("#define A \\\n"
4672                "  f({     \\\n"
4673                "    g();  \\\n"
4674                "  });",
4675                getLLVMStyleWithColumns(11));
4676 }
4677 
TEST_F(FormatTest,IndentPreprocessorDirectives)4678 TEST_F(FormatTest, IndentPreprocessorDirectives) {
4679   FormatStyle Style = getLLVMStyle();
4680   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
4681   Style.ColumnLimit = 40;
4682   verifyFormat("#ifdef _WIN32\n"
4683                "#define A 0\n"
4684                "#ifdef VAR2\n"
4685                "#define B 1\n"
4686                "#include <someheader.h>\n"
4687                "#define MACRO                          \\\n"
4688                "  some_very_long_func_aaaaaaaaaa();\n"
4689                "#endif\n"
4690                "#else\n"
4691                "#define A 1\n"
4692                "#endif",
4693                Style);
4694   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
4695   verifyFormat("#ifdef _WIN32\n"
4696                "#  define A 0\n"
4697                "#  ifdef VAR2\n"
4698                "#    define B 1\n"
4699                "#    include <someheader.h>\n"
4700                "#    define MACRO                      \\\n"
4701                "      some_very_long_func_aaaaaaaaaa();\n"
4702                "#  endif\n"
4703                "#else\n"
4704                "#  define A 1\n"
4705                "#endif",
4706                Style);
4707   verifyFormat("#if A\n"
4708                "#  define MACRO                        \\\n"
4709                "    void a(int x) {                    \\\n"
4710                "      b();                             \\\n"
4711                "      c();                             \\\n"
4712                "      d();                             \\\n"
4713                "      e();                             \\\n"
4714                "      f();                             \\\n"
4715                "    }\n"
4716                "#endif",
4717                Style);
4718   // Comments before include guard.
4719   verifyFormat("// file comment\n"
4720                "// file comment\n"
4721                "#ifndef HEADER_H\n"
4722                "#define HEADER_H\n"
4723                "code();\n"
4724                "#endif",
4725                Style);
4726   // Test with include guards.
4727   verifyFormat("#ifndef HEADER_H\n"
4728                "#define HEADER_H\n"
4729                "code();\n"
4730                "#endif",
4731                Style);
4732   // Include guards must have a #define with the same variable immediately
4733   // after #ifndef.
4734   verifyFormat("#ifndef NOT_GUARD\n"
4735                "#  define FOO\n"
4736                "code();\n"
4737                "#endif",
4738                Style);
4739 
4740   // Include guards must cover the entire file.
4741   verifyFormat("code();\n"
4742                "code();\n"
4743                "#ifndef NOT_GUARD\n"
4744                "#  define NOT_GUARD\n"
4745                "code();\n"
4746                "#endif",
4747                Style);
4748   verifyFormat("#ifndef NOT_GUARD\n"
4749                "#  define NOT_GUARD\n"
4750                "code();\n"
4751                "#endif\n"
4752                "code();",
4753                Style);
4754   // Test with trailing blank lines.
4755   verifyFormat("#ifndef HEADER_H\n"
4756                "#define HEADER_H\n"
4757                "code();\n"
4758                "#endif\n",
4759                Style);
4760   // Include guards don't have #else.
4761   verifyFormat("#ifndef NOT_GUARD\n"
4762                "#  define NOT_GUARD\n"
4763                "code();\n"
4764                "#else\n"
4765                "#endif",
4766                Style);
4767   verifyFormat("#ifndef NOT_GUARD\n"
4768                "#  define NOT_GUARD\n"
4769                "code();\n"
4770                "#elif FOO\n"
4771                "#endif",
4772                Style);
4773   // Non-identifier #define after potential include guard.
4774   verifyFormat("#ifndef FOO\n"
4775                "#  define 1\n"
4776                "#endif\n",
4777                Style);
4778   // #if closes past last non-preprocessor line.
4779   verifyFormat("#ifndef FOO\n"
4780                "#define FOO\n"
4781                "#if 1\n"
4782                "int i;\n"
4783                "#  define A 0\n"
4784                "#endif\n"
4785                "#endif\n",
4786                Style);
4787   // Don't crash if there is an #elif directive without a condition.
4788   verifyFormat("#if 1\n"
4789                "int x;\n"
4790                "#elif\n"
4791                "int y;\n"
4792                "#else\n"
4793                "int z;\n"
4794                "#endif",
4795                Style);
4796   // FIXME: This doesn't handle the case where there's code between the
4797   // #ifndef and #define but all other conditions hold. This is because when
4798   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
4799   // previous code line yet, so we can't detect it.
4800   EXPECT_EQ("#ifndef NOT_GUARD\n"
4801             "code();\n"
4802             "#define NOT_GUARD\n"
4803             "code();\n"
4804             "#endif",
4805             format("#ifndef NOT_GUARD\n"
4806                    "code();\n"
4807                    "#  define NOT_GUARD\n"
4808                    "code();\n"
4809                    "#endif",
4810                    Style));
4811   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
4812   // be outside an include guard. Examples are #pragma once and
4813   // #pragma GCC diagnostic, or anything else that does not change the meaning
4814   // of the file if it's included multiple times.
4815   EXPECT_EQ("#ifdef WIN32\n"
4816             "#  pragma once\n"
4817             "#endif\n"
4818             "#ifndef HEADER_H\n"
4819             "#  define HEADER_H\n"
4820             "code();\n"
4821             "#endif",
4822             format("#ifdef WIN32\n"
4823                    "#  pragma once\n"
4824                    "#endif\n"
4825                    "#ifndef HEADER_H\n"
4826                    "#define HEADER_H\n"
4827                    "code();\n"
4828                    "#endif",
4829                    Style));
4830   // FIXME: This does not detect when there is a single non-preprocessor line
4831   // in front of an include-guard-like structure where other conditions hold
4832   // because ScopedLineState hides the line.
4833   EXPECT_EQ("code();\n"
4834             "#ifndef HEADER_H\n"
4835             "#define HEADER_H\n"
4836             "code();\n"
4837             "#endif",
4838             format("code();\n"
4839                    "#ifndef HEADER_H\n"
4840                    "#  define HEADER_H\n"
4841                    "code();\n"
4842                    "#endif",
4843                    Style));
4844   // Keep comments aligned with #, otherwise indent comments normally. These
4845   // tests cannot use verifyFormat because messUp manipulates leading
4846   // whitespace.
4847   {
4848     const char *Expected = ""
4849                            "void f() {\n"
4850                            "#if 1\n"
4851                            "// Preprocessor aligned.\n"
4852                            "#  define A 0\n"
4853                            "  // Code. Separated by blank line.\n"
4854                            "\n"
4855                            "#  define B 0\n"
4856                            "  // Code. Not aligned with #\n"
4857                            "#  define C 0\n"
4858                            "#endif";
4859     const char *ToFormat = ""
4860                            "void f() {\n"
4861                            "#if 1\n"
4862                            "// Preprocessor aligned.\n"
4863                            "#  define A 0\n"
4864                            "// Code. Separated by blank line.\n"
4865                            "\n"
4866                            "#  define B 0\n"
4867                            "   // Code. Not aligned with #\n"
4868                            "#  define C 0\n"
4869                            "#endif";
4870     EXPECT_EQ(Expected, format(ToFormat, Style));
4871     EXPECT_EQ(Expected, format(Expected, Style));
4872   }
4873   // Keep block quotes aligned.
4874   {
4875     const char *Expected = ""
4876                            "void f() {\n"
4877                            "#if 1\n"
4878                            "/* Preprocessor aligned. */\n"
4879                            "#  define A 0\n"
4880                            "  /* Code. Separated by blank line. */\n"
4881                            "\n"
4882                            "#  define B 0\n"
4883                            "  /* Code. Not aligned with # */\n"
4884                            "#  define C 0\n"
4885                            "#endif";
4886     const char *ToFormat = ""
4887                            "void f() {\n"
4888                            "#if 1\n"
4889                            "/* Preprocessor aligned. */\n"
4890                            "#  define A 0\n"
4891                            "/* Code. Separated by blank line. */\n"
4892                            "\n"
4893                            "#  define B 0\n"
4894                            "   /* Code. Not aligned with # */\n"
4895                            "#  define C 0\n"
4896                            "#endif";
4897     EXPECT_EQ(Expected, format(ToFormat, Style));
4898     EXPECT_EQ(Expected, format(Expected, Style));
4899   }
4900   // Keep comments aligned with un-indented directives.
4901   {
4902     const char *Expected = ""
4903                            "void f() {\n"
4904                            "// Preprocessor aligned.\n"
4905                            "#define A 0\n"
4906                            "  // Code. Separated by blank line.\n"
4907                            "\n"
4908                            "#define B 0\n"
4909                            "  // Code. Not aligned with #\n"
4910                            "#define C 0\n";
4911     const char *ToFormat = ""
4912                            "void f() {\n"
4913                            "// Preprocessor aligned.\n"
4914                            "#define A 0\n"
4915                            "// Code. Separated by blank line.\n"
4916                            "\n"
4917                            "#define B 0\n"
4918                            "   // Code. Not aligned with #\n"
4919                            "#define C 0\n";
4920     EXPECT_EQ(Expected, format(ToFormat, Style));
4921     EXPECT_EQ(Expected, format(Expected, Style));
4922   }
4923   // Test AfterHash with tabs.
4924   {
4925     FormatStyle Tabbed = Style;
4926     Tabbed.UseTab = FormatStyle::UT_Always;
4927     Tabbed.IndentWidth = 8;
4928     Tabbed.TabWidth = 8;
4929     verifyFormat("#ifdef _WIN32\n"
4930                  "#\tdefine A 0\n"
4931                  "#\tifdef VAR2\n"
4932                  "#\t\tdefine B 1\n"
4933                  "#\t\tinclude <someheader.h>\n"
4934                  "#\t\tdefine MACRO          \\\n"
4935                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
4936                  "#\tendif\n"
4937                  "#else\n"
4938                  "#\tdefine A 1\n"
4939                  "#endif",
4940                  Tabbed);
4941   }
4942 
4943   // Regression test: Multiline-macro inside include guards.
4944   verifyFormat("#ifndef HEADER_H\n"
4945                "#define HEADER_H\n"
4946                "#define A()        \\\n"
4947                "  int i;           \\\n"
4948                "  int j;\n"
4949                "#endif // HEADER_H",
4950                getLLVMStyleWithColumns(20));
4951 
4952   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
4953   // Basic before hash indent tests
4954   verifyFormat("#ifdef _WIN32\n"
4955                "  #define A 0\n"
4956                "  #ifdef VAR2\n"
4957                "    #define B 1\n"
4958                "    #include <someheader.h>\n"
4959                "    #define MACRO                      \\\n"
4960                "      some_very_long_func_aaaaaaaaaa();\n"
4961                "  #endif\n"
4962                "#else\n"
4963                "  #define A 1\n"
4964                "#endif",
4965                Style);
4966   verifyFormat("#if A\n"
4967                "  #define MACRO                        \\\n"
4968                "    void a(int x) {                    \\\n"
4969                "      b();                             \\\n"
4970                "      c();                             \\\n"
4971                "      d();                             \\\n"
4972                "      e();                             \\\n"
4973                "      f();                             \\\n"
4974                "    }\n"
4975                "#endif",
4976                Style);
4977   // Keep comments aligned with indented directives. These
4978   // tests cannot use verifyFormat because messUp manipulates leading
4979   // whitespace.
4980   {
4981     const char *Expected = "void f() {\n"
4982                            "// Aligned to preprocessor.\n"
4983                            "#if 1\n"
4984                            "  // Aligned to code.\n"
4985                            "  int a;\n"
4986                            "  #if 1\n"
4987                            "    // Aligned to preprocessor.\n"
4988                            "    #define A 0\n"
4989                            "  // Aligned to code.\n"
4990                            "  int b;\n"
4991                            "  #endif\n"
4992                            "#endif\n"
4993                            "}";
4994     const char *ToFormat = "void f() {\n"
4995                            "// Aligned to preprocessor.\n"
4996                            "#if 1\n"
4997                            "// Aligned to code.\n"
4998                            "int a;\n"
4999                            "#if 1\n"
5000                            "// Aligned to preprocessor.\n"
5001                            "#define A 0\n"
5002                            "// Aligned to code.\n"
5003                            "int b;\n"
5004                            "#endif\n"
5005                            "#endif\n"
5006                            "}";
5007     EXPECT_EQ(Expected, format(ToFormat, Style));
5008     EXPECT_EQ(Expected, format(Expected, Style));
5009   }
5010   {
5011     const char *Expected = "void f() {\n"
5012                            "/* Aligned to preprocessor. */\n"
5013                            "#if 1\n"
5014                            "  /* Aligned to code. */\n"
5015                            "  int a;\n"
5016                            "  #if 1\n"
5017                            "    /* Aligned to preprocessor. */\n"
5018                            "    #define A 0\n"
5019                            "  /* Aligned to code. */\n"
5020                            "  int b;\n"
5021                            "  #endif\n"
5022                            "#endif\n"
5023                            "}";
5024     const char *ToFormat = "void f() {\n"
5025                            "/* Aligned to preprocessor. */\n"
5026                            "#if 1\n"
5027                            "/* Aligned to code. */\n"
5028                            "int a;\n"
5029                            "#if 1\n"
5030                            "/* Aligned to preprocessor. */\n"
5031                            "#define A 0\n"
5032                            "/* Aligned to code. */\n"
5033                            "int b;\n"
5034                            "#endif\n"
5035                            "#endif\n"
5036                            "}";
5037     EXPECT_EQ(Expected, format(ToFormat, Style));
5038     EXPECT_EQ(Expected, format(Expected, Style));
5039   }
5040 
5041   // Test single comment before preprocessor
5042   verifyFormat("// Comment\n"
5043                "\n"
5044                "#if 1\n"
5045                "#endif",
5046                Style);
5047 }
5048 
TEST_F(FormatTest,FormatHashIfNotAtStartOfLine)5049 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
5050   verifyFormat("{\n  { a #c; }\n}");
5051 }
5052 
TEST_F(FormatTest,FormatUnbalancedStructuralElements)5053 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
5054   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
5055             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
5056   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
5057             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
5058 }
5059 
TEST_F(FormatTest,EscapedNewlines)5060 TEST_F(FormatTest, EscapedNewlines) {
5061   FormatStyle Narrow = getLLVMStyleWithColumns(11);
5062   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
5063             format("#define A \\\nint i;\\\n  int j;", Narrow));
5064   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
5065   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5066   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
5067   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
5068 
5069   FormatStyle AlignLeft = getLLVMStyle();
5070   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
5071   EXPECT_EQ("#define MACRO(x) \\\n"
5072             "private:         \\\n"
5073             "  int x(int a);\n",
5074             format("#define MACRO(x) \\\n"
5075                    "private:         \\\n"
5076                    "  int x(int a);\n",
5077                    AlignLeft));
5078 
5079   // CRLF line endings
5080   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
5081             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
5082   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
5083   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
5084   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
5085   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
5086   EXPECT_EQ("#define MACRO(x) \\\r\n"
5087             "private:         \\\r\n"
5088             "  int x(int a);\r\n",
5089             format("#define MACRO(x) \\\r\n"
5090                    "private:         \\\r\n"
5091                    "  int x(int a);\r\n",
5092                    AlignLeft));
5093 
5094   FormatStyle DontAlign = getLLVMStyle();
5095   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
5096   DontAlign.MaxEmptyLinesToKeep = 3;
5097   // FIXME: can't use verifyFormat here because the newline before
5098   // "public:" is not inserted the first time it's reformatted
5099   EXPECT_EQ("#define A \\\n"
5100             "  class Foo { \\\n"
5101             "    void bar(); \\\n"
5102             "\\\n"
5103             "\\\n"
5104             "\\\n"
5105             "  public: \\\n"
5106             "    void baz(); \\\n"
5107             "  };",
5108             format("#define A \\\n"
5109                    "  class Foo { \\\n"
5110                    "    void bar(); \\\n"
5111                    "\\\n"
5112                    "\\\n"
5113                    "\\\n"
5114                    "  public: \\\n"
5115                    "    void baz(); \\\n"
5116                    "  };",
5117                    DontAlign));
5118 }
5119 
TEST_F(FormatTest,CalculateSpaceOnConsecutiveLinesInMacro)5120 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
5121   verifyFormat("#define A \\\n"
5122                "  int v(  \\\n"
5123                "      a); \\\n"
5124                "  int i;",
5125                getLLVMStyleWithColumns(11));
5126 }
5127 
TEST_F(FormatTest,MixingPreprocessorDirectivesAndNormalCode)5128 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
5129   EXPECT_EQ(
5130       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
5131       "                      \\\n"
5132       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5133       "\n"
5134       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5135       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
5136       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
5137              "\\\n"
5138              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
5139              "  \n"
5140              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
5141              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
5142 }
5143 
TEST_F(FormatTest,LayoutStatementsAroundPreprocessorDirectives)5144 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
5145   EXPECT_EQ("int\n"
5146             "#define A\n"
5147             "    a;",
5148             format("int\n#define A\na;"));
5149   verifyFormat("functionCallTo(\n"
5150                "    someOtherFunction(\n"
5151                "        withSomeParameters, whichInSequence,\n"
5152                "        areLongerThanALine(andAnotherCall,\n"
5153                "#define A B\n"
5154                "                           withMoreParamters,\n"
5155                "                           whichStronglyInfluenceTheLayout),\n"
5156                "        andMoreParameters),\n"
5157                "    trailing);",
5158                getLLVMStyleWithColumns(69));
5159   verifyFormat("Foo::Foo()\n"
5160                "#ifdef BAR\n"
5161                "    : baz(0)\n"
5162                "#endif\n"
5163                "{\n"
5164                "}");
5165   verifyFormat("void f() {\n"
5166                "  if (true)\n"
5167                "#ifdef A\n"
5168                "    f(42);\n"
5169                "  x();\n"
5170                "#else\n"
5171                "    g();\n"
5172                "  x();\n"
5173                "#endif\n"
5174                "}");
5175   verifyFormat("void f(param1, param2,\n"
5176                "       param3,\n"
5177                "#ifdef A\n"
5178                "       param4(param5,\n"
5179                "#ifdef A1\n"
5180                "              param6,\n"
5181                "#ifdef A2\n"
5182                "              param7),\n"
5183                "#else\n"
5184                "              param8),\n"
5185                "       param9,\n"
5186                "#endif\n"
5187                "       param10,\n"
5188                "#endif\n"
5189                "       param11)\n"
5190                "#else\n"
5191                "       param12)\n"
5192                "#endif\n"
5193                "{\n"
5194                "  x();\n"
5195                "}",
5196                getLLVMStyleWithColumns(28));
5197   verifyFormat("#if 1\n"
5198                "int i;");
5199   verifyFormat("#if 1\n"
5200                "#endif\n"
5201                "#if 1\n"
5202                "#else\n"
5203                "#endif\n");
5204   verifyFormat("DEBUG({\n"
5205                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5206                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
5207                "});\n"
5208                "#if a\n"
5209                "#else\n"
5210                "#endif");
5211 
5212   verifyIncompleteFormat("void f(\n"
5213                          "#if A\n"
5214                          ");\n"
5215                          "#else\n"
5216                          "#endif");
5217 }
5218 
TEST_F(FormatTest,GraciouslyHandleIncorrectPreprocessorConditions)5219 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
5220   verifyFormat("#endif\n"
5221                "#if B");
5222 }
5223 
TEST_F(FormatTest,FormatsJoinedLinesOnSubsequentRuns)5224 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
5225   FormatStyle SingleLine = getLLVMStyle();
5226   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
5227   verifyFormat("#if 0\n"
5228                "#elif 1\n"
5229                "#endif\n"
5230                "void foo() {\n"
5231                "  if (test) foo2();\n"
5232                "}",
5233                SingleLine);
5234 }
5235 
TEST_F(FormatTest,LayoutBlockInsideParens)5236 TEST_F(FormatTest, LayoutBlockInsideParens) {
5237   verifyFormat("functionCall({ int i; });");
5238   verifyFormat("functionCall({\n"
5239                "  int i;\n"
5240                "  int j;\n"
5241                "});");
5242   verifyFormat("functionCall(\n"
5243                "    {\n"
5244                "      int i;\n"
5245                "      int j;\n"
5246                "    },\n"
5247                "    aaaa, bbbb, cccc);");
5248   verifyFormat("functionA(functionB({\n"
5249                "            int i;\n"
5250                "            int j;\n"
5251                "          }),\n"
5252                "          aaaa, bbbb, cccc);");
5253   verifyFormat("functionCall(\n"
5254                "    {\n"
5255                "      int i;\n"
5256                "      int j;\n"
5257                "    },\n"
5258                "    aaaa, bbbb, // comment\n"
5259                "    cccc);");
5260   verifyFormat("functionA(functionB({\n"
5261                "            int i;\n"
5262                "            int j;\n"
5263                "          }),\n"
5264                "          aaaa, bbbb, // comment\n"
5265                "          cccc);");
5266   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
5267   verifyFormat("functionCall(aaaa, bbbb, {\n"
5268                "  int i;\n"
5269                "  int j;\n"
5270                "});");
5271   verifyFormat(
5272       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
5273       "    {\n"
5274       "      int i; // break\n"
5275       "    },\n"
5276       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
5277       "                                     ccccccccccccccccc));");
5278   verifyFormat("DEBUG({\n"
5279                "  if (a)\n"
5280                "    f();\n"
5281                "});");
5282 }
5283 
TEST_F(FormatTest,LayoutBlockInsideStatement)5284 TEST_F(FormatTest, LayoutBlockInsideStatement) {
5285   EXPECT_EQ("SOME_MACRO { int i; }\n"
5286             "int i;",
5287             format("  SOME_MACRO  {int i;}  int i;"));
5288 }
5289 
TEST_F(FormatTest,LayoutNestedBlocks)5290 TEST_F(FormatTest, LayoutNestedBlocks) {
5291   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
5292                "  struct s {\n"
5293                "    int i;\n"
5294                "  };\n"
5295                "  s kBitsToOs[] = {{10}};\n"
5296                "  for (int i = 0; i < 10; ++i)\n"
5297                "    return;\n"
5298                "}");
5299   verifyFormat("call(parameter, {\n"
5300                "  something();\n"
5301                "  // Comment using all columns.\n"
5302                "  somethingelse();\n"
5303                "});",
5304                getLLVMStyleWithColumns(40));
5305   verifyFormat("DEBUG( //\n"
5306                "    { f(); }, a);");
5307   verifyFormat("DEBUG( //\n"
5308                "    {\n"
5309                "      f(); //\n"
5310                "    },\n"
5311                "    a);");
5312 
5313   EXPECT_EQ("call(parameter, {\n"
5314             "  something();\n"
5315             "  // Comment too\n"
5316             "  // looooooooooong.\n"
5317             "  somethingElse();\n"
5318             "});",
5319             format("call(parameter, {\n"
5320                    "  something();\n"
5321                    "  // Comment too looooooooooong.\n"
5322                    "  somethingElse();\n"
5323                    "});",
5324                    getLLVMStyleWithColumns(29)));
5325   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
5326   EXPECT_EQ("DEBUG({ // comment\n"
5327             "  int i;\n"
5328             "});",
5329             format("DEBUG({ // comment\n"
5330                    "int  i;\n"
5331                    "});"));
5332   EXPECT_EQ("DEBUG({\n"
5333             "  int i;\n"
5334             "\n"
5335             "  // comment\n"
5336             "  int j;\n"
5337             "});",
5338             format("DEBUG({\n"
5339                    "  int  i;\n"
5340                    "\n"
5341                    "  // comment\n"
5342                    "  int  j;\n"
5343                    "});"));
5344 
5345   verifyFormat("DEBUG({\n"
5346                "  if (a)\n"
5347                "    return;\n"
5348                "});");
5349   verifyGoogleFormat("DEBUG({\n"
5350                      "  if (a) return;\n"
5351                      "});");
5352   FormatStyle Style = getGoogleStyle();
5353   Style.ColumnLimit = 45;
5354   verifyFormat("Debug(\n"
5355                "    aaaaa,\n"
5356                "    {\n"
5357                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
5358                "    },\n"
5359                "    a);",
5360                Style);
5361 
5362   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
5363 
5364   verifyNoCrash("^{v^{a}}");
5365 }
5366 
TEST_F(FormatTest,FormatNestedBlocksInMacros)5367 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
5368   EXPECT_EQ("#define MACRO()                     \\\n"
5369             "  Debug(aaa, /* force line break */ \\\n"
5370             "        {                           \\\n"
5371             "          int i;                    \\\n"
5372             "          int j;                    \\\n"
5373             "        })",
5374             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
5375                    "          {  int   i;  int  j;   })",
5376                    getGoogleStyle()));
5377 
5378   EXPECT_EQ("#define A                                       \\\n"
5379             "  [] {                                          \\\n"
5380             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
5381             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
5382             "  }",
5383             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
5384                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
5385                    getGoogleStyle()));
5386 }
5387 
TEST_F(FormatTest,PutEmptyBlocksIntoOneLine)5388 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
5389   EXPECT_EQ("{}", format("{}"));
5390   verifyFormat("enum E {};");
5391   verifyFormat("enum E {}");
5392   FormatStyle Style = getLLVMStyle();
5393   Style.SpaceInEmptyBlock = true;
5394   EXPECT_EQ("void f() { }", format("void f() {}", Style));
5395   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
5396   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
5397 }
5398 
TEST_F(FormatTest,FormatBeginBlockEndMacros)5399 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
5400   FormatStyle Style = getLLVMStyle();
5401   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
5402   Style.MacroBlockEnd = "^[A-Z_]+_END$";
5403   verifyFormat("FOO_BEGIN\n"
5404                "  FOO_ENTRY\n"
5405                "FOO_END",
5406                Style);
5407   verifyFormat("FOO_BEGIN\n"
5408                "  NESTED_FOO_BEGIN\n"
5409                "    NESTED_FOO_ENTRY\n"
5410                "  NESTED_FOO_END\n"
5411                "FOO_END",
5412                Style);
5413   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
5414                "  int x;\n"
5415                "  x = 1;\n"
5416                "FOO_END(Baz)",
5417                Style);
5418 }
5419 
5420 //===----------------------------------------------------------------------===//
5421 // Line break tests.
5422 //===----------------------------------------------------------------------===//
5423 
TEST_F(FormatTest,PreventConfusingIndents)5424 TEST_F(FormatTest, PreventConfusingIndents) {
5425   verifyFormat(
5426       "void f() {\n"
5427       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
5428       "                         parameter, parameter, parameter)),\n"
5429       "                     SecondLongCall(parameter));\n"
5430       "}");
5431   verifyFormat(
5432       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5433       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5434       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5435       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
5436   verifyFormat(
5437       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5438       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
5439       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
5440       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
5441   verifyFormat(
5442       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5443       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
5444       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
5445       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
5446   verifyFormat("int a = bbbb && ccc &&\n"
5447                "        fffff(\n"
5448                "#define A Just forcing a new line\n"
5449                "            ddd);");
5450 }
5451 
TEST_F(FormatTest,LineBreakingInBinaryExpressions)5452 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
5453   verifyFormat(
5454       "bool aaaaaaa =\n"
5455       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
5456       "    bbbbbbbb();");
5457   verifyFormat(
5458       "bool aaaaaaa =\n"
5459       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
5460       "    bbbbbbbb();");
5461 
5462   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5463                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
5464                "    ccccccccc == ddddddddddd;");
5465   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
5466                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
5467                "    ccccccccc == ddddddddddd;");
5468   verifyFormat(
5469       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
5470       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
5471       "    ccccccccc == ddddddddddd;");
5472 
5473   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5474                "                 aaaaaa) &&\n"
5475                "         bbbbbb && cccccc;");
5476   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
5477                "                 aaaaaa) >>\n"
5478                "         bbbbbb;");
5479   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
5480                "    SourceMgr.getSpellingColumnNumber(\n"
5481                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
5482                "    1);");
5483 
5484   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5485                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
5486                "    cccccc) {\n}");
5487   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5488                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5489                "              cccccc) {\n}");
5490   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5491                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
5492                "              cccccc) {\n}");
5493   verifyFormat("b = a &&\n"
5494                "    // Comment\n"
5495                "    b.c && d;");
5496 
5497   // If the LHS of a comparison is not a binary expression itself, the
5498   // additional linebreak confuses many people.
5499   verifyFormat(
5500       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5501       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
5502       "}");
5503   verifyFormat(
5504       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5505       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5506       "}");
5507   verifyFormat(
5508       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
5509       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5510       "}");
5511   verifyFormat(
5512       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5513       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
5514       "}");
5515   // Even explicit parentheses stress the precedence enough to make the
5516   // additional break unnecessary.
5517   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5518                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
5519                "}");
5520   // This cases is borderline, but with the indentation it is still readable.
5521   verifyFormat(
5522       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5523       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5524       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
5525       "}",
5526       getLLVMStyleWithColumns(75));
5527 
5528   // If the LHS is a binary expression, we should still use the additional break
5529   // as otherwise the formatting hides the operator precedence.
5530   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5531                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5532                "    5) {\n"
5533                "}");
5534   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5535                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
5536                "    5) {\n"
5537                "}");
5538 
5539   FormatStyle OnePerLine = getLLVMStyle();
5540   OnePerLine.BinPackParameters = false;
5541   verifyFormat(
5542       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5543       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5544       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
5545       OnePerLine);
5546 
5547   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
5548                "                .aaa(aaaaaaaaaaaaa) *\n"
5549                "            aaaaaaa +\n"
5550                "        aaaaaaa;",
5551                getLLVMStyleWithColumns(40));
5552 }
5553 
TEST_F(FormatTest,ExpressionIndentation)5554 TEST_F(FormatTest, ExpressionIndentation) {
5555   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5556                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5557                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5558                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5559                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
5560                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
5561                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5562                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
5563                "                 ccccccccccccccccccccccccccccccccccccccccc;");
5564   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5565                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5566                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5567                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5568   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5569                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5570                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5571                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5572   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
5573                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
5574                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5575                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
5576   verifyFormat("if () {\n"
5577                "} else if (aaaaa && bbbbb > // break\n"
5578                "                        ccccc) {\n"
5579                "}");
5580   verifyFormat("if () {\n"
5581                "} else if constexpr (aaaaa && bbbbb > // break\n"
5582                "                                  ccccc) {\n"
5583                "}");
5584   verifyFormat("if () {\n"
5585                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
5586                "                                  ccccc) {\n"
5587                "}");
5588   verifyFormat("if () {\n"
5589                "} else if (aaaaa &&\n"
5590                "           bbbbb > // break\n"
5591                "               ccccc &&\n"
5592                "           ddddd) {\n"
5593                "}");
5594 
5595   // Presence of a trailing comment used to change indentation of b.
5596   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
5597                "       b;\n"
5598                "return aaaaaaaaaaaaaaaaaaa +\n"
5599                "       b; //",
5600                getLLVMStyleWithColumns(30));
5601 }
5602 
TEST_F(FormatTest,ExpressionIndentationBreakingBeforeOperators)5603 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
5604   // Not sure what the best system is here. Like this, the LHS can be found
5605   // immediately above an operator (everything with the same or a higher
5606   // indent). The RHS is aligned right of the operator and so compasses
5607   // everything until something with the same indent as the operator is found.
5608   // FIXME: Is this a good system?
5609   FormatStyle Style = getLLVMStyle();
5610   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5611   verifyFormat(
5612       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5613       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5614       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5615       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5616       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5617       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5618       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5619       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5620       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
5621       Style);
5622   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5623                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5624                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5625                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5626                Style);
5627   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5628                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5629                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5630                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5631                Style);
5632   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5633                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5634                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5635                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5636                Style);
5637   verifyFormat("if () {\n"
5638                "} else if (aaaaa\n"
5639                "           && bbbbb // break\n"
5640                "                  > ccccc) {\n"
5641                "}",
5642                Style);
5643   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5644                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5645                Style);
5646   verifyFormat("return (a)\n"
5647                "       // comment\n"
5648                "       + b;",
5649                Style);
5650   verifyFormat(
5651       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5652       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5653       "             + cc;",
5654       Style);
5655 
5656   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5657                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5658                Style);
5659 
5660   // Forced by comments.
5661   verifyFormat(
5662       "unsigned ContentSize =\n"
5663       "    sizeof(int16_t)   // DWARF ARange version number\n"
5664       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5665       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5666       "    + sizeof(int8_t); // Segment Size (in bytes)");
5667 
5668   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
5669                "       == boost::fusion::at_c<1>(iiii).second;",
5670                Style);
5671 
5672   Style.ColumnLimit = 60;
5673   verifyFormat("zzzzzzzzzz\n"
5674                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5675                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
5676                Style);
5677 
5678   Style.ColumnLimit = 80;
5679   Style.IndentWidth = 4;
5680   Style.TabWidth = 4;
5681   Style.UseTab = FormatStyle::UT_Always;
5682   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5683   Style.AlignOperands = FormatStyle::OAS_DontAlign;
5684   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
5685             "\t&& (someOtherLongishConditionPart1\n"
5686             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
5687             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
5688                    "(someOtherLongishConditionPart1 || "
5689                    "someOtherEvenLongerNestedConditionPart2);",
5690                    Style));
5691 }
5692 
TEST_F(FormatTest,ExpressionIndentationStrictAlign)5693 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
5694   FormatStyle Style = getLLVMStyle();
5695   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
5696   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
5697 
5698   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5699                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5700                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5701                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5702                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5703                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5704                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5705                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5706                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
5707                Style);
5708   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5709                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5710                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5711                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5712                Style);
5713   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5714                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5715                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5716                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5717                Style);
5718   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5719                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5720                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5721                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
5722                Style);
5723   verifyFormat("if () {\n"
5724                "} else if (aaaaa\n"
5725                "           && bbbbb // break\n"
5726                "                  > ccccc) {\n"
5727                "}",
5728                Style);
5729   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5730                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5731                Style);
5732   verifyFormat("return (a)\n"
5733                "     // comment\n"
5734                "     + b;",
5735                Style);
5736   verifyFormat(
5737       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5738       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5739       "           + cc;",
5740       Style);
5741   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
5742                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
5743                "                        : 3333333333333333;",
5744                Style);
5745   verifyFormat(
5746       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
5747       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
5748       "                                             : eeeeeeeeeeeeeeeeee)\n"
5749       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
5750       "                        : 3333333333333333;",
5751       Style);
5752   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5753                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
5754                Style);
5755 
5756   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
5757                "    == boost::fusion::at_c<1>(iiii).second;",
5758                Style);
5759 
5760   Style.ColumnLimit = 60;
5761   verifyFormat("zzzzzzzzzzzzz\n"
5762                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5763                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
5764                Style);
5765 
5766   // Forced by comments.
5767   Style.ColumnLimit = 80;
5768   verifyFormat(
5769       "unsigned ContentSize\n"
5770       "    = sizeof(int16_t) // DWARF ARange version number\n"
5771       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5772       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5773       "    + sizeof(int8_t); // Segment Size (in bytes)",
5774       Style);
5775 
5776   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5777   verifyFormat(
5778       "unsigned ContentSize =\n"
5779       "    sizeof(int16_t)   // DWARF ARange version number\n"
5780       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5781       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5782       "    + sizeof(int8_t); // Segment Size (in bytes)",
5783       Style);
5784 
5785   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
5786   verifyFormat(
5787       "unsigned ContentSize =\n"
5788       "    sizeof(int16_t)   // DWARF ARange version number\n"
5789       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
5790       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
5791       "    + sizeof(int8_t); // Segment Size (in bytes)",
5792       Style);
5793 }
5794 
TEST_F(FormatTest,EnforcedOperatorWraps)5795 TEST_F(FormatTest, EnforcedOperatorWraps) {
5796   // Here we'd like to wrap after the || operators, but a comment is forcing an
5797   // earlier wrap.
5798   verifyFormat("bool x = aaaaa //\n"
5799                "         || bbbbb\n"
5800                "         //\n"
5801                "         || cccc;");
5802 }
5803 
TEST_F(FormatTest,NoOperandAlignment)5804 TEST_F(FormatTest, NoOperandAlignment) {
5805   FormatStyle Style = getLLVMStyle();
5806   Style.AlignOperands = FormatStyle::OAS_DontAlign;
5807   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
5808                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5809                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5810                Style);
5811   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5812   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5813                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5814                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5815                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5816                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5817                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5818                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5819                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5820                "        > ccccccccccccccccccccccccccccccccccccccccc;",
5821                Style);
5822 
5823   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5824                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5825                "    + cc;",
5826                Style);
5827   verifyFormat("int a = aa\n"
5828                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
5829                "        * cccccccccccccccccccccccccccccccccccc;\n",
5830                Style);
5831 
5832   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5833   verifyFormat("return (a > b\n"
5834                "    // comment1\n"
5835                "    // comment2\n"
5836                "    || c);",
5837                Style);
5838 }
5839 
TEST_F(FormatTest,BreakingBeforeNonAssigmentOperators)5840 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
5841   FormatStyle Style = getLLVMStyle();
5842   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5843   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5844                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5845                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
5846                Style);
5847 }
5848 
TEST_F(FormatTest,AllowBinPackingInsideArguments)5849 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
5850   FormatStyle Style = getLLVMStyle();
5851   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
5852   Style.BinPackArguments = false;
5853   Style.ColumnLimit = 40;
5854   verifyFormat("void test() {\n"
5855                "  someFunction(\n"
5856                "      this + argument + is + quite\n"
5857                "      + long + so + it + gets + wrapped\n"
5858                "      + but + remains + bin - packed);\n"
5859                "}",
5860                Style);
5861   verifyFormat("void test() {\n"
5862                "  someFunction(arg1,\n"
5863                "               this + argument + is\n"
5864                "                   + quite + long + so\n"
5865                "                   + it + gets + wrapped\n"
5866                "                   + but + remains + bin\n"
5867                "                   - packed,\n"
5868                "               arg3);\n"
5869                "}",
5870                Style);
5871   verifyFormat("void test() {\n"
5872                "  someFunction(\n"
5873                "      arg1,\n"
5874                "      this + argument + has\n"
5875                "          + anotherFunc(nested,\n"
5876                "                        calls + whose\n"
5877                "                            + arguments\n"
5878                "                            + are + also\n"
5879                "                            + wrapped,\n"
5880                "                        in + addition)\n"
5881                "          + to + being + bin - packed,\n"
5882                "      arg3);\n"
5883                "}",
5884                Style);
5885 
5886   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
5887   verifyFormat("void test() {\n"
5888                "  someFunction(\n"
5889                "      arg1,\n"
5890                "      this + argument + has +\n"
5891                "          anotherFunc(nested,\n"
5892                "                      calls + whose +\n"
5893                "                          arguments +\n"
5894                "                          are + also +\n"
5895                "                          wrapped,\n"
5896                "                      in + addition) +\n"
5897                "          to + being + bin - packed,\n"
5898                "      arg3);\n"
5899                "}",
5900                Style);
5901 }
5902 
TEST_F(FormatTest,ConstructorInitializers)5903 TEST_F(FormatTest, ConstructorInitializers) {
5904   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
5905   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
5906                getLLVMStyleWithColumns(45));
5907   verifyFormat("Constructor()\n"
5908                "    : Inttializer(FitsOnTheLine) {}",
5909                getLLVMStyleWithColumns(44));
5910   verifyFormat("Constructor()\n"
5911                "    : Inttializer(FitsOnTheLine) {}",
5912                getLLVMStyleWithColumns(43));
5913 
5914   verifyFormat("template <typename T>\n"
5915                "Constructor() : Initializer(FitsOnTheLine) {}",
5916                getLLVMStyleWithColumns(45));
5917 
5918   verifyFormat(
5919       "SomeClass::Constructor()\n"
5920       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
5921 
5922   verifyFormat(
5923       "SomeClass::Constructor()\n"
5924       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5925       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
5926   verifyFormat(
5927       "SomeClass::Constructor()\n"
5928       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5929       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
5930   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5931                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5932                "    : aaaaaaaaaa(aaaaaa) {}");
5933 
5934   verifyFormat("Constructor()\n"
5935                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5936                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5937                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5938                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
5939 
5940   verifyFormat("Constructor()\n"
5941                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5942                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5943 
5944   verifyFormat("Constructor(int Parameter = 0)\n"
5945                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
5946                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
5947   verifyFormat("Constructor()\n"
5948                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
5949                "}",
5950                getLLVMStyleWithColumns(60));
5951   verifyFormat("Constructor()\n"
5952                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5953                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
5954 
5955   // Here a line could be saved by splitting the second initializer onto two
5956   // lines, but that is not desirable.
5957   verifyFormat("Constructor()\n"
5958                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
5959                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
5960                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5961 
5962   FormatStyle OnePerLine = getLLVMStyle();
5963   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_Never;
5964   verifyFormat("MyClass::MyClass()\n"
5965                "    : a(a),\n"
5966                "      b(b),\n"
5967                "      c(c) {}",
5968                OnePerLine);
5969   verifyFormat("MyClass::MyClass()\n"
5970                "    : a(a), // comment\n"
5971                "      b(b),\n"
5972                "      c(c) {}",
5973                OnePerLine);
5974   verifyFormat("MyClass::MyClass(int a)\n"
5975                "    : b(a),      // comment\n"
5976                "      c(a + 1) { // lined up\n"
5977                "}",
5978                OnePerLine);
5979   verifyFormat("Constructor()\n"
5980                "    : a(b, b, b) {}",
5981                OnePerLine);
5982   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
5983   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
5984   verifyFormat("SomeClass::Constructor()\n"
5985                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5986                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5987                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5988                OnePerLine);
5989   verifyFormat("SomeClass::Constructor()\n"
5990                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
5991                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5992                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5993                OnePerLine);
5994   verifyFormat("MyClass::MyClass(int var)\n"
5995                "    : some_var_(var),            // 4 space indent\n"
5996                "      some_other_var_(var + 1) { // lined up\n"
5997                "}",
5998                OnePerLine);
5999   verifyFormat("Constructor()\n"
6000                "    : aaaaa(aaaaaa),\n"
6001                "      aaaaa(aaaaaa),\n"
6002                "      aaaaa(aaaaaa),\n"
6003                "      aaaaa(aaaaaa),\n"
6004                "      aaaaa(aaaaaa) {}",
6005                OnePerLine);
6006   verifyFormat("Constructor()\n"
6007                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6008                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
6009                OnePerLine);
6010   OnePerLine.BinPackParameters = false;
6011   verifyFormat(
6012       "Constructor()\n"
6013       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6014       "          aaaaaaaaaaa().aaa(),\n"
6015       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6016       OnePerLine);
6017   OnePerLine.ColumnLimit = 60;
6018   verifyFormat("Constructor()\n"
6019                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6020                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6021                OnePerLine);
6022 
6023   EXPECT_EQ("Constructor()\n"
6024             "    : // Comment forcing unwanted break.\n"
6025             "      aaaa(aaaa) {}",
6026             format("Constructor() :\n"
6027                    "    // Comment forcing unwanted break.\n"
6028                    "    aaaa(aaaa) {}"));
6029 }
6030 
TEST_F(FormatTest,AllowAllConstructorInitializersOnNextLine)6031 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
6032   FormatStyle Style = getLLVMStyle();
6033   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6034   Style.ColumnLimit = 60;
6035   Style.BinPackParameters = false;
6036 
6037   for (int i = 0; i < 4; ++i) {
6038     // Test all combinations of parameters that should not have an effect.
6039     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6040     Style.AllowAllArgumentsOnNextLine = i & 2;
6041 
6042     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6043     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6044     verifyFormat("Constructor()\n"
6045                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6046                  Style);
6047     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6048 
6049     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6050     verifyFormat("Constructor()\n"
6051                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6052                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6053                  Style);
6054     verifyFormat("Constructor() : a(a), b(b) {}", Style);
6055 
6056     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6057     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6058     verifyFormat("Constructor()\n"
6059                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6060                  Style);
6061 
6062     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6063     verifyFormat("Constructor()\n"
6064                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6065                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6066                  Style);
6067 
6068     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6069     Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6070     verifyFormat("Constructor() :\n"
6071                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6072                  Style);
6073 
6074     Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6075     verifyFormat("Constructor() :\n"
6076                  "    aaaaaaaaaaaaaaaaaa(a),\n"
6077                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6078                  Style);
6079   }
6080 
6081   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
6082   // AllowAllConstructorInitializersOnNextLine in all
6083   // BreakConstructorInitializers modes
6084   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
6085   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6086   verifyFormat("SomeClassWithALongName::Constructor(\n"
6087                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6088                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6089                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6090                Style);
6091 
6092   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6093   verifyFormat("SomeClassWithALongName::Constructor(\n"
6094                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6095                "    int bbbbbbbbbbbbb,\n"
6096                "    int cccccccccccccccc)\n"
6097                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6098                Style);
6099 
6100   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6101   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6102   verifyFormat("SomeClassWithALongName::Constructor(\n"
6103                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6104                "    int bbbbbbbbbbbbb)\n"
6105                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
6106                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
6107                Style);
6108 
6109   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
6110 
6111   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6112   verifyFormat("SomeClassWithALongName::Constructor(\n"
6113                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
6114                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6115                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6116                Style);
6117 
6118   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6119   verifyFormat("SomeClassWithALongName::Constructor(\n"
6120                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6121                "    int bbbbbbbbbbbbb,\n"
6122                "    int cccccccccccccccc)\n"
6123                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6124                Style);
6125 
6126   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6127   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6128   verifyFormat("SomeClassWithALongName::Constructor(\n"
6129                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6130                "    int bbbbbbbbbbbbb)\n"
6131                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
6132                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
6133                Style);
6134 
6135   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6136   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6137   verifyFormat("SomeClassWithALongName::Constructor(\n"
6138                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
6139                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6140                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6141                Style);
6142 
6143   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6144   verifyFormat("SomeClassWithALongName::Constructor(\n"
6145                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6146                "    int bbbbbbbbbbbbb,\n"
6147                "    int cccccccccccccccc) :\n"
6148                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
6149                Style);
6150 
6151   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6152   Style.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6153   verifyFormat("SomeClassWithALongName::Constructor(\n"
6154                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
6155                "    int bbbbbbbbbbbbb) :\n"
6156                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6157                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
6158                Style);
6159 }
6160 
TEST_F(FormatTest,AllowAllArgumentsOnNextLine)6161 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
6162   FormatStyle Style = getLLVMStyle();
6163   Style.ColumnLimit = 60;
6164   Style.BinPackArguments = false;
6165   for (int i = 0; i < 4; ++i) {
6166     // Test all combinations of parameters that should not have an effect.
6167     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
6168     Style.PackConstructorInitializers =
6169         i & 2 ? FormatStyle::PCIS_BinPack : FormatStyle::PCIS_Never;
6170 
6171     Style.AllowAllArgumentsOnNextLine = true;
6172     verifyFormat("void foo() {\n"
6173                  "  FunctionCallWithReallyLongName(\n"
6174                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
6175                  "}",
6176                  Style);
6177     Style.AllowAllArgumentsOnNextLine = false;
6178     verifyFormat("void foo() {\n"
6179                  "  FunctionCallWithReallyLongName(\n"
6180                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6181                  "      bbbbbbbbbbbb);\n"
6182                  "}",
6183                  Style);
6184 
6185     Style.AllowAllArgumentsOnNextLine = true;
6186     verifyFormat("void foo() {\n"
6187                  "  auto VariableWithReallyLongName = {\n"
6188                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
6189                  "}",
6190                  Style);
6191     Style.AllowAllArgumentsOnNextLine = false;
6192     verifyFormat("void foo() {\n"
6193                  "  auto VariableWithReallyLongName = {\n"
6194                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6195                  "      bbbbbbbbbbbb};\n"
6196                  "}",
6197                  Style);
6198   }
6199 
6200   // This parameter should not affect declarations.
6201   Style.BinPackParameters = false;
6202   Style.AllowAllArgumentsOnNextLine = false;
6203   Style.AllowAllParametersOfDeclarationOnNextLine = true;
6204   verifyFormat("void FunctionCallWithReallyLongName(\n"
6205                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
6206                Style);
6207   Style.AllowAllParametersOfDeclarationOnNextLine = false;
6208   verifyFormat("void FunctionCallWithReallyLongName(\n"
6209                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
6210                "    int bbbbbbbbbbbb);",
6211                Style);
6212 }
6213 
TEST_F(FormatTest,AllowAllArgumentsOnNextLineDontAlign)6214 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
6215   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
6216   // and BAS_Align.
6217   auto Style = getLLVMStyle();
6218   Style.ColumnLimit = 35;
6219   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
6220                     "void functionDecl(int A, int B, int C);";
6221   Style.AllowAllArgumentsOnNextLine = false;
6222   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6223   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6224                       "    paramC);\n"
6225                       "void functionDecl(int A, int B,\n"
6226                       "    int C);"),
6227             format(Input, Style));
6228   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6229   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6230                       "             paramC);\n"
6231                       "void functionDecl(int A, int B,\n"
6232                       "                  int C);"),
6233             format(Input, Style));
6234   // However, BAS_AlwaysBreak should take precedence over
6235   // AllowAllArgumentsOnNextLine.
6236   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6237   EXPECT_EQ(StringRef("functionCall(\n"
6238                       "    paramA, paramB, paramC);\n"
6239                       "void functionDecl(\n"
6240                       "    int A, int B, int C);"),
6241             format(Input, Style));
6242 
6243   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
6244   // first argument.
6245   Style.AllowAllArgumentsOnNextLine = true;
6246   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6247   EXPECT_EQ(StringRef("functionCall(\n"
6248                       "    paramA, paramB, paramC);\n"
6249                       "void functionDecl(\n"
6250                       "    int A, int B, int C);"),
6251             format(Input, Style));
6252   // It wouldn't fit on one line with aligned parameters so this setting
6253   // doesn't change anything for BAS_Align.
6254   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6255   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
6256                       "             paramC);\n"
6257                       "void functionDecl(int A, int B,\n"
6258                       "                  int C);"),
6259             format(Input, Style));
6260   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6261   EXPECT_EQ(StringRef("functionCall(\n"
6262                       "    paramA, paramB, paramC);\n"
6263                       "void functionDecl(\n"
6264                       "    int A, int B, int C);"),
6265             format(Input, Style));
6266 }
6267 
TEST_F(FormatTest,BreakConstructorInitializersAfterColon)6268 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
6269   FormatStyle Style = getLLVMStyle();
6270   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
6271 
6272   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
6273   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
6274                getStyleWithColumns(Style, 45));
6275   verifyFormat("Constructor() :\n"
6276                "    Initializer(FitsOnTheLine) {}",
6277                getStyleWithColumns(Style, 44));
6278   verifyFormat("Constructor() :\n"
6279                "    Initializer(FitsOnTheLine) {}",
6280                getStyleWithColumns(Style, 43));
6281 
6282   verifyFormat("template <typename T>\n"
6283                "Constructor() : Initializer(FitsOnTheLine) {}",
6284                getStyleWithColumns(Style, 50));
6285   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6286   verifyFormat(
6287       "SomeClass::Constructor() :\n"
6288       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6289       Style);
6290 
6291   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
6292   verifyFormat(
6293       "SomeClass::Constructor() :\n"
6294       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6295       Style);
6296 
6297   verifyFormat(
6298       "SomeClass::Constructor() :\n"
6299       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6300       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6301       Style);
6302   verifyFormat(
6303       "SomeClass::Constructor() :\n"
6304       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6305       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
6306       Style);
6307   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6308                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6309                "    aaaaaaaaaa(aaaaaa) {}",
6310                Style);
6311 
6312   verifyFormat("Constructor() :\n"
6313                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6314                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6315                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6316                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
6317                Style);
6318 
6319   verifyFormat("Constructor() :\n"
6320                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6321                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6322                Style);
6323 
6324   verifyFormat("Constructor(int Parameter = 0) :\n"
6325                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
6326                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
6327                Style);
6328   verifyFormat("Constructor() :\n"
6329                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
6330                "}",
6331                getStyleWithColumns(Style, 60));
6332   verifyFormat("Constructor() :\n"
6333                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6334                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
6335                Style);
6336 
6337   // Here a line could be saved by splitting the second initializer onto two
6338   // lines, but that is not desirable.
6339   verifyFormat("Constructor() :\n"
6340                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
6341                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
6342                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6343                Style);
6344 
6345   FormatStyle OnePerLine = Style;
6346   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_CurrentLine;
6347   verifyFormat("SomeClass::Constructor() :\n"
6348                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6349                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6350                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6351                OnePerLine);
6352   verifyFormat("SomeClass::Constructor() :\n"
6353                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
6354                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
6355                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
6356                OnePerLine);
6357   verifyFormat("MyClass::MyClass(int var) :\n"
6358                "    some_var_(var),            // 4 space indent\n"
6359                "    some_other_var_(var + 1) { // lined up\n"
6360                "}",
6361                OnePerLine);
6362   verifyFormat("Constructor() :\n"
6363                "    aaaaa(aaaaaa),\n"
6364                "    aaaaa(aaaaaa),\n"
6365                "    aaaaa(aaaaaa),\n"
6366                "    aaaaa(aaaaaa),\n"
6367                "    aaaaa(aaaaaa) {}",
6368                OnePerLine);
6369   verifyFormat("Constructor() :\n"
6370                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
6371                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
6372                OnePerLine);
6373   OnePerLine.BinPackParameters = false;
6374   verifyFormat("Constructor() :\n"
6375                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6376                "        aaaaaaaaaaa().aaa(),\n"
6377                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6378                OnePerLine);
6379   OnePerLine.ColumnLimit = 60;
6380   verifyFormat("Constructor() :\n"
6381                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
6382                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
6383                OnePerLine);
6384 
6385   EXPECT_EQ("Constructor() :\n"
6386             "    // Comment forcing unwanted break.\n"
6387             "    aaaa(aaaa) {}",
6388             format("Constructor() :\n"
6389                    "    // Comment forcing unwanted break.\n"
6390                    "    aaaa(aaaa) {}",
6391                    Style));
6392 
6393   Style.ColumnLimit = 0;
6394   verifyFormat("SomeClass::Constructor() :\n"
6395                "    a(a) {}",
6396                Style);
6397   verifyFormat("SomeClass::Constructor() noexcept :\n"
6398                "    a(a) {}",
6399                Style);
6400   verifyFormat("SomeClass::Constructor() :\n"
6401                "    a(a), b(b), c(c) {}",
6402                Style);
6403   verifyFormat("SomeClass::Constructor() :\n"
6404                "    a(a) {\n"
6405                "  foo();\n"
6406                "  bar();\n"
6407                "}",
6408                Style);
6409 
6410   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
6411   verifyFormat("SomeClass::Constructor() :\n"
6412                "    a(a), b(b), c(c) {\n"
6413                "}",
6414                Style);
6415   verifyFormat("SomeClass::Constructor() :\n"
6416                "    a(a) {\n"
6417                "}",
6418                Style);
6419 
6420   Style.ColumnLimit = 80;
6421   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
6422   Style.ConstructorInitializerIndentWidth = 2;
6423   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
6424   verifyFormat("SomeClass::Constructor() :\n"
6425                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6426                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
6427                Style);
6428 
6429   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
6430   // well
6431   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
6432   verifyFormat(
6433       "class SomeClass\n"
6434       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6435       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6436       Style);
6437   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
6438   verifyFormat(
6439       "class SomeClass\n"
6440       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6441       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6442       Style);
6443   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
6444   verifyFormat(
6445       "class SomeClass :\n"
6446       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6447       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6448       Style);
6449   Style.BreakInheritanceList = FormatStyle::BILS_AfterComma;
6450   verifyFormat(
6451       "class SomeClass\n"
6452       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6453       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
6454       Style);
6455 }
6456 
6457 #ifndef EXPENSIVE_CHECKS
6458 // Expensive checks enables libstdc++ checking which includes validating the
6459 // state of ranges used in std::priority_queue - this blows out the
6460 // runtime/scalability of the function and makes this test unacceptably slow.
TEST_F(FormatTest,MemoizationTests)6461 TEST_F(FormatTest, MemoizationTests) {
6462   // This breaks if the memoization lookup does not take \c Indent and
6463   // \c LastSpace into account.
6464   verifyFormat(
6465       "extern CFRunLoopTimerRef\n"
6466       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
6467       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
6468       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
6469       "                     CFRunLoopTimerContext *context) {}");
6470 
6471   // Deep nesting somewhat works around our memoization.
6472   verifyFormat(
6473       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6474       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6475       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6476       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
6477       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
6478       getLLVMStyleWithColumns(65));
6479   verifyFormat(
6480       "aaaaa(\n"
6481       "    aaaaa,\n"
6482       "    aaaaa(\n"
6483       "        aaaaa,\n"
6484       "        aaaaa(\n"
6485       "            aaaaa,\n"
6486       "            aaaaa(\n"
6487       "                aaaaa,\n"
6488       "                aaaaa(\n"
6489       "                    aaaaa,\n"
6490       "                    aaaaa(\n"
6491       "                        aaaaa,\n"
6492       "                        aaaaa(\n"
6493       "                            aaaaa,\n"
6494       "                            aaaaa(\n"
6495       "                                aaaaa,\n"
6496       "                                aaaaa(\n"
6497       "                                    aaaaa,\n"
6498       "                                    aaaaa(\n"
6499       "                                        aaaaa,\n"
6500       "                                        aaaaa(\n"
6501       "                                            aaaaa,\n"
6502       "                                            aaaaa(\n"
6503       "                                                aaaaa,\n"
6504       "                                                aaaaa))))))))))));",
6505       getLLVMStyleWithColumns(65));
6506   verifyFormat(
6507       "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n"
6508       "                                  a),\n"
6509       "                                a),\n"
6510       "                              a),\n"
6511       "                            a),\n"
6512       "                          a),\n"
6513       "                        a),\n"
6514       "                      a),\n"
6515       "                    a),\n"
6516       "                  a),\n"
6517       "                a),\n"
6518       "              a),\n"
6519       "            a),\n"
6520       "          a),\n"
6521       "        a),\n"
6522       "      a),\n"
6523       "    a),\n"
6524       "  a)",
6525       getLLVMStyleWithColumns(65));
6526 
6527   // This test takes VERY long when memoization is broken.
6528   FormatStyle OnePerLine = getLLVMStyle();
6529   OnePerLine.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
6530   OnePerLine.BinPackParameters = false;
6531   std::string input = "Constructor()\n"
6532                       "    : aaaa(a,\n";
6533   for (unsigned i = 0, e = 80; i != e; ++i) {
6534     input += "           a,\n";
6535   }
6536   input += "           a) {}";
6537   verifyFormat(input, OnePerLine);
6538 }
6539 #endif
6540 
TEST_F(FormatTest,BreaksAsHighAsPossible)6541 TEST_F(FormatTest, BreaksAsHighAsPossible) {
6542   verifyFormat(
6543       "void f() {\n"
6544       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
6545       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
6546       "    f();\n"
6547       "}");
6548   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
6549                "    Intervals[i - 1].getRange().getLast()) {\n}");
6550 }
6551 
TEST_F(FormatTest,BreaksFunctionDeclarations)6552 TEST_F(FormatTest, BreaksFunctionDeclarations) {
6553   // Principially, we break function declarations in a certain order:
6554   // 1) break amongst arguments.
6555   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
6556                "                              Cccccccccccccc cccccccccccccc);");
6557   verifyFormat("template <class TemplateIt>\n"
6558                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
6559                "                            TemplateIt *stop) {}");
6560 
6561   // 2) break after return type.
6562   verifyFormat(
6563       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6564       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
6565       getGoogleStyle());
6566 
6567   // 3) break after (.
6568   verifyFormat(
6569       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
6570       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
6571       getGoogleStyle());
6572 
6573   // 4) break before after nested name specifiers.
6574   verifyFormat(
6575       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6576       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
6577       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
6578       getGoogleStyle());
6579 
6580   // However, there are exceptions, if a sufficient amount of lines can be
6581   // saved.
6582   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
6583   // more adjusting.
6584   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6585                "                                  Cccccccccccccc cccccccccc,\n"
6586                "                                  Cccccccccccccc cccccccccc,\n"
6587                "                                  Cccccccccccccc cccccccccc,\n"
6588                "                                  Cccccccccccccc cccccccccc);");
6589   verifyFormat(
6590       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6591       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6592       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6593       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
6594       getGoogleStyle());
6595   verifyFormat(
6596       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
6597       "                                          Cccccccccccccc cccccccccc,\n"
6598       "                                          Cccccccccccccc cccccccccc,\n"
6599       "                                          Cccccccccccccc cccccccccc,\n"
6600       "                                          Cccccccccccccc cccccccccc,\n"
6601       "                                          Cccccccccccccc cccccccccc,\n"
6602       "                                          Cccccccccccccc cccccccccc);");
6603   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6604                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6605                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6606                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
6607                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
6608 
6609   // Break after multi-line parameters.
6610   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6611                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6612                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6613                "    bbbb bbbb);");
6614   verifyFormat("void SomeLoooooooooooongFunction(\n"
6615                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
6616                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6617                "    int bbbbbbbbbbbbb);");
6618 
6619   // Treat overloaded operators like other functions.
6620   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6621                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
6622   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6623                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
6624   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
6625                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
6626   verifyGoogleFormat(
6627       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
6628       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6629   verifyGoogleFormat(
6630       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
6631       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
6632   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6633                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6634   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
6635                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
6636   verifyGoogleFormat(
6637       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
6638       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6639       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
6640   verifyGoogleFormat("template <typename T>\n"
6641                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6642                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
6643                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
6644 
6645   FormatStyle Style = getLLVMStyle();
6646   Style.PointerAlignment = FormatStyle::PAS_Left;
6647   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6648                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
6649                Style);
6650   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
6651                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6652                Style);
6653 }
6654 
TEST_F(FormatTest,DontBreakBeforeQualifiedOperator)6655 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
6656   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
6657   // Prefer keeping `::` followed by `operator` together.
6658   EXPECT_EQ("const aaaa::bbbbbbb &\n"
6659             "ccccccccc::operator++() {\n"
6660             "  stuff();\n"
6661             "}",
6662             format("const aaaa::bbbbbbb\n"
6663                    "&ccccccccc::operator++() { stuff(); }",
6664                    getLLVMStyleWithColumns(40)));
6665 }
6666 
TEST_F(FormatTest,TrailingReturnType)6667 TEST_F(FormatTest, TrailingReturnType) {
6668   verifyFormat("auto foo() -> int;\n");
6669   // correct trailing return type spacing
6670   verifyFormat("auto operator->() -> int;\n");
6671   verifyFormat("auto operator++(int) -> int;\n");
6672 
6673   verifyFormat("struct S {\n"
6674                "  auto bar() const -> int;\n"
6675                "};");
6676   verifyFormat("template <size_t Order, typename T>\n"
6677                "auto load_img(const std::string &filename)\n"
6678                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
6679   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
6680                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
6681   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
6682   verifyFormat("template <typename T>\n"
6683                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
6684                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
6685 
6686   // Not trailing return types.
6687   verifyFormat("void f() { auto a = b->c(); }");
6688 }
6689 
TEST_F(FormatTest,DeductionGuides)6690 TEST_F(FormatTest, DeductionGuides) {
6691   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
6692   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
6693   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
6694   verifyFormat(
6695       "template <class... T>\n"
6696       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
6697   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
6698   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
6699   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
6700   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
6701   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
6702   verifyFormat("template <class T> x() -> x<1>;");
6703   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
6704 
6705   // Ensure not deduction guides.
6706   verifyFormat("c()->f<int>();");
6707   verifyFormat("x()->foo<1>;");
6708   verifyFormat("x = p->foo<3>();");
6709   verifyFormat("x()->x<1>();");
6710   verifyFormat("x()->x<1>;");
6711 }
6712 
TEST_F(FormatTest,BreaksFunctionDeclarationsWithTrailingTokens)6713 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
6714   // Avoid breaking before trailing 'const' or other trailing annotations, if
6715   // they are not function-like.
6716   FormatStyle Style = getGoogleStyle();
6717   Style.ColumnLimit = 47;
6718   verifyFormat("void someLongFunction(\n"
6719                "    int someLoooooooooooooongParameter) const {\n}",
6720                getLLVMStyleWithColumns(47));
6721   verifyFormat("LoooooongReturnType\n"
6722                "someLoooooooongFunction() const {}",
6723                getLLVMStyleWithColumns(47));
6724   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
6725                "    const {}",
6726                Style);
6727   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6728                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
6729   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6730                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
6731   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
6732                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
6733   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
6734                "                   aaaaaaaaaaa aaaaa) const override;");
6735   verifyGoogleFormat(
6736       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6737       "    const override;");
6738 
6739   // Even if the first parameter has to be wrapped.
6740   verifyFormat("void someLongFunction(\n"
6741                "    int someLongParameter) const {}",
6742                getLLVMStyleWithColumns(46));
6743   verifyFormat("void someLongFunction(\n"
6744                "    int someLongParameter) const {}",
6745                Style);
6746   verifyFormat("void someLongFunction(\n"
6747                "    int someLongParameter) override {}",
6748                Style);
6749   verifyFormat("void someLongFunction(\n"
6750                "    int someLongParameter) OVERRIDE {}",
6751                Style);
6752   verifyFormat("void someLongFunction(\n"
6753                "    int someLongParameter) final {}",
6754                Style);
6755   verifyFormat("void someLongFunction(\n"
6756                "    int someLongParameter) FINAL {}",
6757                Style);
6758   verifyFormat("void someLongFunction(\n"
6759                "    int parameter) const override {}",
6760                Style);
6761 
6762   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
6763   verifyFormat("void someLongFunction(\n"
6764                "    int someLongParameter) const\n"
6765                "{\n"
6766                "}",
6767                Style);
6768 
6769   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
6770   verifyFormat("void someLongFunction(\n"
6771                "    int someLongParameter) const\n"
6772                "  {\n"
6773                "  }",
6774                Style);
6775 
6776   // Unless these are unknown annotations.
6777   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
6778                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6779                "    LONG_AND_UGLY_ANNOTATION;");
6780 
6781   // Breaking before function-like trailing annotations is fine to keep them
6782   // close to their arguments.
6783   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6784                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
6785   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
6786                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
6787   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
6788                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
6789   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
6790                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
6791   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
6792 
6793   verifyFormat(
6794       "void aaaaaaaaaaaaaaaaaa()\n"
6795       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
6796       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
6797   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6798                "    __attribute__((unused));");
6799   verifyGoogleFormat(
6800       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6801       "    GUARDED_BY(aaaaaaaaaaaa);");
6802   verifyGoogleFormat(
6803       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6804       "    GUARDED_BY(aaaaaaaaaaaa);");
6805   verifyGoogleFormat(
6806       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
6807       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6808   verifyGoogleFormat(
6809       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
6810       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
6811 }
6812 
TEST_F(FormatTest,FunctionAnnotations)6813 TEST_F(FormatTest, FunctionAnnotations) {
6814   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6815                "int OldFunction(const string &parameter) {}");
6816   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6817                "string OldFunction(const string &parameter) {}");
6818   verifyFormat("template <typename T>\n"
6819                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
6820                "string OldFunction(const string &parameter) {}");
6821 
6822   // Not function annotations.
6823   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6824                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
6825   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
6826                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
6827   verifyFormat("MACRO(abc).function() // wrap\n"
6828                "    << abc;");
6829   verifyFormat("MACRO(abc)->function() // wrap\n"
6830                "    << abc;");
6831   verifyFormat("MACRO(abc)::function() // wrap\n"
6832                "    << abc;");
6833 }
6834 
TEST_F(FormatTest,BreaksDesireably)6835 TEST_F(FormatTest, BreaksDesireably) {
6836   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
6837                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
6838                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
6839   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6840                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
6841                "}");
6842 
6843   verifyFormat(
6844       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6845       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
6846 
6847   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6848                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6849                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6850 
6851   verifyFormat(
6852       "aaaaaaaa(aaaaaaaaaaaaa,\n"
6853       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6854       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
6855       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6856       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
6857 
6858   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
6859                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6860 
6861   verifyFormat(
6862       "void f() {\n"
6863       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
6864       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
6865       "}");
6866   verifyFormat(
6867       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6868       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6869   verifyFormat(
6870       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6871       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6872   verifyFormat(
6873       "aaaaaa(aaa,\n"
6874       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6875       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6876       "       aaaa);");
6877   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6878                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6879                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6880 
6881   // Indent consistently independent of call expression and unary operator.
6882   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6883                "    dddddddddddddddddddddddddddddd));");
6884   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
6885                "    dddddddddddddddddddddddddddddd));");
6886   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
6887                "    dddddddddddddddddddddddddddddd));");
6888 
6889   // This test case breaks on an incorrect memoization, i.e. an optimization not
6890   // taking into account the StopAt value.
6891   verifyFormat(
6892       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
6893       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
6894       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
6895       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6896 
6897   verifyFormat("{\n  {\n    {\n"
6898                "      Annotation.SpaceRequiredBefore =\n"
6899                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
6900                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
6901                "    }\n  }\n}");
6902 
6903   // Break on an outer level if there was a break on an inner level.
6904   EXPECT_EQ("f(g(h(a, // comment\n"
6905             "      b, c),\n"
6906             "    d, e),\n"
6907             "  x, y);",
6908             format("f(g(h(a, // comment\n"
6909                    "    b, c), d, e), x, y);"));
6910 
6911   // Prefer breaking similar line breaks.
6912   verifyFormat(
6913       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
6914       "                             NSTrackingMouseEnteredAndExited |\n"
6915       "                             NSTrackingActiveAlways;");
6916 }
6917 
TEST_F(FormatTest,FormatsDeclarationsOnePerLine)6918 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
6919   FormatStyle NoBinPacking = getGoogleStyle();
6920   NoBinPacking.BinPackParameters = false;
6921   NoBinPacking.BinPackArguments = true;
6922   verifyFormat("void f() {\n"
6923                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
6924                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
6925                "}",
6926                NoBinPacking);
6927   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
6928                "       int aaaaaaaaaaaaaaaaaaaa,\n"
6929                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6930                NoBinPacking);
6931 
6932   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
6933   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6934                "                        vector<int> bbbbbbbbbbbbbbb);",
6935                NoBinPacking);
6936   // FIXME: This behavior difference is probably not wanted. However, currently
6937   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
6938   // template arguments from BreakBeforeParameter being set because of the
6939   // one-per-line formatting.
6940   verifyFormat(
6941       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
6942       "                                             aaaaaaaaaa> aaaaaaaaaa);",
6943       NoBinPacking);
6944   verifyFormat(
6945       "void fffffffffff(\n"
6946       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
6947       "        aaaaaaaaaa);");
6948 }
6949 
TEST_F(FormatTest,FormatsOneParameterPerLineIfNecessary)6950 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
6951   FormatStyle NoBinPacking = getGoogleStyle();
6952   NoBinPacking.BinPackParameters = false;
6953   NoBinPacking.BinPackArguments = false;
6954   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
6955                "  aaaaaaaaaaaaaaaaaaaa,\n"
6956                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
6957                NoBinPacking);
6958   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
6959                "        aaaaaaaaaaaaa,\n"
6960                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
6961                NoBinPacking);
6962   verifyFormat(
6963       "aaaaaaaa(aaaaaaaaaaaaa,\n"
6964       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6965       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
6966       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6967       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
6968       NoBinPacking);
6969   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
6970                "    .aaaaaaaaaaaaaaaaaa();",
6971                NoBinPacking);
6972   verifyFormat("void f() {\n"
6973                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6974                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
6975                "}",
6976                NoBinPacking);
6977 
6978   verifyFormat(
6979       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6980       "             aaaaaaaaaaaa,\n"
6981       "             aaaaaaaaaaaa);",
6982       NoBinPacking);
6983   verifyFormat(
6984       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
6985       "                               ddddddddddddddddddddddddddddd),\n"
6986       "             test);",
6987       NoBinPacking);
6988 
6989   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
6990                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
6991                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
6992                "    aaaaaaaaaaaaaaaaaa;",
6993                NoBinPacking);
6994   verifyFormat("a(\"a\"\n"
6995                "  \"a\",\n"
6996                "  a);");
6997 
6998   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
6999   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
7000                "                aaaaaaaaa,\n"
7001                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7002                NoBinPacking);
7003   verifyFormat(
7004       "void f() {\n"
7005       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
7006       "      .aaaaaaa();\n"
7007       "}",
7008       NoBinPacking);
7009   verifyFormat(
7010       "template <class SomeType, class SomeOtherType>\n"
7011       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
7012       NoBinPacking);
7013 }
7014 
TEST_F(FormatTest,AdaptiveOnePerLineFormatting)7015 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
7016   FormatStyle Style = getLLVMStyleWithColumns(15);
7017   Style.ExperimentalAutoDetectBinPacking = true;
7018   EXPECT_EQ("aaa(aaaa,\n"
7019             "    aaaa,\n"
7020             "    aaaa);\n"
7021             "aaa(aaaa,\n"
7022             "    aaaa,\n"
7023             "    aaaa);",
7024             format("aaa(aaaa,\n" // one-per-line
7025                    "  aaaa,\n"
7026                    "    aaaa  );\n"
7027                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7028                    Style));
7029   EXPECT_EQ("aaa(aaaa, aaaa,\n"
7030             "    aaaa);\n"
7031             "aaa(aaaa, aaaa,\n"
7032             "    aaaa);",
7033             format("aaa(aaaa,  aaaa,\n" // bin-packed
7034                    "    aaaa  );\n"
7035                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
7036                    Style));
7037 }
7038 
TEST_F(FormatTest,FormatsBuilderPattern)7039 TEST_F(FormatTest, FormatsBuilderPattern) {
7040   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
7041                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
7042                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
7043                "    .StartsWith(\".init\", ORDER_INIT)\n"
7044                "    .StartsWith(\".fini\", ORDER_FINI)\n"
7045                "    .StartsWith(\".hash\", ORDER_HASH)\n"
7046                "    .Default(ORDER_TEXT);\n");
7047 
7048   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
7049                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
7050   verifyFormat("aaaaaaa->aaaaaaa\n"
7051                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7052                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7053                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7054   verifyFormat(
7055       "aaaaaaa->aaaaaaa\n"
7056       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7057       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
7058   verifyFormat(
7059       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
7060       "    aaaaaaaaaaaaaa);");
7061   verifyFormat(
7062       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
7063       "    aaaaaa->aaaaaaaaaaaa()\n"
7064       "        ->aaaaaaaaaaaaaaaa(\n"
7065       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7066       "        ->aaaaaaaaaaaaaaaaa();");
7067   verifyGoogleFormat(
7068       "void f() {\n"
7069       "  someo->Add((new util::filetools::Handler(dir))\n"
7070       "                 ->OnEvent1(NewPermanentCallback(\n"
7071       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
7072       "                 ->OnEvent2(NewPermanentCallback(\n"
7073       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
7074       "                 ->OnEvent3(NewPermanentCallback(\n"
7075       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
7076       "                 ->OnEvent5(NewPermanentCallback(\n"
7077       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
7078       "                 ->OnEvent6(NewPermanentCallback(\n"
7079       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
7080       "}");
7081 
7082   verifyFormat(
7083       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
7084   verifyFormat("aaaaaaaaaaaaaaa()\n"
7085                "    .aaaaaaaaaaaaaaa()\n"
7086                "    .aaaaaaaaaaaaaaa()\n"
7087                "    .aaaaaaaaaaaaaaa()\n"
7088                "    .aaaaaaaaaaaaaaa();");
7089   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7090                "    .aaaaaaaaaaaaaaa()\n"
7091                "    .aaaaaaaaaaaaaaa()\n"
7092                "    .aaaaaaaaaaaaaaa();");
7093   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7094                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
7095                "    .aaaaaaaaaaaaaaa();");
7096   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
7097                "    ->aaaaaaaaaaaaaae(0)\n"
7098                "    ->aaaaaaaaaaaaaaa();");
7099 
7100   // Don't linewrap after very short segments.
7101   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7102                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7103                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7104   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7105                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7106                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7107   verifyFormat("aaa()\n"
7108                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7109                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7110                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7111 
7112   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7113                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7114                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
7115   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
7116                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
7117                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
7118 
7119   // Prefer not to break after empty parentheses.
7120   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
7121                "    First->LastNewlineOffset);");
7122 
7123   // Prefer not to create "hanging" indents.
7124   verifyFormat(
7125       "return !soooooooooooooome_map\n"
7126       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7127       "            .second;");
7128   verifyFormat(
7129       "return aaaaaaaaaaaaaaaa\n"
7130       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
7131       "    .aaaa(aaaaaaaaaaaaaa);");
7132   // No hanging indent here.
7133   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
7134                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7135   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
7136                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7137   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7138                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7139                getLLVMStyleWithColumns(60));
7140   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
7141                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
7142                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7143                getLLVMStyleWithColumns(59));
7144   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7145                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7146                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7147 
7148   // Dont break if only closing statements before member call
7149   verifyFormat("test() {\n"
7150                "  ([]() -> {\n"
7151                "    int b = 32;\n"
7152                "    return 3;\n"
7153                "  }).foo();\n"
7154                "}");
7155   verifyFormat("test() {\n"
7156                "  (\n"
7157                "      []() -> {\n"
7158                "        int b = 32;\n"
7159                "        return 3;\n"
7160                "      },\n"
7161                "      foo, bar)\n"
7162                "      .foo();\n"
7163                "}");
7164   verifyFormat("test() {\n"
7165                "  ([]() -> {\n"
7166                "    int b = 32;\n"
7167                "    return 3;\n"
7168                "  })\n"
7169                "      .foo()\n"
7170                "      .bar();\n"
7171                "}");
7172   verifyFormat("test() {\n"
7173                "  ([]() -> {\n"
7174                "    int b = 32;\n"
7175                "    return 3;\n"
7176                "  })\n"
7177                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
7178                "           \"bbbb\");\n"
7179                "}",
7180                getLLVMStyleWithColumns(30));
7181 }
7182 
TEST_F(FormatTest,BreaksAccordingToOperatorPrecedence)7183 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
7184   verifyFormat(
7185       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
7186       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
7187   verifyFormat(
7188       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
7189       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
7190 
7191   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7192                "    ccccccccccccccccccccccccc) {\n}");
7193   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
7194                "    ccccccccccccccccccccccccc) {\n}");
7195 
7196   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
7197                "    ccccccccccccccccccccccccc) {\n}");
7198   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
7199                "    ccccccccccccccccccccccccc) {\n}");
7200 
7201   verifyFormat(
7202       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
7203       "    ccccccccccccccccccccccccc) {\n}");
7204   verifyFormat(
7205       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
7206       "    ccccccccccccccccccccccccc) {\n}");
7207 
7208   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
7209                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
7210                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
7211                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7212   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
7213                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
7214                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
7215                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
7216 
7217   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
7218                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
7219                "    aaaaaaaaaaaaaaa != aa) {\n}");
7220   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
7221                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
7222                "    aaaaaaaaaaaaaaa != aa) {\n}");
7223 }
7224 
TEST_F(FormatTest,BreaksAfterAssignments)7225 TEST_F(FormatTest, BreaksAfterAssignments) {
7226   verifyFormat(
7227       "unsigned Cost =\n"
7228       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
7229       "                        SI->getPointerAddressSpaceee());\n");
7230   verifyFormat(
7231       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
7232       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
7233 
7234   verifyFormat(
7235       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
7236       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
7237   verifyFormat("unsigned OriginalStartColumn =\n"
7238                "    SourceMgr.getSpellingColumnNumber(\n"
7239                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
7240                "    1;");
7241 }
7242 
TEST_F(FormatTest,ConfigurableBreakAssignmentPenalty)7243 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
7244   FormatStyle Style = getLLVMStyle();
7245   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7246                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
7247                Style);
7248 
7249   Style.PenaltyBreakAssignment = 20;
7250   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
7251                "                                 cccccccccccccccccccccccccc;",
7252                Style);
7253 }
7254 
TEST_F(FormatTest,AlignsAfterAssignments)7255 TEST_F(FormatTest, AlignsAfterAssignments) {
7256   verifyFormat(
7257       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7258       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
7259   verifyFormat(
7260       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7261       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
7262   verifyFormat(
7263       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7264       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
7265   verifyFormat(
7266       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7267       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
7268   verifyFormat(
7269       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7270       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
7271       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
7272 }
7273 
TEST_F(FormatTest,AlignsAfterReturn)7274 TEST_F(FormatTest, AlignsAfterReturn) {
7275   verifyFormat(
7276       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7277       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
7278   verifyFormat(
7279       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7280       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
7281   verifyFormat(
7282       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7283       "       aaaaaaaaaaaaaaaaaaaaaa();");
7284   verifyFormat(
7285       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
7286       "        aaaaaaaaaaaaaaaaaaaaaa());");
7287   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7288                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7289   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7290                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
7291                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7292   verifyFormat("return\n"
7293                "    // true if code is one of a or b.\n"
7294                "    code == a || code == b;");
7295 }
7296 
TEST_F(FormatTest,AlignsAfterOpenBracket)7297 TEST_F(FormatTest, AlignsAfterOpenBracket) {
7298   verifyFormat(
7299       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7300       "                                                aaaaaaaaa aaaaaaa) {}");
7301   verifyFormat(
7302       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7303       "                                               aaaaaaaaaaa aaaaaaaaa);");
7304   verifyFormat(
7305       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7306       "                                             aaaaaaaaaaaaaaaaaaaaa));");
7307   FormatStyle Style = getLLVMStyle();
7308   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7309   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7310                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
7311                Style);
7312   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7313                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
7314                Style);
7315   verifyFormat("SomeLongVariableName->someFunction(\n"
7316                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
7317                Style);
7318   verifyFormat(
7319       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
7320       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7321       Style);
7322   verifyFormat(
7323       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
7324       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7325       Style);
7326   verifyFormat(
7327       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
7328       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7329       Style);
7330 
7331   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
7332                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
7333                "        b));",
7334                Style);
7335 
7336   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7337   Style.BinPackArguments = false;
7338   Style.BinPackParameters = false;
7339   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7340                "    aaaaaaaaaaa aaaaaaaa,\n"
7341                "    aaaaaaaaa aaaaaaa,\n"
7342                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
7343                Style);
7344   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
7345                "    aaaaaaaaaaa aaaaaaaaa,\n"
7346                "    aaaaaaaaaaa aaaaaaaaa,\n"
7347                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7348                Style);
7349   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
7350                "    aaaaaaaaaaaaaaa,\n"
7351                "    aaaaaaaaaaaaaaaaaaaaa,\n"
7352                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
7353                Style);
7354   verifyFormat(
7355       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
7356       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7357       Style);
7358   verifyFormat(
7359       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
7360       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
7361       Style);
7362   verifyFormat(
7363       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7364       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7365       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
7366       "    aaaaaaaaaaaaaaaa);",
7367       Style);
7368   verifyFormat(
7369       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
7370       "    aaaaaaaaaaaaaaaaaaaaa(\n"
7371       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
7372       "    aaaaaaaaaaaaaaaa);",
7373       Style);
7374 }
7375 
TEST_F(FormatTest,ParenthesesAndOperandAlignment)7376 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
7377   FormatStyle Style = getLLVMStyleWithColumns(40);
7378   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7379                "          bbbbbbbbbbbbbbbbbbbbbb);",
7380                Style);
7381   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
7382   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7383   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7384                "          bbbbbbbbbbbbbbbbbbbbbb);",
7385                Style);
7386   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7387   Style.AlignOperands = FormatStyle::OAS_Align;
7388   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7389                "          bbbbbbbbbbbbbbbbbbbbbb);",
7390                Style);
7391   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7392   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7393   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
7394                "    bbbbbbbbbbbbbbbbbbbbbb);",
7395                Style);
7396 }
7397 
TEST_F(FormatTest,BreaksConditionalExpressions)7398 TEST_F(FormatTest, BreaksConditionalExpressions) {
7399   verifyFormat(
7400       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7401       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7402       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7403   verifyFormat(
7404       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7405       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7406       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7407   verifyFormat(
7408       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7409       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7410   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
7411                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7412                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7413   verifyFormat(
7414       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
7415       "                                                    : aaaaaaaaaaaaa);");
7416   verifyFormat(
7417       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7418       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7419       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7420       "                   aaaaaaaaaaaaa);");
7421   verifyFormat(
7422       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7423       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7424       "                   aaaaaaaaaaaaa);");
7425   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7426                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7427                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7428                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7429                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7430   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7431                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7432                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7433                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7434                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7435                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7436                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7437   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7438                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7439                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7440                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7441                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7442   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7443                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7444                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7445   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7446                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7447                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7448                "        : aaaaaaaaaaaaaaaa;");
7449   verifyFormat(
7450       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7451       "    ? aaaaaaaaaaaaaaa\n"
7452       "    : aaaaaaaaaaaaaaa;");
7453   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7454                "          aaaaaaaaa\n"
7455                "      ? b\n"
7456                "      : c);");
7457   verifyFormat("return aaaa == bbbb\n"
7458                "           // comment\n"
7459                "           ? aaaa\n"
7460                "           : bbbb;");
7461   verifyFormat("unsigned Indent =\n"
7462                "    format(TheLine.First,\n"
7463                "           IndentForLevel[TheLine.Level] >= 0\n"
7464                "               ? IndentForLevel[TheLine.Level]\n"
7465                "               : TheLine * 2,\n"
7466                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
7467                getLLVMStyleWithColumns(60));
7468   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7469                "                  ? aaaaaaaaaaaaaaa\n"
7470                "                  : bbbbbbbbbbbbbbb //\n"
7471                "                        ? ccccccccccccccc\n"
7472                "                        : ddddddddddddddd;");
7473   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
7474                "                  ? aaaaaaaaaaaaaaa\n"
7475                "                  : (bbbbbbbbbbbbbbb //\n"
7476                "                         ? ccccccccccccccc\n"
7477                "                         : ddddddddddddddd);");
7478   verifyFormat(
7479       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7480       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
7481       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
7482       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
7483       "                                      : aaaaaaaaaa;");
7484   verifyFormat(
7485       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7486       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
7487       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7488 
7489   FormatStyle NoBinPacking = getLLVMStyle();
7490   NoBinPacking.BinPackArguments = false;
7491   verifyFormat(
7492       "void f() {\n"
7493       "  g(aaa,\n"
7494       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7495       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7496       "        ? aaaaaaaaaaaaaaa\n"
7497       "        : aaaaaaaaaaaaaaa);\n"
7498       "}",
7499       NoBinPacking);
7500   verifyFormat(
7501       "void f() {\n"
7502       "  g(aaa,\n"
7503       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
7504       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7505       "        ?: aaaaaaaaaaaaaaa);\n"
7506       "}",
7507       NoBinPacking);
7508 
7509   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
7510                "             // comment.\n"
7511                "             ccccccccccccccccccccccccccccccccccccccc\n"
7512                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7513                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
7514 
7515   // Assignments in conditional expressions. Apparently not uncommon :-(.
7516   verifyFormat("return a != b\n"
7517                "           // comment\n"
7518                "           ? a = b\n"
7519                "           : a = b;");
7520   verifyFormat("return a != b\n"
7521                "           // comment\n"
7522                "           ? a = a != b\n"
7523                "                     // comment\n"
7524                "                     ? a = b\n"
7525                "                     : a\n"
7526                "           : a;\n");
7527   verifyFormat("return a != b\n"
7528                "           // comment\n"
7529                "           ? a\n"
7530                "           : a = a != b\n"
7531                "                     // comment\n"
7532                "                     ? a = b\n"
7533                "                     : a;");
7534 
7535   // Chained conditionals
7536   FormatStyle Style = getLLVMStyle();
7537   Style.ColumnLimit = 70;
7538   Style.AlignOperands = FormatStyle::OAS_Align;
7539   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7540                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7541                "                        : 3333333333333333;",
7542                Style);
7543   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7544                "       : bbbbbbbbbb     ? 2222222222222222\n"
7545                "                        : 3333333333333333;",
7546                Style);
7547   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
7548                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
7549                "                          : 3333333333333333;",
7550                Style);
7551   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7552                "       : bbbbbbbbbbbbbb ? 222222\n"
7553                "                        : 333333;",
7554                Style);
7555   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7556                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7557                "       : cccccccccccccc ? 3333333333333333\n"
7558                "                        : 4444444444444444;",
7559                Style);
7560   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
7561                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7562                "                        : 3333333333333333;",
7563                Style);
7564   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7565                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7566                "                        : (aaa ? bbb : ccc);",
7567                Style);
7568   verifyFormat(
7569       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7570       "                                             : cccccccccccccccccc)\n"
7571       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7572       "                        : 3333333333333333;",
7573       Style);
7574   verifyFormat(
7575       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7576       "                                             : cccccccccccccccccc)\n"
7577       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7578       "                        : 3333333333333333;",
7579       Style);
7580   verifyFormat(
7581       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7582       "                                             : dddddddddddddddddd)\n"
7583       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7584       "                        : 3333333333333333;",
7585       Style);
7586   verifyFormat(
7587       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7588       "                                             : dddddddddddddddddd)\n"
7589       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7590       "                        : 3333333333333333;",
7591       Style);
7592   verifyFormat(
7593       "return aaaaaaaaa        ? 1111111111111111\n"
7594       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7595       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7596       "                                             : dddddddddddddddddd)\n",
7597       Style);
7598   verifyFormat(
7599       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
7600       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7601       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7602       "                                             : cccccccccccccccccc);",
7603       Style);
7604   verifyFormat(
7605       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7606       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7607       "                                             : eeeeeeeeeeeeeeeeee)\n"
7608       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7609       "                        : 3333333333333333;",
7610       Style);
7611   verifyFormat(
7612       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
7613       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
7614       "                                             : eeeeeeeeeeeeeeeeee)\n"
7615       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7616       "                        : 3333333333333333;",
7617       Style);
7618   verifyFormat(
7619       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7620       "                           : cccccccccccc    ? dddddddddddddddddd\n"
7621       "                                             : eeeeeeeeeeeeeeeeee)\n"
7622       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7623       "                        : 3333333333333333;",
7624       Style);
7625   verifyFormat(
7626       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7627       "                                             : cccccccccccccccccc\n"
7628       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7629       "                        : 3333333333333333;",
7630       Style);
7631   verifyFormat(
7632       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7633       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
7634       "                                             : eeeeeeeeeeeeeeeeee\n"
7635       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
7636       "                        : 3333333333333333;",
7637       Style);
7638   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
7639                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
7640                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
7641                "                                   : eeeeeeeeeeeeeeeeee)\n"
7642                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7643                "                             : 3333333333333333;",
7644                Style);
7645   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
7646                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
7647                "             : cccccccccccccccc ? dddddddddddddddddd\n"
7648                "                                : eeeeeeeeeeeeeeeeee\n"
7649                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
7650                "                                 : 3333333333333333;",
7651                Style);
7652 
7653   Style.AlignOperands = FormatStyle::OAS_DontAlign;
7654   Style.BreakBeforeTernaryOperators = false;
7655   // FIXME: Aligning the question marks is weird given DontAlign.
7656   // Consider disabling this alignment in this case. Also check whether this
7657   // will render the adjustment from https://reviews.llvm.org/D82199
7658   // unnecessary.
7659   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
7660                "    bbbb                ? cccccccccccccccccc :\n"
7661                "                          ddddd;\n",
7662                Style);
7663 
7664   EXPECT_EQ(
7665       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
7666       "    /*\n"
7667       "     */\n"
7668       "    function() {\n"
7669       "      try {\n"
7670       "        return JJJJJJJJJJJJJJ(\n"
7671       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
7672       "      }\n"
7673       "    } :\n"
7674       "    function() {};",
7675       format(
7676           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
7677           "     /*\n"
7678           "      */\n"
7679           "     function() {\n"
7680           "      try {\n"
7681           "        return JJJJJJJJJJJJJJ(\n"
7682           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
7683           "      }\n"
7684           "    } :\n"
7685           "    function() {};",
7686           getGoogleStyle(FormatStyle::LK_JavaScript)));
7687 }
7688 
TEST_F(FormatTest,BreaksConditionalExpressionsAfterOperator)7689 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
7690   FormatStyle Style = getLLVMStyle();
7691   Style.BreakBeforeTernaryOperators = false;
7692   Style.ColumnLimit = 70;
7693   verifyFormat(
7694       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7695       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7696       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7697       Style);
7698   verifyFormat(
7699       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
7700       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7701       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7702       Style);
7703   verifyFormat(
7704       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7705       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7706       Style);
7707   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
7708                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7709                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7710                Style);
7711   verifyFormat(
7712       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
7713       "                                                      aaaaaaaaaaaaa);",
7714       Style);
7715   verifyFormat(
7716       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7717       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7718       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7719       "                   aaaaaaaaaaaaa);",
7720       Style);
7721   verifyFormat(
7722       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7723       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7724       "                   aaaaaaaaaaaaa);",
7725       Style);
7726   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7727                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7728                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7729                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7730                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7731                Style);
7732   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7733                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7734                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7735                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
7736                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7737                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7738                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7739                Style);
7740   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7741                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
7742                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7743                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
7744                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7745                Style);
7746   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7747                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7748                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7749                Style);
7750   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
7751                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7752                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
7753                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7754                Style);
7755   verifyFormat(
7756       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7757       "    aaaaaaaaaaaaaaa :\n"
7758       "    aaaaaaaaaaaaaaa;",
7759       Style);
7760   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
7761                "          aaaaaaaaa ?\n"
7762                "      b :\n"
7763                "      c);",
7764                Style);
7765   verifyFormat("unsigned Indent =\n"
7766                "    format(TheLine.First,\n"
7767                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
7768                "               IndentForLevel[TheLine.Level] :\n"
7769                "               TheLine * 2,\n"
7770                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
7771                Style);
7772   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
7773                "                  aaaaaaaaaaaaaaa :\n"
7774                "                  bbbbbbbbbbbbbbb ? //\n"
7775                "                      ccccccccccccccc :\n"
7776                "                      ddddddddddddddd;",
7777                Style);
7778   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
7779                "                  aaaaaaaaaaaaaaa :\n"
7780                "                  (bbbbbbbbbbbbbbb ? //\n"
7781                "                       ccccccccccccccc :\n"
7782                "                       ddddddddddddddd);",
7783                Style);
7784   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7785                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
7786                "            ccccccccccccccccccccccccccc;",
7787                Style);
7788   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
7789                "           aaaaa :\n"
7790                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
7791                Style);
7792 
7793   // Chained conditionals
7794   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7795                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7796                "                          3333333333333333;",
7797                Style);
7798   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7799                "       bbbbbbbbbb       ? 2222222222222222 :\n"
7800                "                          3333333333333333;",
7801                Style);
7802   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
7803                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7804                "                          3333333333333333;",
7805                Style);
7806   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7807                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
7808                "                          333333;",
7809                Style);
7810   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7811                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7812                "       cccccccccccccccc ? 3333333333333333 :\n"
7813                "                          4444444444444444;",
7814                Style);
7815   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
7816                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7817                "                          3333333333333333;",
7818                Style);
7819   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7820                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7821                "                          (aaa ? bbb : ccc);",
7822                Style);
7823   verifyFormat(
7824       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7825       "                                               cccccccccccccccccc) :\n"
7826       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7827       "                          3333333333333333;",
7828       Style);
7829   verifyFormat(
7830       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7831       "                                               cccccccccccccccccc) :\n"
7832       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7833       "                          3333333333333333;",
7834       Style);
7835   verifyFormat(
7836       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7837       "                                               dddddddddddddddddd) :\n"
7838       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7839       "                          3333333333333333;",
7840       Style);
7841   verifyFormat(
7842       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7843       "                                               dddddddddddddddddd) :\n"
7844       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7845       "                          3333333333333333;",
7846       Style);
7847   verifyFormat(
7848       "return aaaaaaaaa        ? 1111111111111111 :\n"
7849       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7850       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7851       "                                               dddddddddddddddddd)\n",
7852       Style);
7853   verifyFormat(
7854       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
7855       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7856       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7857       "                                               cccccccccccccccccc);",
7858       Style);
7859   verifyFormat(
7860       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7861       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
7862       "                                               eeeeeeeeeeeeeeeeee) :\n"
7863       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7864       "                          3333333333333333;",
7865       Style);
7866   verifyFormat(
7867       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7868       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
7869       "                                               eeeeeeeeeeeeeeeeee) :\n"
7870       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7871       "                          3333333333333333;",
7872       Style);
7873   verifyFormat(
7874       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
7875       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
7876       "                                               eeeeeeeeeeeeeeeeee) :\n"
7877       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7878       "                          3333333333333333;",
7879       Style);
7880   verifyFormat(
7881       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7882       "                                               cccccccccccccccccc :\n"
7883       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7884       "                          3333333333333333;",
7885       Style);
7886   verifyFormat(
7887       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7888       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
7889       "                                               eeeeeeeeeeeeeeeeee :\n"
7890       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7891       "                          3333333333333333;",
7892       Style);
7893   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
7894                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7895                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
7896                "                                 eeeeeeeeeeeeeeeeee) :\n"
7897                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7898                "                               3333333333333333;",
7899                Style);
7900   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
7901                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
7902                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
7903                "                                  eeeeeeeeeeeeeeeeee :\n"
7904                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
7905                "                               3333333333333333;",
7906                Style);
7907 }
7908 
TEST_F(FormatTest,DeclarationsOfMultipleVariables)7909 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
7910   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
7911                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
7912   verifyFormat("bool a = true, b = false;");
7913 
7914   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7915                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
7916                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
7917                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
7918   verifyFormat(
7919       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
7920       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
7921       "     d = e && f;");
7922   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
7923                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
7924   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
7925                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
7926   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
7927                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
7928 
7929   FormatStyle Style = getGoogleStyle();
7930   Style.PointerAlignment = FormatStyle::PAS_Left;
7931   Style.DerivePointerAlignment = false;
7932   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7933                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
7934                "    *b = bbbbbbbbbbbbbbbbbbb;",
7935                Style);
7936   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
7937                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
7938                Style);
7939   verifyFormat("vector<int*> a, b;", Style);
7940   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
7941 }
7942 
TEST_F(FormatTest,ConditionalExpressionsInBrackets)7943 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
7944   verifyFormat("arr[foo ? bar : baz];");
7945   verifyFormat("f()[foo ? bar : baz];");
7946   verifyFormat("(a + b)[foo ? bar : baz];");
7947   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
7948 }
7949 
TEST_F(FormatTest,AlignsStringLiterals)7950 TEST_F(FormatTest, AlignsStringLiterals) {
7951   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
7952                "                                      \"short literal\");");
7953   verifyFormat(
7954       "looooooooooooooooooooooooongFunction(\n"
7955       "    \"short literal\"\n"
7956       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
7957   verifyFormat("someFunction(\"Always break between multi-line\"\n"
7958                "             \" string literals\",\n"
7959                "             and, other, parameters);");
7960   EXPECT_EQ("fun + \"1243\" /* comment */\n"
7961             "      \"5678\";",
7962             format("fun + \"1243\" /* comment */\n"
7963                    "    \"5678\";",
7964                    getLLVMStyleWithColumns(28)));
7965   EXPECT_EQ(
7966       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
7967       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
7968       "         \"aaaaaaaaaaaaaaaa\";",
7969       format("aaaaaa ="
7970              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
7971              "aaaaaaaaaaaaaaaaaaaaa\" "
7972              "\"aaaaaaaaaaaaaaaa\";"));
7973   verifyFormat("a = a + \"a\"\n"
7974                "        \"a\"\n"
7975                "        \"a\";");
7976   verifyFormat("f(\"a\", \"b\"\n"
7977                "       \"c\");");
7978 
7979   verifyFormat(
7980       "#define LL_FORMAT \"ll\"\n"
7981       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
7982       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
7983 
7984   verifyFormat("#define A(X)          \\\n"
7985                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
7986                "  \"ccccc\"",
7987                getLLVMStyleWithColumns(23));
7988   verifyFormat("#define A \"def\"\n"
7989                "f(\"abc\" A \"ghi\"\n"
7990                "  \"jkl\");");
7991 
7992   verifyFormat("f(L\"a\"\n"
7993                "  L\"b\");");
7994   verifyFormat("#define A(X)            \\\n"
7995                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
7996                "  L\"ccccc\"",
7997                getLLVMStyleWithColumns(25));
7998 
7999   verifyFormat("f(@\"a\"\n"
8000                "  @\"b\");");
8001   verifyFormat("NSString s = @\"a\"\n"
8002                "             @\"b\"\n"
8003                "             @\"c\";");
8004   verifyFormat("NSString s = @\"a\"\n"
8005                "              \"b\"\n"
8006                "              \"c\";");
8007 }
8008 
TEST_F(FormatTest,ReturnTypeBreakingStyle)8009 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
8010   FormatStyle Style = getLLVMStyle();
8011   // No declarations or definitions should be moved to own line.
8012   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
8013   verifyFormat("class A {\n"
8014                "  int f() { return 1; }\n"
8015                "  int g();\n"
8016                "};\n"
8017                "int f() { return 1; }\n"
8018                "int g();\n",
8019                Style);
8020 
8021   // All declarations and definitions should have the return type moved to its
8022   // own line.
8023   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8024   Style.TypenameMacros = {"LIST"};
8025   verifyFormat("SomeType\n"
8026                "funcdecl(LIST(uint64_t));",
8027                Style);
8028   verifyFormat("class E {\n"
8029                "  int\n"
8030                "  f() {\n"
8031                "    return 1;\n"
8032                "  }\n"
8033                "  int\n"
8034                "  g();\n"
8035                "};\n"
8036                "int\n"
8037                "f() {\n"
8038                "  return 1;\n"
8039                "}\n"
8040                "int\n"
8041                "g();\n",
8042                Style);
8043 
8044   // Top-level definitions, and no kinds of declarations should have the
8045   // return type moved to its own line.
8046   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
8047   verifyFormat("class B {\n"
8048                "  int f() { return 1; }\n"
8049                "  int g();\n"
8050                "};\n"
8051                "int\n"
8052                "f() {\n"
8053                "  return 1;\n"
8054                "}\n"
8055                "int g();\n",
8056                Style);
8057 
8058   // Top-level definitions and declarations should have the return type moved
8059   // to its own line.
8060   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
8061   verifyFormat("class C {\n"
8062                "  int f() { return 1; }\n"
8063                "  int g();\n"
8064                "};\n"
8065                "int\n"
8066                "f() {\n"
8067                "  return 1;\n"
8068                "}\n"
8069                "int\n"
8070                "g();\n",
8071                Style);
8072 
8073   // All definitions should have the return type moved to its own line, but no
8074   // kinds of declarations.
8075   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
8076   verifyFormat("class D {\n"
8077                "  int\n"
8078                "  f() {\n"
8079                "    return 1;\n"
8080                "  }\n"
8081                "  int g();\n"
8082                "};\n"
8083                "int\n"
8084                "f() {\n"
8085                "  return 1;\n"
8086                "}\n"
8087                "int g();\n",
8088                Style);
8089   verifyFormat("const char *\n"
8090                "f(void) {\n" // Break here.
8091                "  return \"\";\n"
8092                "}\n"
8093                "const char *bar(void);\n", // No break here.
8094                Style);
8095   verifyFormat("template <class T>\n"
8096                "T *\n"
8097                "f(T &c) {\n" // Break here.
8098                "  return NULL;\n"
8099                "}\n"
8100                "template <class T> T *f(T &c);\n", // No break here.
8101                Style);
8102   verifyFormat("class C {\n"
8103                "  int\n"
8104                "  operator+() {\n"
8105                "    return 1;\n"
8106                "  }\n"
8107                "  int\n"
8108                "  operator()() {\n"
8109                "    return 1;\n"
8110                "  }\n"
8111                "};\n",
8112                Style);
8113   verifyFormat("void\n"
8114                "A::operator()() {}\n"
8115                "void\n"
8116                "A::operator>>() {}\n"
8117                "void\n"
8118                "A::operator+() {}\n"
8119                "void\n"
8120                "A::operator*() {}\n"
8121                "void\n"
8122                "A::operator->() {}\n"
8123                "void\n"
8124                "A::operator void *() {}\n"
8125                "void\n"
8126                "A::operator void &() {}\n"
8127                "void\n"
8128                "A::operator void &&() {}\n"
8129                "void\n"
8130                "A::operator char *() {}\n"
8131                "void\n"
8132                "A::operator[]() {}\n"
8133                "void\n"
8134                "A::operator!() {}\n"
8135                "void\n"
8136                "A::operator**() {}\n"
8137                "void\n"
8138                "A::operator<Foo> *() {}\n"
8139                "void\n"
8140                "A::operator<Foo> **() {}\n"
8141                "void\n"
8142                "A::operator<Foo> &() {}\n"
8143                "void\n"
8144                "A::operator void **() {}\n",
8145                Style);
8146   verifyFormat("constexpr auto\n"
8147                "operator()() const -> reference {}\n"
8148                "constexpr auto\n"
8149                "operator>>() const -> reference {}\n"
8150                "constexpr auto\n"
8151                "operator+() const -> reference {}\n"
8152                "constexpr auto\n"
8153                "operator*() const -> reference {}\n"
8154                "constexpr auto\n"
8155                "operator->() const -> reference {}\n"
8156                "constexpr auto\n"
8157                "operator++() const -> reference {}\n"
8158                "constexpr auto\n"
8159                "operator void *() const -> reference {}\n"
8160                "constexpr auto\n"
8161                "operator void **() const -> reference {}\n"
8162                "constexpr auto\n"
8163                "operator void *() const -> reference {}\n"
8164                "constexpr auto\n"
8165                "operator void &() const -> reference {}\n"
8166                "constexpr auto\n"
8167                "operator void &&() const -> reference {}\n"
8168                "constexpr auto\n"
8169                "operator char *() const -> reference {}\n"
8170                "constexpr auto\n"
8171                "operator!() const -> reference {}\n"
8172                "constexpr auto\n"
8173                "operator[]() const -> reference {}\n",
8174                Style);
8175   verifyFormat("void *operator new(std::size_t s);", // No break here.
8176                Style);
8177   verifyFormat("void *\n"
8178                "operator new(std::size_t s) {}",
8179                Style);
8180   verifyFormat("void *\n"
8181                "operator delete[](void *ptr) {}",
8182                Style);
8183   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
8184   verifyFormat("const char *\n"
8185                "f(void)\n" // Break here.
8186                "{\n"
8187                "  return \"\";\n"
8188                "}\n"
8189                "const char *bar(void);\n", // No break here.
8190                Style);
8191   verifyFormat("template <class T>\n"
8192                "T *\n"     // Problem here: no line break
8193                "f(T &c)\n" // Break here.
8194                "{\n"
8195                "  return NULL;\n"
8196                "}\n"
8197                "template <class T> T *f(T &c);\n", // No break here.
8198                Style);
8199   verifyFormat("int\n"
8200                "foo(A<bool> a)\n"
8201                "{\n"
8202                "  return a;\n"
8203                "}\n",
8204                Style);
8205   verifyFormat("int\n"
8206                "foo(A<8> a)\n"
8207                "{\n"
8208                "  return a;\n"
8209                "}\n",
8210                Style);
8211   verifyFormat("int\n"
8212                "foo(A<B<bool>, 8> a)\n"
8213                "{\n"
8214                "  return a;\n"
8215                "}\n",
8216                Style);
8217   verifyFormat("int\n"
8218                "foo(A<B<8>, bool> a)\n"
8219                "{\n"
8220                "  return a;\n"
8221                "}\n",
8222                Style);
8223   verifyFormat("int\n"
8224                "foo(A<B<bool>, bool> a)\n"
8225                "{\n"
8226                "  return a;\n"
8227                "}\n",
8228                Style);
8229   verifyFormat("int\n"
8230                "foo(A<B<8>, 8> a)\n"
8231                "{\n"
8232                "  return a;\n"
8233                "}\n",
8234                Style);
8235 
8236   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8237   Style.BraceWrapping.AfterFunction = true;
8238   verifyFormat("int f(i);\n" // No break here.
8239                "int\n"       // Break here.
8240                "f(i)\n"
8241                "{\n"
8242                "  return i + 1;\n"
8243                "}\n"
8244                "int\n" // Break here.
8245                "f(i)\n"
8246                "{\n"
8247                "  return i + 1;\n"
8248                "};",
8249                Style);
8250   verifyFormat("int f(a, b, c);\n" // No break here.
8251                "int\n"             // Break here.
8252                "f(a, b, c)\n"      // Break here.
8253                "short a, b;\n"
8254                "float c;\n"
8255                "{\n"
8256                "  return a + b < c;\n"
8257                "}\n"
8258                "int\n"        // Break here.
8259                "f(a, b, c)\n" // Break here.
8260                "short a, b;\n"
8261                "float c;\n"
8262                "{\n"
8263                "  return a + b < c;\n"
8264                "};",
8265                Style);
8266   verifyFormat("byte *\n" // Break here.
8267                "f(a)\n"   // Break here.
8268                "byte a[];\n"
8269                "{\n"
8270                "  return a;\n"
8271                "}",
8272                Style);
8273   verifyFormat("bool f(int a, int) override;\n"
8274                "Bar g(int a, Bar) final;\n"
8275                "Bar h(a, Bar) final;",
8276                Style);
8277   verifyFormat("int\n"
8278                "f(a)",
8279                Style);
8280   verifyFormat("bool\n"
8281                "f(size_t = 0, bool b = false)\n"
8282                "{\n"
8283                "  return !b;\n"
8284                "}",
8285                Style);
8286 
8287   // The return breaking style doesn't affect:
8288   // * function and object definitions with attribute-like macros
8289   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8290                "    ABSL_GUARDED_BY(mutex) = {};",
8291                getGoogleStyleWithColumns(40));
8292   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8293                "    ABSL_GUARDED_BY(mutex);  // comment",
8294                getGoogleStyleWithColumns(40));
8295   verifyFormat("Tttttttttttttttttttttttt ppppppppppppppp\n"
8296                "    ABSL_GUARDED_BY(mutex1)\n"
8297                "        ABSL_GUARDED_BY(mutex2);",
8298                getGoogleStyleWithColumns(40));
8299   verifyFormat("Tttttt f(int a, int b)\n"
8300                "    ABSL_GUARDED_BY(mutex1)\n"
8301                "        ABSL_GUARDED_BY(mutex2);",
8302                getGoogleStyleWithColumns(40));
8303   // * typedefs
8304   verifyFormat("typedef ATTR(X) char x;", getGoogleStyle());
8305 
8306   Style = getGNUStyle();
8307 
8308   // Test for comments at the end of function declarations.
8309   verifyFormat("void\n"
8310                "foo (int a, /*abc*/ int b) // def\n"
8311                "{\n"
8312                "}\n",
8313                Style);
8314 
8315   verifyFormat("void\n"
8316                "foo (int a, /* abc */ int b) /* def */\n"
8317                "{\n"
8318                "}\n",
8319                Style);
8320 
8321   // Definitions that should not break after return type
8322   verifyFormat("void foo (int a, int b); // def\n", Style);
8323   verifyFormat("void foo (int a, int b); /* def */\n", Style);
8324   verifyFormat("void foo (int a, int b);\n", Style);
8325 }
8326 
TEST_F(FormatTest,AlwaysBreakBeforeMultilineStrings)8327 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
8328   FormatStyle NoBreak = getLLVMStyle();
8329   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
8330   FormatStyle Break = getLLVMStyle();
8331   Break.AlwaysBreakBeforeMultilineStrings = true;
8332   verifyFormat("aaaa = \"bbbb\"\n"
8333                "       \"cccc\";",
8334                NoBreak);
8335   verifyFormat("aaaa =\n"
8336                "    \"bbbb\"\n"
8337                "    \"cccc\";",
8338                Break);
8339   verifyFormat("aaaa(\"bbbb\"\n"
8340                "     \"cccc\");",
8341                NoBreak);
8342   verifyFormat("aaaa(\n"
8343                "    \"bbbb\"\n"
8344                "    \"cccc\");",
8345                Break);
8346   verifyFormat("aaaa(qqq, \"bbbb\"\n"
8347                "          \"cccc\");",
8348                NoBreak);
8349   verifyFormat("aaaa(qqq,\n"
8350                "     \"bbbb\"\n"
8351                "     \"cccc\");",
8352                Break);
8353   verifyFormat("aaaa(qqq,\n"
8354                "     L\"bbbb\"\n"
8355                "     L\"cccc\");",
8356                Break);
8357   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
8358                "                      \"bbbb\"));",
8359                Break);
8360   verifyFormat("string s = someFunction(\n"
8361                "    \"abc\"\n"
8362                "    \"abc\");",
8363                Break);
8364 
8365   // As we break before unary operators, breaking right after them is bad.
8366   verifyFormat("string foo = abc ? \"x\"\n"
8367                "                   \"blah blah blah blah blah blah\"\n"
8368                "                 : \"y\";",
8369                Break);
8370 
8371   // Don't break if there is no column gain.
8372   verifyFormat("f(\"aaaa\"\n"
8373                "  \"bbbb\");",
8374                Break);
8375 
8376   // Treat literals with escaped newlines like multi-line string literals.
8377   EXPECT_EQ("x = \"a\\\n"
8378             "b\\\n"
8379             "c\";",
8380             format("x = \"a\\\n"
8381                    "b\\\n"
8382                    "c\";",
8383                    NoBreak));
8384   EXPECT_EQ("xxxx =\n"
8385             "    \"a\\\n"
8386             "b\\\n"
8387             "c\";",
8388             format("xxxx = \"a\\\n"
8389                    "b\\\n"
8390                    "c\";",
8391                    Break));
8392 
8393   EXPECT_EQ("NSString *const kString =\n"
8394             "    @\"aaaa\"\n"
8395             "    @\"bbbb\";",
8396             format("NSString *const kString = @\"aaaa\"\n"
8397                    "@\"bbbb\";",
8398                    Break));
8399 
8400   Break.ColumnLimit = 0;
8401   verifyFormat("const char *hello = \"hello llvm\";", Break);
8402 }
8403 
TEST_F(FormatTest,AlignsPipes)8404 TEST_F(FormatTest, AlignsPipes) {
8405   verifyFormat(
8406       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8407       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8408       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8409   verifyFormat(
8410       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
8411       "                     << aaaaaaaaaaaaaaaaaaaa;");
8412   verifyFormat(
8413       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8414       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8415   verifyFormat(
8416       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
8417       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8418   verifyFormat(
8419       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
8420       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
8421       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
8422   verifyFormat(
8423       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8424       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8425       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8426   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8427                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8428                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8429                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8430   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
8431                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
8432   verifyFormat(
8433       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8434       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8435   verifyFormat(
8436       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
8437       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
8438 
8439   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
8440                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
8441   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8442                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8443                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
8444                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
8445   verifyFormat("LOG_IF(aaa == //\n"
8446                "       bbb)\n"
8447                "    << a << b;");
8448 
8449   // But sometimes, breaking before the first "<<" is desirable.
8450   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8451                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
8452   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
8453                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8454                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8455   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
8456                "    << BEF << IsTemplate << Description << E->getType();");
8457   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8458                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8459                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8460   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
8461                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8462                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8463                "    << aaa;");
8464 
8465   verifyFormat(
8466       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8467       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8468 
8469   // Incomplete string literal.
8470   EXPECT_EQ("llvm::errs() << \"\n"
8471             "             << a;",
8472             format("llvm::errs() << \"\n<<a;"));
8473 
8474   verifyFormat("void f() {\n"
8475                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
8476                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
8477                "}");
8478 
8479   // Handle 'endl'.
8480   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
8481                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8482   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
8483 
8484   // Handle '\n'.
8485   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
8486                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8487   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
8488                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
8489   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
8490                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
8491   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
8492 }
8493 
TEST_F(FormatTest,KeepStringLabelValuePairsOnALine)8494 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
8495   verifyFormat("return out << \"somepacket = {\\n\"\n"
8496                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
8497                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
8498                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
8499                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
8500                "           << \"}\";");
8501 
8502   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8503                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
8504                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
8505   verifyFormat(
8506       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
8507       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
8508       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
8509       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
8510       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
8511   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
8512                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8513   verifyFormat(
8514       "void f() {\n"
8515       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
8516       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
8517       "}");
8518 
8519   // Breaking before the first "<<" is generally not desirable.
8520   verifyFormat(
8521       "llvm::errs()\n"
8522       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8523       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8524       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8525       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8526       getLLVMStyleWithColumns(70));
8527   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8528                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8529                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8530                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8531                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
8532                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
8533                getLLVMStyleWithColumns(70));
8534 
8535   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8536                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
8537                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
8538   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8539                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
8540                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
8541   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
8542                "           (aaaa + aaaa);",
8543                getLLVMStyleWithColumns(40));
8544   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
8545                "                  (aaaaaaa + aaaaa));",
8546                getLLVMStyleWithColumns(40));
8547   verifyFormat(
8548       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
8549       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
8550       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
8551 }
8552 
TEST_F(FormatTest,UnderstandsEquals)8553 TEST_F(FormatTest, UnderstandsEquals) {
8554   verifyFormat(
8555       "aaaaaaaaaaaaaaaaa =\n"
8556       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8557   verifyFormat(
8558       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8559       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8560   verifyFormat(
8561       "if (a) {\n"
8562       "  f();\n"
8563       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8564       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
8565       "}");
8566 
8567   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8568                "        100000000 + 10000000) {\n}");
8569 }
8570 
TEST_F(FormatTest,WrapsAtFunctionCallsIfNecessary)8571 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
8572   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8573                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
8574 
8575   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
8576                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
8577 
8578   verifyFormat(
8579       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
8580       "                                                          Parameter2);");
8581 
8582   verifyFormat(
8583       "ShortObject->shortFunction(\n"
8584       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
8585       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
8586 
8587   verifyFormat("loooooooooooooongFunction(\n"
8588                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
8589 
8590   verifyFormat(
8591       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
8592       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
8593 
8594   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8595                "    .WillRepeatedly(Return(SomeValue));");
8596   verifyFormat("void f() {\n"
8597                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
8598                "      .Times(2)\n"
8599                "      .WillRepeatedly(Return(SomeValue));\n"
8600                "}");
8601   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
8602                "    ccccccccccccccccccccccc);");
8603   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8604                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8605                "          .aaaaa(aaaaa),\n"
8606                "      aaaaaaaaaaaaaaaaaaaaa);");
8607   verifyFormat("void f() {\n"
8608                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8609                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
8610                "}");
8611   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8612                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8613                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8614                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8615                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
8616   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8617                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8618                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8619                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
8620                "}");
8621 
8622   // Here, it is not necessary to wrap at "." or "->".
8623   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
8624                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
8625   verifyFormat(
8626       "aaaaaaaaaaa->aaaaaaaaa(\n"
8627       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8628       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
8629 
8630   verifyFormat(
8631       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8632       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
8633   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
8634                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8635   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
8636                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
8637 
8638   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8639                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8640                "    .a();");
8641 
8642   FormatStyle NoBinPacking = getLLVMStyle();
8643   NoBinPacking.BinPackParameters = false;
8644   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8645                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
8646                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
8647                "                         aaaaaaaaaaaaaaaaaaa,\n"
8648                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
8649                NoBinPacking);
8650 
8651   // If there is a subsequent call, change to hanging indentation.
8652   verifyFormat(
8653       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8654       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
8655       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8656   verifyFormat(
8657       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8658       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
8659   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8660                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8661                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8662   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8663                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
8664                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
8665 }
8666 
TEST_F(FormatTest,WrapsTemplateDeclarations)8667 TEST_F(FormatTest, WrapsTemplateDeclarations) {
8668   verifyFormat("template <typename T>\n"
8669                "virtual void loooooooooooongFunction(int Param1, int Param2);");
8670   verifyFormat("template <typename T>\n"
8671                "// T should be one of {A, B}.\n"
8672                "virtual void loooooooooooongFunction(int Param1, int Param2);");
8673   verifyFormat(
8674       "template <typename T>\n"
8675       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
8676   verifyFormat("template <typename T>\n"
8677                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
8678                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
8679   verifyFormat(
8680       "template <typename T>\n"
8681       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
8682       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
8683   verifyFormat(
8684       "template <typename T>\n"
8685       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
8686       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
8687       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8688   verifyFormat("template <typename T>\n"
8689                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8690                "    int aaaaaaaaaaaaaaaaaaaaaa);");
8691   verifyFormat(
8692       "template <typename T1, typename T2 = char, typename T3 = char,\n"
8693       "          typename T4 = char>\n"
8694       "void f();");
8695   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
8696                "          template <typename> class cccccccccccccccccccccc,\n"
8697                "          typename ddddddddddddd>\n"
8698                "class C {};");
8699   verifyFormat(
8700       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
8701       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8702 
8703   verifyFormat("void f() {\n"
8704                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
8705                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
8706                "}");
8707 
8708   verifyFormat("template <typename T> class C {};");
8709   verifyFormat("template <typename T> void f();");
8710   verifyFormat("template <typename T> void f() {}");
8711   verifyFormat(
8712       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
8713       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8714       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
8715       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
8716       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8717       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
8718       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
8719       getLLVMStyleWithColumns(72));
8720   EXPECT_EQ("static_cast<A< //\n"
8721             "    B> *>(\n"
8722             "\n"
8723             ");",
8724             format("static_cast<A<//\n"
8725                    "    B>*>(\n"
8726                    "\n"
8727                    "    );"));
8728   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8729                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
8730 
8731   FormatStyle AlwaysBreak = getLLVMStyle();
8732   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
8733   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
8734   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
8735   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
8736   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8737                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
8738                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
8739   verifyFormat("template <template <typename> class Fooooooo,\n"
8740                "          template <typename> class Baaaaaaar>\n"
8741                "struct C {};",
8742                AlwaysBreak);
8743   verifyFormat("template <typename T> // T can be A, B or C.\n"
8744                "struct C {};",
8745                AlwaysBreak);
8746   verifyFormat("template <enum E> class A {\n"
8747                "public:\n"
8748                "  E *f();\n"
8749                "};");
8750 
8751   FormatStyle NeverBreak = getLLVMStyle();
8752   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
8753   verifyFormat("template <typename T> class C {};", NeverBreak);
8754   verifyFormat("template <typename T> void f();", NeverBreak);
8755   verifyFormat("template <typename T> void f() {}", NeverBreak);
8756   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
8757                "bbbbbbbbbbbbbbbbbbbb) {}",
8758                NeverBreak);
8759   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8760                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
8761                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
8762                NeverBreak);
8763   verifyFormat("template <template <typename> class Fooooooo,\n"
8764                "          template <typename> class Baaaaaaar>\n"
8765                "struct C {};",
8766                NeverBreak);
8767   verifyFormat("template <typename T> // T can be A, B or C.\n"
8768                "struct C {};",
8769                NeverBreak);
8770   verifyFormat("template <enum E> class A {\n"
8771                "public:\n"
8772                "  E *f();\n"
8773                "};",
8774                NeverBreak);
8775   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
8776   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
8777                "bbbbbbbbbbbbbbbbbbbb) {}",
8778                NeverBreak);
8779 }
8780 
TEST_F(FormatTest,WrapsTemplateDeclarationsWithComments)8781 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
8782   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
8783   Style.ColumnLimit = 60;
8784   EXPECT_EQ("// Baseline - no comments.\n"
8785             "template <\n"
8786             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
8787             "void f() {}",
8788             format("// Baseline - no comments.\n"
8789                    "template <\n"
8790                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
8791                    "void f() {}",
8792                    Style));
8793 
8794   EXPECT_EQ("template <\n"
8795             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
8796             "void f() {}",
8797             format("template <\n"
8798                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
8799                    "void f() {}",
8800                    Style));
8801 
8802   EXPECT_EQ(
8803       "template <\n"
8804       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
8805       "void f() {}",
8806       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
8807              "void f() {}",
8808              Style));
8809 
8810   EXPECT_EQ(
8811       "template <\n"
8812       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
8813       "                                               // multiline\n"
8814       "void f() {}",
8815       format("template <\n"
8816              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
8817              "                                              // multiline\n"
8818              "void f() {}",
8819              Style));
8820 
8821   EXPECT_EQ(
8822       "template <typename aaaaaaaaaa<\n"
8823       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
8824       "void f() {}",
8825       format(
8826           "template <\n"
8827           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
8828           "void f() {}",
8829           Style));
8830 }
8831 
TEST_F(FormatTest,WrapsTemplateParameters)8832 TEST_F(FormatTest, WrapsTemplateParameters) {
8833   FormatStyle Style = getLLVMStyle();
8834   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8835   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
8836   verifyFormat(
8837       "template <typename... a> struct q {};\n"
8838       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
8839       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
8840       "    y;",
8841       Style);
8842   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
8843   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
8844   verifyFormat(
8845       "template <typename... a> struct r {};\n"
8846       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
8847       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
8848       "    y;",
8849       Style);
8850   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8851   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
8852   verifyFormat("template <typename... a> struct s {};\n"
8853                "extern s<\n"
8854                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8855                "aaaaaaaaaaaaaaaaaaaaaa,\n"
8856                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8857                "aaaaaaaaaaaaaaaaaaaaaa>\n"
8858                "    y;",
8859                Style);
8860   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8861   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
8862   verifyFormat("template <typename... a> struct t {};\n"
8863                "extern t<\n"
8864                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8865                "aaaaaaaaaaaaaaaaaaaaaa,\n"
8866                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
8867                "aaaaaaaaaaaaaaaaaaaaaa>\n"
8868                "    y;",
8869                Style);
8870 }
8871 
TEST_F(FormatTest,WrapsAtNestedNameSpecifiers)8872 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
8873   verifyFormat(
8874       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8875       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8876   verifyFormat(
8877       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8878       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8879       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
8880 
8881   // FIXME: Should we have the extra indent after the second break?
8882   verifyFormat(
8883       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8884       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8885       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8886 
8887   verifyFormat(
8888       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
8889       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
8890 
8891   // Breaking at nested name specifiers is generally not desirable.
8892   verifyFormat(
8893       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8894       "    aaaaaaaaaaaaaaaaaaaaaaa);");
8895 
8896   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
8897                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8898                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8899                "                   aaaaaaaaaaaaaaaaaaaaa);",
8900                getLLVMStyleWithColumns(74));
8901 
8902   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
8903                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8904                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
8905 }
8906 
TEST_F(FormatTest,UnderstandsTemplateParameters)8907 TEST_F(FormatTest, UnderstandsTemplateParameters) {
8908   verifyFormat("A<int> a;");
8909   verifyFormat("A<A<A<int>>> a;");
8910   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
8911   verifyFormat("bool x = a < 1 || 2 > a;");
8912   verifyFormat("bool x = 5 < f<int>();");
8913   verifyFormat("bool x = f<int>() > 5;");
8914   verifyFormat("bool x = 5 < a<int>::x;");
8915   verifyFormat("bool x = a < 4 ? a > 2 : false;");
8916   verifyFormat("bool x = f() ? a < 2 : a > 2;");
8917 
8918   verifyGoogleFormat("A<A<int>> a;");
8919   verifyGoogleFormat("A<A<A<int>>> a;");
8920   verifyGoogleFormat("A<A<A<A<int>>>> a;");
8921   verifyGoogleFormat("A<A<int> > a;");
8922   verifyGoogleFormat("A<A<A<int> > > a;");
8923   verifyGoogleFormat("A<A<A<A<int> > > > a;");
8924   verifyGoogleFormat("A<::A<int>> a;");
8925   verifyGoogleFormat("A<::A> a;");
8926   verifyGoogleFormat("A< ::A> a;");
8927   verifyGoogleFormat("A< ::A<int> > a;");
8928   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
8929   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
8930   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
8931   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
8932   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
8933             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
8934 
8935   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
8936 
8937   // template closer followed by a token that starts with > or =
8938   verifyFormat("bool b = a<1> > 1;");
8939   verifyFormat("bool b = a<1> >= 1;");
8940   verifyFormat("int i = a<1> >> 1;");
8941   FormatStyle Style = getLLVMStyle();
8942   Style.SpaceBeforeAssignmentOperators = false;
8943   verifyFormat("bool b= a<1> == 1;", Style);
8944   verifyFormat("a<int> = 1;", Style);
8945   verifyFormat("a<int> >>= 1;", Style);
8946 
8947   verifyFormat("test < a | b >> c;");
8948   verifyFormat("test<test<a | b>> c;");
8949   verifyFormat("test >> a >> b;");
8950   verifyFormat("test << a >> b;");
8951 
8952   verifyFormat("f<int>();");
8953   verifyFormat("template <typename T> void f() {}");
8954   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
8955   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
8956                "sizeof(char)>::type>;");
8957   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
8958   verifyFormat("f(a.operator()<A>());");
8959   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8960                "      .template operator()<A>());",
8961                getLLVMStyleWithColumns(35));
8962 
8963   // Not template parameters.
8964   verifyFormat("return a < b && c > d;");
8965   verifyFormat("void f() {\n"
8966                "  while (a < b && c > d) {\n"
8967                "  }\n"
8968                "}");
8969   verifyFormat("template <typename... Types>\n"
8970                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
8971 
8972   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8973                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
8974                getLLVMStyleWithColumns(60));
8975   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
8976   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
8977   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
8978   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
8979 }
8980 
TEST_F(FormatTest,UnderstandsShiftOperators)8981 TEST_F(FormatTest, UnderstandsShiftOperators) {
8982   verifyFormat("if (i < x >> 1)");
8983   verifyFormat("while (i < x >> 1)");
8984   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
8985   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
8986   verifyFormat(
8987       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
8988   verifyFormat("Foo.call<Bar<Function>>()");
8989   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
8990   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
8991                "++i, v = v >> 1)");
8992   verifyFormat("if (w<u<v<x>>, 1>::t)");
8993 }
8994 
TEST_F(FormatTest,BitshiftOperatorWidth)8995 TEST_F(FormatTest, BitshiftOperatorWidth) {
8996   EXPECT_EQ("int a = 1 << 2; /* foo\n"
8997             "                   bar */",
8998             format("int    a=1<<2;  /* foo\n"
8999                    "                   bar */"));
9000 
9001   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
9002             "                     bar */",
9003             format("int  b  =256>>1 ;  /* foo\n"
9004                    "                      bar */"));
9005 }
9006 
TEST_F(FormatTest,UnderstandsBinaryOperators)9007 TEST_F(FormatTest, UnderstandsBinaryOperators) {
9008   verifyFormat("COMPARE(a, ==, b);");
9009   verifyFormat("auto s = sizeof...(Ts) - 1;");
9010 }
9011 
TEST_F(FormatTest,UnderstandsPointersToMembers)9012 TEST_F(FormatTest, UnderstandsPointersToMembers) {
9013   verifyFormat("int A::*x;");
9014   verifyFormat("int (S::*func)(void *);");
9015   verifyFormat("void f() { int (S::*func)(void *); }");
9016   verifyFormat("typedef bool *(Class::*Member)() const;");
9017   verifyFormat("void f() {\n"
9018                "  (a->*f)();\n"
9019                "  a->*x;\n"
9020                "  (a.*f)();\n"
9021                "  ((*a).*f)();\n"
9022                "  a.*x;\n"
9023                "}");
9024   verifyFormat("void f() {\n"
9025                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
9026                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
9027                "}");
9028   verifyFormat(
9029       "(aaaaaaaaaa->*bbbbbbb)(\n"
9030       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
9031   FormatStyle Style = getLLVMStyle();
9032   Style.PointerAlignment = FormatStyle::PAS_Left;
9033   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
9034 }
9035 
TEST_F(FormatTest,UnderstandsUnaryOperators)9036 TEST_F(FormatTest, UnderstandsUnaryOperators) {
9037   verifyFormat("int a = -2;");
9038   verifyFormat("f(-1, -2, -3);");
9039   verifyFormat("a[-1] = 5;");
9040   verifyFormat("int a = 5 + -2;");
9041   verifyFormat("if (i == -1) {\n}");
9042   verifyFormat("if (i != -1) {\n}");
9043   verifyFormat("if (i > -1) {\n}");
9044   verifyFormat("if (i < -1) {\n}");
9045   verifyFormat("++(a->f());");
9046   verifyFormat("--(a->f());");
9047   verifyFormat("(a->f())++;");
9048   verifyFormat("a[42]++;");
9049   verifyFormat("if (!(a->f())) {\n}");
9050   verifyFormat("if (!+i) {\n}");
9051   verifyFormat("~&a;");
9052 
9053   verifyFormat("a-- > b;");
9054   verifyFormat("b ? -a : c;");
9055   verifyFormat("n * sizeof char16;");
9056   verifyFormat("n * alignof char16;", getGoogleStyle());
9057   verifyFormat("sizeof(char);");
9058   verifyFormat("alignof(char);", getGoogleStyle());
9059 
9060   verifyFormat("return -1;");
9061   verifyFormat("throw -1;");
9062   verifyFormat("switch (a) {\n"
9063                "case -1:\n"
9064                "  break;\n"
9065                "}");
9066   verifyFormat("#define X -1");
9067   verifyFormat("#define X -kConstant");
9068 
9069   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
9070   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
9071 
9072   verifyFormat("int a = /* confusing comment */ -1;");
9073   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
9074   verifyFormat("int a = i /* confusing comment */++;");
9075 
9076   verifyFormat("co_yield -1;");
9077   verifyFormat("co_return -1;");
9078 
9079   // Check that * is not treated as a binary operator when we set
9080   // PointerAlignment as PAS_Left after a keyword and not a declaration.
9081   FormatStyle PASLeftStyle = getLLVMStyle();
9082   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
9083   verifyFormat("co_return *a;", PASLeftStyle);
9084   verifyFormat("co_await *a;", PASLeftStyle);
9085   verifyFormat("co_yield *a", PASLeftStyle);
9086   verifyFormat("return *a;", PASLeftStyle);
9087 }
9088 
TEST_F(FormatTest,DoesNotIndentRelativeToUnaryOperators)9089 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
9090   verifyFormat("if (!aaaaaaaaaa( // break\n"
9091                "        aaaaa)) {\n"
9092                "}");
9093   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
9094                "    aaaaa));");
9095   verifyFormat("*aaa = aaaaaaa( // break\n"
9096                "    bbbbbb);");
9097 }
9098 
TEST_F(FormatTest,UnderstandsOverloadedOperators)9099 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
9100   verifyFormat("bool operator<();");
9101   verifyFormat("bool operator>();");
9102   verifyFormat("bool operator=();");
9103   verifyFormat("bool operator==();");
9104   verifyFormat("bool operator!=();");
9105   verifyFormat("int operator+();");
9106   verifyFormat("int operator++();");
9107   verifyFormat("int operator++(int) volatile noexcept;");
9108   verifyFormat("bool operator,();");
9109   verifyFormat("bool operator();");
9110   verifyFormat("bool operator()();");
9111   verifyFormat("bool operator[]();");
9112   verifyFormat("operator bool();");
9113   verifyFormat("operator int();");
9114   verifyFormat("operator void *();");
9115   verifyFormat("operator SomeType<int>();");
9116   verifyFormat("operator SomeType<int, int>();");
9117   verifyFormat("operator SomeType<SomeType<int>>();");
9118   verifyFormat("void *operator new(std::size_t size);");
9119   verifyFormat("void *operator new[](std::size_t size);");
9120   verifyFormat("void operator delete(void *ptr);");
9121   verifyFormat("void operator delete[](void *ptr);");
9122   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
9123                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
9124   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
9125                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
9126 
9127   verifyFormat(
9128       "ostream &operator<<(ostream &OutputStream,\n"
9129       "                    SomeReallyLongType WithSomeReallyLongValue);");
9130   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
9131                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
9132                "  return left.group < right.group;\n"
9133                "}");
9134   verifyFormat("SomeType &operator=(const SomeType &S);");
9135   verifyFormat("f.template operator()<int>();");
9136 
9137   verifyGoogleFormat("operator void*();");
9138   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
9139   verifyGoogleFormat("operator ::A();");
9140 
9141   verifyFormat("using A::operator+;");
9142   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
9143                "int i;");
9144 
9145   // Calling an operator as a member function.
9146   verifyFormat("void f() { a.operator*(); }");
9147   verifyFormat("void f() { a.operator*(b & b); }");
9148   verifyFormat("void f() { a->operator&(a * b); }");
9149   verifyFormat("void f() { NS::a.operator+(*b * *b); }");
9150   // TODO: Calling an operator as a non-member function is hard to distinguish.
9151   // https://llvm.org/PR50629
9152   // verifyFormat("void f() { operator*(a & a); }");
9153   // verifyFormat("void f() { operator&(a, b * b); }");
9154 }
9155 
TEST_F(FormatTest,UnderstandsFunctionRefQualification)9156 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
9157   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
9158   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
9159   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
9160   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
9161   verifyFormat("Deleted &operator=(const Deleted &) &;");
9162   verifyFormat("Deleted &operator=(const Deleted &) &&;");
9163   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
9164   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
9165   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
9166   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
9167   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
9168   verifyFormat("void Fn(T const &) const &;");
9169   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
9170   verifyFormat("template <typename T>\n"
9171                "void F(T) && = delete;",
9172                getGoogleStyle());
9173 
9174   FormatStyle AlignLeft = getLLVMStyle();
9175   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
9176   verifyFormat("void A::b() && {}", AlignLeft);
9177   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
9178   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
9179                AlignLeft);
9180   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
9181   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
9182   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
9183   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
9184   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
9185   verifyFormat("auto Function(T) & -> void;", AlignLeft);
9186   verifyFormat("void Fn(T const&) const&;", AlignLeft);
9187   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
9188 
9189   FormatStyle Spaces = getLLVMStyle();
9190   Spaces.SpacesInCStyleCastParentheses = true;
9191   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
9192   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
9193   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
9194   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
9195 
9196   Spaces.SpacesInCStyleCastParentheses = false;
9197   Spaces.SpacesInParentheses = true;
9198   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
9199   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
9200                Spaces);
9201   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
9202   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
9203 
9204   FormatStyle BreakTemplate = getLLVMStyle();
9205   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
9206 
9207   verifyFormat("struct f {\n"
9208                "  template <class T>\n"
9209                "  int &foo(const std::string &str) &noexcept {}\n"
9210                "};",
9211                BreakTemplate);
9212 
9213   verifyFormat("struct f {\n"
9214                "  template <class T>\n"
9215                "  int &foo(const std::string &str) &&noexcept {}\n"
9216                "};",
9217                BreakTemplate);
9218 
9219   verifyFormat("struct f {\n"
9220                "  template <class T>\n"
9221                "  int &foo(const std::string &str) const &noexcept {}\n"
9222                "};",
9223                BreakTemplate);
9224 
9225   verifyFormat("struct f {\n"
9226                "  template <class T>\n"
9227                "  int &foo(const std::string &str) const &noexcept {}\n"
9228                "};",
9229                BreakTemplate);
9230 
9231   verifyFormat("struct f {\n"
9232                "  template <class T>\n"
9233                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
9234                "};",
9235                BreakTemplate);
9236 
9237   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
9238   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
9239       FormatStyle::BTDS_Yes;
9240   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
9241 
9242   verifyFormat("struct f {\n"
9243                "  template <class T>\n"
9244                "  int& foo(const std::string& str) & noexcept {}\n"
9245                "};",
9246                AlignLeftBreakTemplate);
9247 
9248   verifyFormat("struct f {\n"
9249                "  template <class T>\n"
9250                "  int& foo(const std::string& str) && noexcept {}\n"
9251                "};",
9252                AlignLeftBreakTemplate);
9253 
9254   verifyFormat("struct f {\n"
9255                "  template <class T>\n"
9256                "  int& foo(const std::string& str) const& noexcept {}\n"
9257                "};",
9258                AlignLeftBreakTemplate);
9259 
9260   verifyFormat("struct f {\n"
9261                "  template <class T>\n"
9262                "  int& foo(const std::string& str) const&& noexcept {}\n"
9263                "};",
9264                AlignLeftBreakTemplate);
9265 
9266   verifyFormat("struct f {\n"
9267                "  template <class T>\n"
9268                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
9269                "};",
9270                AlignLeftBreakTemplate);
9271 
9272   // The `&` in `Type&` should not be confused with a trailing `&` of
9273   // DEPRECATED(reason) member function.
9274   verifyFormat("struct f {\n"
9275                "  template <class T>\n"
9276                "  DEPRECATED(reason)\n"
9277                "  Type &foo(arguments) {}\n"
9278                "};",
9279                BreakTemplate);
9280 
9281   verifyFormat("struct f {\n"
9282                "  template <class T>\n"
9283                "  DEPRECATED(reason)\n"
9284                "  Type& foo(arguments) {}\n"
9285                "};",
9286                AlignLeftBreakTemplate);
9287 
9288   verifyFormat("void (*foopt)(int) = &func;");
9289 }
9290 
TEST_F(FormatTest,UnderstandsNewAndDelete)9291 TEST_F(FormatTest, UnderstandsNewAndDelete) {
9292   verifyFormat("void f() {\n"
9293                "  A *a = new A;\n"
9294                "  A *a = new (placement) A;\n"
9295                "  delete a;\n"
9296                "  delete (A *)a;\n"
9297                "}");
9298   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9299                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9300   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9301                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
9302                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
9303   verifyFormat("delete[] h->p;");
9304 }
9305 
TEST_F(FormatTest,UnderstandsUsesOfStarAndAmp)9306 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
9307   verifyFormat("int *f(int *a) {}");
9308   verifyFormat("int main(int argc, char **argv) {}");
9309   verifyFormat("Test::Test(int b) : a(b * b) {}");
9310   verifyIndependentOfContext("f(a, *a);");
9311   verifyFormat("void g() { f(*a); }");
9312   verifyIndependentOfContext("int a = b * 10;");
9313   verifyIndependentOfContext("int a = 10 * b;");
9314   verifyIndependentOfContext("int a = b * c;");
9315   verifyIndependentOfContext("int a += b * c;");
9316   verifyIndependentOfContext("int a -= b * c;");
9317   verifyIndependentOfContext("int a *= b * c;");
9318   verifyIndependentOfContext("int a /= b * c;");
9319   verifyIndependentOfContext("int a = *b;");
9320   verifyIndependentOfContext("int a = *b * c;");
9321   verifyIndependentOfContext("int a = b * *c;");
9322   verifyIndependentOfContext("int a = b * (10);");
9323   verifyIndependentOfContext("S << b * (10);");
9324   verifyIndependentOfContext("return 10 * b;");
9325   verifyIndependentOfContext("return *b * *c;");
9326   verifyIndependentOfContext("return a & ~b;");
9327   verifyIndependentOfContext("f(b ? *c : *d);");
9328   verifyIndependentOfContext("int a = b ? *c : *d;");
9329   verifyIndependentOfContext("*b = a;");
9330   verifyIndependentOfContext("a * ~b;");
9331   verifyIndependentOfContext("a * !b;");
9332   verifyIndependentOfContext("a * +b;");
9333   verifyIndependentOfContext("a * -b;");
9334   verifyIndependentOfContext("a * ++b;");
9335   verifyIndependentOfContext("a * --b;");
9336   verifyIndependentOfContext("a[4] * b;");
9337   verifyIndependentOfContext("a[a * a] = 1;");
9338   verifyIndependentOfContext("f() * b;");
9339   verifyIndependentOfContext("a * [self dostuff];");
9340   verifyIndependentOfContext("int x = a * (a + b);");
9341   verifyIndependentOfContext("(a *)(a + b);");
9342   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
9343   verifyIndependentOfContext("int *pa = (int *)&a;");
9344   verifyIndependentOfContext("return sizeof(int **);");
9345   verifyIndependentOfContext("return sizeof(int ******);");
9346   verifyIndependentOfContext("return (int **&)a;");
9347   verifyIndependentOfContext("f((*PointerToArray)[10]);");
9348   verifyFormat("void f(Type (*parameter)[10]) {}");
9349   verifyFormat("void f(Type (&parameter)[10]) {}");
9350   verifyGoogleFormat("return sizeof(int**);");
9351   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
9352   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
9353   verifyFormat("auto a = [](int **&, int ***) {};");
9354   verifyFormat("auto PointerBinding = [](const char *S) {};");
9355   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
9356   verifyFormat("[](const decltype(*a) &value) {}");
9357   verifyFormat("[](const typeof(*a) &value) {}");
9358   verifyFormat("[](const _Atomic(a *) &value) {}");
9359   verifyFormat("[](const __underlying_type(a) &value) {}");
9360   verifyFormat("decltype(a * b) F();");
9361   verifyFormat("typeof(a * b) F();");
9362   verifyFormat("#define MACRO() [](A *a) { return 1; }");
9363   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
9364   verifyIndependentOfContext("typedef void (*f)(int *a);");
9365   verifyIndependentOfContext("int i{a * b};");
9366   verifyIndependentOfContext("aaa && aaa->f();");
9367   verifyIndependentOfContext("int x = ~*p;");
9368   verifyFormat("Constructor() : a(a), area(width * height) {}");
9369   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
9370   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
9371   verifyFormat("void f() { f(a, c * d); }");
9372   verifyFormat("void f() { f(new a(), c * d); }");
9373   verifyFormat("void f(const MyOverride &override);");
9374   verifyFormat("void f(const MyFinal &final);");
9375   verifyIndependentOfContext("bool a = f() && override.f();");
9376   verifyIndependentOfContext("bool a = f() && final.f();");
9377 
9378   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
9379 
9380   verifyIndependentOfContext("A<int *> a;");
9381   verifyIndependentOfContext("A<int **> a;");
9382   verifyIndependentOfContext("A<int *, int *> a;");
9383   verifyIndependentOfContext("A<int *[]> a;");
9384   verifyIndependentOfContext(
9385       "const char *const p = reinterpret_cast<const char *const>(q);");
9386   verifyIndependentOfContext("A<int **, int **> a;");
9387   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
9388   verifyFormat("for (char **a = b; *a; ++a) {\n}");
9389   verifyFormat("for (; a && b;) {\n}");
9390   verifyFormat("bool foo = true && [] { return false; }();");
9391 
9392   verifyFormat(
9393       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
9394       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9395 
9396   verifyGoogleFormat("int const* a = &b;");
9397   verifyGoogleFormat("**outparam = 1;");
9398   verifyGoogleFormat("*outparam = a * b;");
9399   verifyGoogleFormat("int main(int argc, char** argv) {}");
9400   verifyGoogleFormat("A<int*> a;");
9401   verifyGoogleFormat("A<int**> a;");
9402   verifyGoogleFormat("A<int*, int*> a;");
9403   verifyGoogleFormat("A<int**, int**> a;");
9404   verifyGoogleFormat("f(b ? *c : *d);");
9405   verifyGoogleFormat("int a = b ? *c : *d;");
9406   verifyGoogleFormat("Type* t = **x;");
9407   verifyGoogleFormat("Type* t = *++*x;");
9408   verifyGoogleFormat("*++*x;");
9409   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
9410   verifyGoogleFormat("Type* t = x++ * y;");
9411   verifyGoogleFormat(
9412       "const char* const p = reinterpret_cast<const char* const>(q);");
9413   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
9414   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
9415   verifyGoogleFormat("template <typename T>\n"
9416                      "void f(int i = 0, SomeType** temps = NULL);");
9417 
9418   FormatStyle Left = getLLVMStyle();
9419   Left.PointerAlignment = FormatStyle::PAS_Left;
9420   verifyFormat("x = *a(x) = *a(y);", Left);
9421   verifyFormat("for (;; *a = b) {\n}", Left);
9422   verifyFormat("return *this += 1;", Left);
9423   verifyFormat("throw *x;", Left);
9424   verifyFormat("delete *x;", Left);
9425   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
9426   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
9427   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
9428   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
9429   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
9430   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
9431   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
9432   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
9433   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
9434 
9435   verifyIndependentOfContext("a = *(x + y);");
9436   verifyIndependentOfContext("a = &(x + y);");
9437   verifyIndependentOfContext("*(x + y).call();");
9438   verifyIndependentOfContext("&(x + y)->call();");
9439   verifyFormat("void f() { &(*I).first; }");
9440 
9441   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
9442   verifyFormat(
9443       "int *MyValues = {\n"
9444       "    *A, // Operator detection might be confused by the '{'\n"
9445       "    *BB // Operator detection might be confused by previous comment\n"
9446       "};");
9447 
9448   verifyIndependentOfContext("if (int *a = &b)");
9449   verifyIndependentOfContext("if (int &a = *b)");
9450   verifyIndependentOfContext("if (a & b[i])");
9451   verifyIndependentOfContext("if constexpr (a & b[i])");
9452   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
9453   verifyIndependentOfContext("if (a * (b * c))");
9454   verifyIndependentOfContext("if constexpr (a * (b * c))");
9455   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
9456   verifyIndependentOfContext("if (a::b::c::d & b[i])");
9457   verifyIndependentOfContext("if (*b[i])");
9458   verifyIndependentOfContext("if (int *a = (&b))");
9459   verifyIndependentOfContext("while (int *a = &b)");
9460   verifyIndependentOfContext("while (a * (b * c))");
9461   verifyIndependentOfContext("size = sizeof *a;");
9462   verifyIndependentOfContext("if (a && (b = c))");
9463   verifyFormat("void f() {\n"
9464                "  for (const int &v : Values) {\n"
9465                "  }\n"
9466                "}");
9467   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
9468   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
9469   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
9470 
9471   verifyFormat("#define A (!a * b)");
9472   verifyFormat("#define MACRO     \\\n"
9473                "  int *i = a * b; \\\n"
9474                "  void f(a *b);",
9475                getLLVMStyleWithColumns(19));
9476 
9477   verifyIndependentOfContext("A = new SomeType *[Length];");
9478   verifyIndependentOfContext("A = new SomeType *[Length]();");
9479   verifyIndependentOfContext("T **t = new T *;");
9480   verifyIndependentOfContext("T **t = new T *();");
9481   verifyGoogleFormat("A = new SomeType*[Length]();");
9482   verifyGoogleFormat("A = new SomeType*[Length];");
9483   verifyGoogleFormat("T** t = new T*;");
9484   verifyGoogleFormat("T** t = new T*();");
9485 
9486   verifyFormat("STATIC_ASSERT((a & b) == 0);");
9487   verifyFormat("STATIC_ASSERT(0 == (a & b));");
9488   verifyFormat("template <bool a, bool b> "
9489                "typename t::if<x && y>::type f() {}");
9490   verifyFormat("template <int *y> f() {}");
9491   verifyFormat("vector<int *> v;");
9492   verifyFormat("vector<int *const> v;");
9493   verifyFormat("vector<int *const **const *> v;");
9494   verifyFormat("vector<int *volatile> v;");
9495   verifyFormat("vector<a *_Nonnull> v;");
9496   verifyFormat("vector<a *_Nullable> v;");
9497   verifyFormat("vector<a *_Null_unspecified> v;");
9498   verifyFormat("vector<a *__ptr32> v;");
9499   verifyFormat("vector<a *__ptr64> v;");
9500   verifyFormat("vector<a *__capability> v;");
9501   FormatStyle TypeMacros = getLLVMStyle();
9502   TypeMacros.TypenameMacros = {"LIST"};
9503   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
9504   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
9505   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
9506   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
9507   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
9508 
9509   FormatStyle CustomQualifier = getLLVMStyle();
9510   // Add identifiers that should not be parsed as a qualifier by default.
9511   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9512   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
9513   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
9514   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
9515   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
9516   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
9517   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
9518   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
9519   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
9520   verifyFormat("vector<a * _NotAQualifier> v;");
9521   verifyFormat("vector<a * __not_a_qualifier> v;");
9522   verifyFormat("vector<a * b> v;");
9523   verifyFormat("foo<b && false>();");
9524   verifyFormat("foo<b & 1>();");
9525   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
9526   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
9527   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
9528   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
9529   verifyFormat(
9530       "template <class T, class = typename std::enable_if<\n"
9531       "                       std::is_integral<T>::value &&\n"
9532       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
9533       "void F();",
9534       getLLVMStyleWithColumns(70));
9535   verifyFormat("template <class T,\n"
9536                "          class = typename std::enable_if<\n"
9537                "              std::is_integral<T>::value &&\n"
9538                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
9539                "          class U>\n"
9540                "void F();",
9541                getLLVMStyleWithColumns(70));
9542   verifyFormat(
9543       "template <class T,\n"
9544       "          class = typename ::std::enable_if<\n"
9545       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
9546       "void F();",
9547       getGoogleStyleWithColumns(68));
9548 
9549   verifyIndependentOfContext("MACRO(int *i);");
9550   verifyIndependentOfContext("MACRO(auto *a);");
9551   verifyIndependentOfContext("MACRO(const A *a);");
9552   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
9553   verifyIndependentOfContext("MACRO(decltype(A) *a);");
9554   verifyIndependentOfContext("MACRO(typeof(A) *a);");
9555   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
9556   verifyIndependentOfContext("MACRO(A *const a);");
9557   verifyIndependentOfContext("MACRO(A *restrict a);");
9558   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
9559   verifyIndependentOfContext("MACRO(A *__restrict a);");
9560   verifyIndependentOfContext("MACRO(A *volatile a);");
9561   verifyIndependentOfContext("MACRO(A *__volatile a);");
9562   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
9563   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
9564   verifyIndependentOfContext("MACRO(A *_Nullable a);");
9565   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
9566   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
9567   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
9568   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
9569   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
9570   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
9571   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
9572   verifyIndependentOfContext("MACRO(A *__capability);");
9573   verifyIndependentOfContext("MACRO(A &__capability);");
9574   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
9575   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
9576   // If we add __my_qualifier to AttributeMacros it should always be parsed as
9577   // a type declaration:
9578   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
9579   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
9580   // Also check that TypenameMacros prevents parsing it as multiplication:
9581   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
9582   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
9583 
9584   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
9585   verifyFormat("void f() { f(float{1}, a * a); }");
9586   verifyFormat("void f() { f(float(1), a * a); }");
9587 
9588   verifyFormat("f((void (*)(int))g);");
9589   verifyFormat("f((void (&)(int))g);");
9590   verifyFormat("f((void (^)(int))g);");
9591 
9592   // FIXME: Is there a way to make this work?
9593   // verifyIndependentOfContext("MACRO(A *a);");
9594   verifyFormat("MACRO(A &B);");
9595   verifyFormat("MACRO(A *B);");
9596   verifyFormat("void f() { MACRO(A * B); }");
9597   verifyFormat("void f() { MACRO(A & B); }");
9598 
9599   // This lambda was mis-formatted after D88956 (treating it as a binop):
9600   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
9601   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
9602   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
9603   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
9604 
9605   verifyFormat("DatumHandle const *operator->() const { return input_; }");
9606   verifyFormat("return options != nullptr && operator==(*options);");
9607 
9608   EXPECT_EQ("#define OP(x)                                    \\\n"
9609             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
9610             "    return s << a.DebugString();                 \\\n"
9611             "  }",
9612             format("#define OP(x) \\\n"
9613                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
9614                    "    return s << a.DebugString(); \\\n"
9615                    "  }",
9616                    getLLVMStyleWithColumns(50)));
9617 
9618   // FIXME: We cannot handle this case yet; we might be able to figure out that
9619   // foo<x> d > v; doesn't make sense.
9620   verifyFormat("foo<a<b && c> d> v;");
9621 
9622   FormatStyle PointerMiddle = getLLVMStyle();
9623   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
9624   verifyFormat("delete *x;", PointerMiddle);
9625   verifyFormat("int * x;", PointerMiddle);
9626   verifyFormat("int *[] x;", PointerMiddle);
9627   verifyFormat("template <int * y> f() {}", PointerMiddle);
9628   verifyFormat("int * f(int * a) {}", PointerMiddle);
9629   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
9630   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
9631   verifyFormat("A<int *> a;", PointerMiddle);
9632   verifyFormat("A<int **> a;", PointerMiddle);
9633   verifyFormat("A<int *, int *> a;", PointerMiddle);
9634   verifyFormat("A<int *[]> a;", PointerMiddle);
9635   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
9636   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
9637   verifyFormat("T ** t = new T *;", PointerMiddle);
9638 
9639   // Member function reference qualifiers aren't binary operators.
9640   verifyFormat("string // break\n"
9641                "operator()() & {}");
9642   verifyFormat("string // break\n"
9643                "operator()() && {}");
9644   verifyGoogleFormat("template <typename T>\n"
9645                      "auto x() & -> int {}");
9646 
9647   // Should be binary operators when used as an argument expression (overloaded
9648   // operator invoked as a member function).
9649   verifyFormat("void f() { a.operator()(a * a); }");
9650   verifyFormat("void f() { a->operator()(a & a); }");
9651   verifyFormat("void f() { a.operator()(*a & *a); }");
9652   verifyFormat("void f() { a->operator()(*a * *a); }");
9653 }
9654 
TEST_F(FormatTest,UnderstandsAttributes)9655 TEST_F(FormatTest, UnderstandsAttributes) {
9656   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
9657   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
9658                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
9659   FormatStyle AfterType = getLLVMStyle();
9660   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
9661   verifyFormat("__attribute__((nodebug)) void\n"
9662                "foo() {}\n",
9663                AfterType);
9664   verifyFormat("__unused void\n"
9665                "foo() {}",
9666                AfterType);
9667 
9668   FormatStyle CustomAttrs = getLLVMStyle();
9669   CustomAttrs.AttributeMacros.push_back("__unused");
9670   CustomAttrs.AttributeMacros.push_back("__attr1");
9671   CustomAttrs.AttributeMacros.push_back("__attr2");
9672   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
9673   verifyFormat("vector<SomeType *__attribute((foo))> v;");
9674   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
9675   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
9676   // Check that it is parsed as a multiplication without AttributeMacros and
9677   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
9678   verifyFormat("vector<SomeType * __attr1> v;");
9679   verifyFormat("vector<SomeType __attr1 *> v;");
9680   verifyFormat("vector<SomeType __attr1 *const> v;");
9681   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
9682   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
9683   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
9684   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
9685   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
9686   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
9687   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
9688   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
9689 
9690   // Check that these are not parsed as function declarations:
9691   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9692   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
9693   verifyFormat("SomeType s(InitValue);", CustomAttrs);
9694   verifyFormat("SomeType s{InitValue};", CustomAttrs);
9695   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
9696   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
9697   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
9698   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
9699   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
9700   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
9701 }
9702 
TEST_F(FormatTest,UnderstandsPointerQualifiersInCast)9703 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
9704   // Check that qualifiers on pointers don't break parsing of casts.
9705   verifyFormat("x = (foo *const)*v;");
9706   verifyFormat("x = (foo *volatile)*v;");
9707   verifyFormat("x = (foo *restrict)*v;");
9708   verifyFormat("x = (foo *__attribute__((foo)))*v;");
9709   verifyFormat("x = (foo *_Nonnull)*v;");
9710   verifyFormat("x = (foo *_Nullable)*v;");
9711   verifyFormat("x = (foo *_Null_unspecified)*v;");
9712   verifyFormat("x = (foo *_Nonnull)*v;");
9713   verifyFormat("x = (foo *[[clang::attr]])*v;");
9714   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
9715   verifyFormat("x = (foo *__ptr32)*v;");
9716   verifyFormat("x = (foo *__ptr64)*v;");
9717   verifyFormat("x = (foo *__capability)*v;");
9718 
9719   // Check that we handle multiple trailing qualifiers and skip them all to
9720   // determine that the expression is a cast to a pointer type.
9721   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
9722   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
9723   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
9724   StringRef AllQualifiers =
9725       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
9726       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
9727   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
9728   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
9729 
9730   // Also check that address-of is not parsed as a binary bitwise-and:
9731   verifyFormat("x = (foo *const)&v;");
9732   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
9733   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
9734 
9735   // Check custom qualifiers:
9736   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
9737   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
9738   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
9739   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
9740   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
9741                CustomQualifier);
9742   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
9743                CustomQualifier);
9744 
9745   // Check that unknown identifiers result in binary operator parsing:
9746   verifyFormat("x = (foo * __unknown_qualifier) * v;");
9747   verifyFormat("x = (foo * __unknown_qualifier) & v;");
9748 }
9749 
TEST_F(FormatTest,UnderstandsSquareAttributes)9750 TEST_F(FormatTest, UnderstandsSquareAttributes) {
9751   verifyFormat("SomeType s [[unused]] (InitValue);");
9752   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
9753   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
9754   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
9755   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
9756   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9757                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
9758   verifyFormat("[[nodiscard]] bool f() { return false; }");
9759   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
9760   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
9761   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
9762 
9763   // Make sure we do not mistake attributes for array subscripts.
9764   verifyFormat("int a() {}\n"
9765                "[[unused]] int b() {}\n");
9766   verifyFormat("NSArray *arr;\n"
9767                "arr[[Foo() bar]];");
9768 
9769   // On the other hand, we still need to correctly find array subscripts.
9770   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
9771 
9772   // Make sure that we do not mistake Objective-C method inside array literals
9773   // as attributes, even if those method names are also keywords.
9774   verifyFormat("@[ [foo bar] ];");
9775   verifyFormat("@[ [NSArray class] ];");
9776   verifyFormat("@[ [foo enum] ];");
9777 
9778   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
9779 
9780   // Make sure we do not parse attributes as lambda introducers.
9781   FormatStyle MultiLineFunctions = getLLVMStyle();
9782   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9783   verifyFormat("[[unused]] int b() {\n"
9784                "  return 42;\n"
9785                "}\n",
9786                MultiLineFunctions);
9787 }
9788 
TEST_F(FormatTest,AttributeClass)9789 TEST_F(FormatTest, AttributeClass) {
9790   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
9791   verifyFormat("class S {\n"
9792                "  S(S&&) = default;\n"
9793                "};",
9794                Style);
9795   verifyFormat("class [[nodiscard]] S {\n"
9796                "  S(S&&) = default;\n"
9797                "};",
9798                Style);
9799   verifyFormat("class __attribute((maybeunused)) S {\n"
9800                "  S(S&&) = default;\n"
9801                "};",
9802                Style);
9803   verifyFormat("struct S {\n"
9804                "  S(S&&) = default;\n"
9805                "};",
9806                Style);
9807   verifyFormat("struct [[nodiscard]] S {\n"
9808                "  S(S&&) = default;\n"
9809                "};",
9810                Style);
9811 }
9812 
TEST_F(FormatTest,AttributesAfterMacro)9813 TEST_F(FormatTest, AttributesAfterMacro) {
9814   FormatStyle Style = getLLVMStyle();
9815   verifyFormat("MACRO;\n"
9816                "__attribute__((maybe_unused)) int foo() {\n"
9817                "  //...\n"
9818                "}");
9819 
9820   verifyFormat("MACRO;\n"
9821                "[[nodiscard]] int foo() {\n"
9822                "  //...\n"
9823                "}");
9824 
9825   EXPECT_EQ("MACRO\n\n"
9826             "__attribute__((maybe_unused)) int foo() {\n"
9827             "  //...\n"
9828             "}",
9829             format("MACRO\n\n"
9830                    "__attribute__((maybe_unused)) int foo() {\n"
9831                    "  //...\n"
9832                    "}"));
9833 
9834   EXPECT_EQ("MACRO\n\n"
9835             "[[nodiscard]] int foo() {\n"
9836             "  //...\n"
9837             "}",
9838             format("MACRO\n\n"
9839                    "[[nodiscard]] int foo() {\n"
9840                    "  //...\n"
9841                    "}"));
9842 }
9843 
TEST_F(FormatTest,AttributePenaltyBreaking)9844 TEST_F(FormatTest, AttributePenaltyBreaking) {
9845   FormatStyle Style = getLLVMStyle();
9846   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
9847                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
9848                Style);
9849   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
9850                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
9851                Style);
9852   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
9853                "shared_ptr<ALongTypeName> &C d) {\n}",
9854                Style);
9855 }
9856 
TEST_F(FormatTest,UnderstandsEllipsis)9857 TEST_F(FormatTest, UnderstandsEllipsis) {
9858   FormatStyle Style = getLLVMStyle();
9859   verifyFormat("int printf(const char *fmt, ...);");
9860   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
9861   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
9862 
9863   verifyFormat("template <int *...PP> a;", Style);
9864 
9865   Style.PointerAlignment = FormatStyle::PAS_Left;
9866   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
9867 
9868   verifyFormat("template <int*... PP> a;", Style);
9869 
9870   Style.PointerAlignment = FormatStyle::PAS_Middle;
9871   verifyFormat("template <int *... PP> a;", Style);
9872 }
9873 
TEST_F(FormatTest,AdaptivelyFormatsPointersAndReferences)9874 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
9875   EXPECT_EQ("int *a;\n"
9876             "int *a;\n"
9877             "int *a;",
9878             format("int *a;\n"
9879                    "int* a;\n"
9880                    "int *a;",
9881                    getGoogleStyle()));
9882   EXPECT_EQ("int* a;\n"
9883             "int* a;\n"
9884             "int* a;",
9885             format("int* a;\n"
9886                    "int* a;\n"
9887                    "int *a;",
9888                    getGoogleStyle()));
9889   EXPECT_EQ("int *a;\n"
9890             "int *a;\n"
9891             "int *a;",
9892             format("int *a;\n"
9893                    "int * a;\n"
9894                    "int *  a;",
9895                    getGoogleStyle()));
9896   EXPECT_EQ("auto x = [] {\n"
9897             "  int *a;\n"
9898             "  int *a;\n"
9899             "  int *a;\n"
9900             "};",
9901             format("auto x=[]{int *a;\n"
9902                    "int * a;\n"
9903                    "int *  a;};",
9904                    getGoogleStyle()));
9905 }
9906 
TEST_F(FormatTest,UnderstandsRvalueReferences)9907 TEST_F(FormatTest, UnderstandsRvalueReferences) {
9908   verifyFormat("int f(int &&a) {}");
9909   verifyFormat("int f(int a, char &&b) {}");
9910   verifyFormat("void f() { int &&a = b; }");
9911   verifyGoogleFormat("int f(int a, char&& b) {}");
9912   verifyGoogleFormat("void f() { int&& a = b; }");
9913 
9914   verifyIndependentOfContext("A<int &&> a;");
9915   verifyIndependentOfContext("A<int &&, int &&> a;");
9916   verifyGoogleFormat("A<int&&> a;");
9917   verifyGoogleFormat("A<int&&, int&&> a;");
9918 
9919   // Not rvalue references:
9920   verifyFormat("template <bool B, bool C> class A {\n"
9921                "  static_assert(B && C, \"Something is wrong\");\n"
9922                "};");
9923   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
9924   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
9925   verifyFormat("#define A(a, b) (a && b)");
9926 }
9927 
TEST_F(FormatTest,FormatsBinaryOperatorsPrecedingEquals)9928 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
9929   verifyFormat("void f() {\n"
9930                "  x[aaaaaaaaa -\n"
9931                "    b] = 23;\n"
9932                "}",
9933                getLLVMStyleWithColumns(15));
9934 }
9935 
TEST_F(FormatTest,FormatsCasts)9936 TEST_F(FormatTest, FormatsCasts) {
9937   verifyFormat("Type *A = static_cast<Type *>(P);");
9938   verifyFormat("Type *A = (Type *)P;");
9939   verifyFormat("Type *A = (vector<Type *, int *>)P;");
9940   verifyFormat("int a = (int)(2.0f);");
9941   verifyFormat("int a = (int)2.0f;");
9942   verifyFormat("x[(int32)y];");
9943   verifyFormat("x = (int32)y;");
9944   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
9945   verifyFormat("int a = (int)*b;");
9946   verifyFormat("int a = (int)2.0f;");
9947   verifyFormat("int a = (int)~0;");
9948   verifyFormat("int a = (int)++a;");
9949   verifyFormat("int a = (int)sizeof(int);");
9950   verifyFormat("int a = (int)+2;");
9951   verifyFormat("my_int a = (my_int)2.0f;");
9952   verifyFormat("my_int a = (my_int)sizeof(int);");
9953   verifyFormat("return (my_int)aaa;");
9954   verifyFormat("#define x ((int)-1)");
9955   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
9956   verifyFormat("#define p(q) ((int *)&q)");
9957   verifyFormat("fn(a)(b) + 1;");
9958 
9959   verifyFormat("void f() { my_int a = (my_int)*b; }");
9960   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
9961   verifyFormat("my_int a = (my_int)~0;");
9962   verifyFormat("my_int a = (my_int)++a;");
9963   verifyFormat("my_int a = (my_int)-2;");
9964   verifyFormat("my_int a = (my_int)1;");
9965   verifyFormat("my_int a = (my_int *)1;");
9966   verifyFormat("my_int a = (const my_int)-1;");
9967   verifyFormat("my_int a = (const my_int *)-1;");
9968   verifyFormat("my_int a = (my_int)(my_int)-1;");
9969   verifyFormat("my_int a = (ns::my_int)-2;");
9970   verifyFormat("case (my_int)ONE:");
9971   verifyFormat("auto x = (X)this;");
9972   // Casts in Obj-C style calls used to not be recognized as such.
9973   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
9974 
9975   // FIXME: single value wrapped with paren will be treated as cast.
9976   verifyFormat("void f(int i = (kValue)*kMask) {}");
9977 
9978   verifyFormat("{ (void)F; }");
9979 
9980   // Don't break after a cast's
9981   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
9982                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
9983                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
9984 
9985   // These are not casts.
9986   verifyFormat("void f(int *) {}");
9987   verifyFormat("f(foo)->b;");
9988   verifyFormat("f(foo).b;");
9989   verifyFormat("f(foo)(b);");
9990   verifyFormat("f(foo)[b];");
9991   verifyFormat("[](foo) { return 4; }(bar);");
9992   verifyFormat("(*funptr)(foo)[4];");
9993   verifyFormat("funptrs[4](foo)[4];");
9994   verifyFormat("void f(int *);");
9995   verifyFormat("void f(int *) = 0;");
9996   verifyFormat("void f(SmallVector<int>) {}");
9997   verifyFormat("void f(SmallVector<int>);");
9998   verifyFormat("void f(SmallVector<int>) = 0;");
9999   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
10000   verifyFormat("int a = sizeof(int) * b;");
10001   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
10002   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
10003   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
10004   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
10005 
10006   // These are not casts, but at some point were confused with casts.
10007   verifyFormat("virtual void foo(int *) override;");
10008   verifyFormat("virtual void foo(char &) const;");
10009   verifyFormat("virtual void foo(int *a, char *) const;");
10010   verifyFormat("int a = sizeof(int *) + b;");
10011   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
10012   verifyFormat("bool b = f(g<int>) && c;");
10013   verifyFormat("typedef void (*f)(int i) func;");
10014   verifyFormat("void operator++(int) noexcept;");
10015   verifyFormat("void operator++(int &) noexcept;");
10016   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
10017                "&) noexcept;");
10018   verifyFormat(
10019       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
10020   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
10021   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
10022   verifyFormat("void operator delete(nothrow_t &) noexcept;");
10023   verifyFormat("void operator delete(foo &) noexcept;");
10024   verifyFormat("void operator delete(foo) noexcept;");
10025   verifyFormat("void operator delete(int) noexcept;");
10026   verifyFormat("void operator delete(int &) noexcept;");
10027   verifyFormat("void operator delete(int &) volatile noexcept;");
10028   verifyFormat("void operator delete(int &) const");
10029   verifyFormat("void operator delete(int &) = default");
10030   verifyFormat("void operator delete(int &) = delete");
10031   verifyFormat("void operator delete(int &) [[noreturn]]");
10032   verifyFormat("void operator delete(int &) throw();");
10033   verifyFormat("void operator delete(int &) throw(int);");
10034   verifyFormat("auto operator delete(int &) -> int;");
10035   verifyFormat("auto operator delete(int &) override");
10036   verifyFormat("auto operator delete(int &) final");
10037 
10038   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
10039                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
10040   // FIXME: The indentation here is not ideal.
10041   verifyFormat(
10042       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10043       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
10044       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
10045 }
10046 
TEST_F(FormatTest,FormatsFunctionTypes)10047 TEST_F(FormatTest, FormatsFunctionTypes) {
10048   verifyFormat("A<bool()> a;");
10049   verifyFormat("A<SomeType()> a;");
10050   verifyFormat("A<void (*)(int, std::string)> a;");
10051   verifyFormat("A<void *(int)>;");
10052   verifyFormat("void *(*a)(int *, SomeType *);");
10053   verifyFormat("int (*func)(void *);");
10054   verifyFormat("void f() { int (*func)(void *); }");
10055   verifyFormat("template <class CallbackClass>\n"
10056                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
10057 
10058   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
10059   verifyGoogleFormat("void* (*a)(int);");
10060   verifyGoogleFormat(
10061       "template <class CallbackClass>\n"
10062       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
10063 
10064   // Other constructs can look somewhat like function types:
10065   verifyFormat("A<sizeof(*x)> a;");
10066   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
10067   verifyFormat("some_var = function(*some_pointer_var)[0];");
10068   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
10069   verifyFormat("int x = f(&h)();");
10070   verifyFormat("returnsFunction(&param1, &param2)(param);");
10071   verifyFormat("std::function<\n"
10072                "    LooooooooooongTemplatedType<\n"
10073                "        SomeType>*(\n"
10074                "        LooooooooooooooooongType type)>\n"
10075                "    function;",
10076                getGoogleStyleWithColumns(40));
10077 }
10078 
TEST_F(FormatTest,FormatsPointersToArrayTypes)10079 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
10080   verifyFormat("A (*foo_)[6];");
10081   verifyFormat("vector<int> (*foo_)[6];");
10082 }
10083 
TEST_F(FormatTest,BreaksLongVariableDeclarations)10084 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
10085   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10086                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10087   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
10088                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
10089   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10090                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
10091 
10092   // Different ways of ()-initializiation.
10093   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10094                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
10095   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10096                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
10097   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10098                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
10099   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
10100                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
10101 
10102   // Lambdas should not confuse the variable declaration heuristic.
10103   verifyFormat("LooooooooooooooooongType\n"
10104                "    variable(nullptr, [](A *a) {});",
10105                getLLVMStyleWithColumns(40));
10106 }
10107 
TEST_F(FormatTest,BreaksLongDeclarations)10108 TEST_F(FormatTest, BreaksLongDeclarations) {
10109   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
10110                "    AnotherNameForTheLongType;");
10111   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
10112                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
10113   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10114                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10115   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
10116                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
10117   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10118                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10119   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
10120                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10121   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10122                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10123   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10124                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10125   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
10126                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10127   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
10128                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10129   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
10130                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
10131   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10132                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
10133   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10134                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
10135   FormatStyle Indented = getLLVMStyle();
10136   Indented.IndentWrappedFunctionNames = true;
10137   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10138                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
10139                Indented);
10140   verifyFormat(
10141       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
10142       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10143       Indented);
10144   verifyFormat(
10145       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
10146       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10147       Indented);
10148   verifyFormat(
10149       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
10150       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
10151       Indented);
10152 
10153   // FIXME: Without the comment, this breaks after "(".
10154   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
10155                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
10156                getGoogleStyle());
10157 
10158   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
10159                "                  int LoooooooooooooooooooongParam2) {}");
10160   verifyFormat(
10161       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
10162       "                                   SourceLocation L, IdentifierIn *II,\n"
10163       "                                   Type *T) {}");
10164   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
10165                "ReallyReaaallyLongFunctionName(\n"
10166                "    const std::string &SomeParameter,\n"
10167                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10168                "        &ReallyReallyLongParameterName,\n"
10169                "    const SomeType<string, SomeOtherTemplateParameter>\n"
10170                "        &AnotherLongParameterName) {}");
10171   verifyFormat("template <typename A>\n"
10172                "SomeLoooooooooooooooooooooongType<\n"
10173                "    typename some_namespace::SomeOtherType<A>::Type>\n"
10174                "Function() {}");
10175 
10176   verifyGoogleFormat(
10177       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
10178       "    aaaaaaaaaaaaaaaaaaaaaaa;");
10179   verifyGoogleFormat(
10180       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
10181       "                                   SourceLocation L) {}");
10182   verifyGoogleFormat(
10183       "some_namespace::LongReturnType\n"
10184       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
10185       "    int first_long_parameter, int second_parameter) {}");
10186 
10187   verifyGoogleFormat("template <typename T>\n"
10188                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10189                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
10190   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10191                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
10192 
10193   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
10194                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10195                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10196   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10197                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
10198                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
10199   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
10200                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
10201                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
10202                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
10203 
10204   verifyFormat("template <typename T> // Templates on own line.\n"
10205                "static int            // Some comment.\n"
10206                "MyFunction(int a);",
10207                getLLVMStyle());
10208 }
10209 
TEST_F(FormatTest,FormatsAccessModifiers)10210 TEST_F(FormatTest, FormatsAccessModifiers) {
10211   FormatStyle Style = getLLVMStyle();
10212   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
10213             FormatStyle::ELBAMS_LogicalBlock);
10214   verifyFormat("struct foo {\n"
10215                "private:\n"
10216                "  void f() {}\n"
10217                "\n"
10218                "private:\n"
10219                "  int i;\n"
10220                "\n"
10221                "protected:\n"
10222                "  int j;\n"
10223                "};\n",
10224                Style);
10225   verifyFormat("struct foo {\n"
10226                "private:\n"
10227                "  void f() {}\n"
10228                "\n"
10229                "private:\n"
10230                "  int i;\n"
10231                "\n"
10232                "protected:\n"
10233                "  int j;\n"
10234                "};\n",
10235                "struct foo {\n"
10236                "private:\n"
10237                "  void f() {}\n"
10238                "private:\n"
10239                "  int i;\n"
10240                "protected:\n"
10241                "  int j;\n"
10242                "};\n",
10243                Style);
10244   verifyFormat("struct foo { /* comment */\n"
10245                "private:\n"
10246                "  int i;\n"
10247                "  // comment\n"
10248                "private:\n"
10249                "  int j;\n"
10250                "};\n",
10251                Style);
10252   verifyFormat("struct foo {\n"
10253                "#ifdef FOO\n"
10254                "#endif\n"
10255                "private:\n"
10256                "  int i;\n"
10257                "#ifdef FOO\n"
10258                "private:\n"
10259                "#endif\n"
10260                "  int j;\n"
10261                "};\n",
10262                Style);
10263   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10264   verifyFormat("struct foo {\n"
10265                "private:\n"
10266                "  void f() {}\n"
10267                "private:\n"
10268                "  int i;\n"
10269                "protected:\n"
10270                "  int j;\n"
10271                "};\n",
10272                Style);
10273   verifyFormat("struct foo {\n"
10274                "private:\n"
10275                "  void f() {}\n"
10276                "private:\n"
10277                "  int i;\n"
10278                "protected:\n"
10279                "  int j;\n"
10280                "};\n",
10281                "struct foo {\n"
10282                "\n"
10283                "private:\n"
10284                "  void f() {}\n"
10285                "\n"
10286                "private:\n"
10287                "  int i;\n"
10288                "\n"
10289                "protected:\n"
10290                "  int j;\n"
10291                "};\n",
10292                Style);
10293   verifyFormat("struct foo { /* comment */\n"
10294                "private:\n"
10295                "  int i;\n"
10296                "  // comment\n"
10297                "private:\n"
10298                "  int j;\n"
10299                "};\n",
10300                "struct foo { /* comment */\n"
10301                "\n"
10302                "private:\n"
10303                "  int i;\n"
10304                "  // comment\n"
10305                "\n"
10306                "private:\n"
10307                "  int j;\n"
10308                "};\n",
10309                Style);
10310   verifyFormat("struct foo {\n"
10311                "#ifdef FOO\n"
10312                "#endif\n"
10313                "private:\n"
10314                "  int i;\n"
10315                "#ifdef FOO\n"
10316                "private:\n"
10317                "#endif\n"
10318                "  int j;\n"
10319                "};\n",
10320                "struct foo {\n"
10321                "#ifdef FOO\n"
10322                "#endif\n"
10323                "\n"
10324                "private:\n"
10325                "  int i;\n"
10326                "#ifdef FOO\n"
10327                "\n"
10328                "private:\n"
10329                "#endif\n"
10330                "  int j;\n"
10331                "};\n",
10332                Style);
10333   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10334   verifyFormat("struct foo {\n"
10335                "private:\n"
10336                "  void f() {}\n"
10337                "\n"
10338                "private:\n"
10339                "  int i;\n"
10340                "\n"
10341                "protected:\n"
10342                "  int j;\n"
10343                "};\n",
10344                Style);
10345   verifyFormat("struct foo {\n"
10346                "private:\n"
10347                "  void f() {}\n"
10348                "\n"
10349                "private:\n"
10350                "  int i;\n"
10351                "\n"
10352                "protected:\n"
10353                "  int j;\n"
10354                "};\n",
10355                "struct foo {\n"
10356                "private:\n"
10357                "  void f() {}\n"
10358                "private:\n"
10359                "  int i;\n"
10360                "protected:\n"
10361                "  int j;\n"
10362                "};\n",
10363                Style);
10364   verifyFormat("struct foo { /* comment */\n"
10365                "private:\n"
10366                "  int i;\n"
10367                "  // comment\n"
10368                "\n"
10369                "private:\n"
10370                "  int j;\n"
10371                "};\n",
10372                "struct foo { /* comment */\n"
10373                "private:\n"
10374                "  int i;\n"
10375                "  // comment\n"
10376                "\n"
10377                "private:\n"
10378                "  int j;\n"
10379                "};\n",
10380                Style);
10381   verifyFormat("struct foo {\n"
10382                "#ifdef FOO\n"
10383                "#endif\n"
10384                "\n"
10385                "private:\n"
10386                "  int i;\n"
10387                "#ifdef FOO\n"
10388                "\n"
10389                "private:\n"
10390                "#endif\n"
10391                "  int j;\n"
10392                "};\n",
10393                "struct foo {\n"
10394                "#ifdef FOO\n"
10395                "#endif\n"
10396                "private:\n"
10397                "  int i;\n"
10398                "#ifdef FOO\n"
10399                "private:\n"
10400                "#endif\n"
10401                "  int j;\n"
10402                "};\n",
10403                Style);
10404   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10405   EXPECT_EQ("struct foo {\n"
10406             "\n"
10407             "private:\n"
10408             "  void f() {}\n"
10409             "\n"
10410             "private:\n"
10411             "  int i;\n"
10412             "\n"
10413             "protected:\n"
10414             "  int j;\n"
10415             "};\n",
10416             format("struct foo {\n"
10417                    "\n"
10418                    "private:\n"
10419                    "  void f() {}\n"
10420                    "\n"
10421                    "private:\n"
10422                    "  int i;\n"
10423                    "\n"
10424                    "protected:\n"
10425                    "  int j;\n"
10426                    "};\n",
10427                    Style));
10428   verifyFormat("struct foo {\n"
10429                "private:\n"
10430                "  void f() {}\n"
10431                "private:\n"
10432                "  int i;\n"
10433                "protected:\n"
10434                "  int j;\n"
10435                "};\n",
10436                Style);
10437   EXPECT_EQ("struct foo { /* comment */\n"
10438             "\n"
10439             "private:\n"
10440             "  int i;\n"
10441             "  // comment\n"
10442             "\n"
10443             "private:\n"
10444             "  int j;\n"
10445             "};\n",
10446             format("struct foo { /* comment */\n"
10447                    "\n"
10448                    "private:\n"
10449                    "  int i;\n"
10450                    "  // comment\n"
10451                    "\n"
10452                    "private:\n"
10453                    "  int j;\n"
10454                    "};\n",
10455                    Style));
10456   verifyFormat("struct foo { /* comment */\n"
10457                "private:\n"
10458                "  int i;\n"
10459                "  // comment\n"
10460                "private:\n"
10461                "  int j;\n"
10462                "};\n",
10463                Style);
10464   EXPECT_EQ("struct foo {\n"
10465             "#ifdef FOO\n"
10466             "#endif\n"
10467             "\n"
10468             "private:\n"
10469             "  int i;\n"
10470             "#ifdef FOO\n"
10471             "\n"
10472             "private:\n"
10473             "#endif\n"
10474             "  int j;\n"
10475             "};\n",
10476             format("struct foo {\n"
10477                    "#ifdef FOO\n"
10478                    "#endif\n"
10479                    "\n"
10480                    "private:\n"
10481                    "  int i;\n"
10482                    "#ifdef FOO\n"
10483                    "\n"
10484                    "private:\n"
10485                    "#endif\n"
10486                    "  int j;\n"
10487                    "};\n",
10488                    Style));
10489   verifyFormat("struct foo {\n"
10490                "#ifdef FOO\n"
10491                "#endif\n"
10492                "private:\n"
10493                "  int i;\n"
10494                "#ifdef FOO\n"
10495                "private:\n"
10496                "#endif\n"
10497                "  int j;\n"
10498                "};\n",
10499                Style);
10500 
10501   FormatStyle NoEmptyLines = getLLVMStyle();
10502   NoEmptyLines.MaxEmptyLinesToKeep = 0;
10503   verifyFormat("struct foo {\n"
10504                "private:\n"
10505                "  void f() {}\n"
10506                "\n"
10507                "private:\n"
10508                "  int i;\n"
10509                "\n"
10510                "public:\n"
10511                "protected:\n"
10512                "  int j;\n"
10513                "};\n",
10514                NoEmptyLines);
10515 
10516   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10517   verifyFormat("struct foo {\n"
10518                "private:\n"
10519                "  void f() {}\n"
10520                "private:\n"
10521                "  int i;\n"
10522                "public:\n"
10523                "protected:\n"
10524                "  int j;\n"
10525                "};\n",
10526                NoEmptyLines);
10527 
10528   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10529   verifyFormat("struct foo {\n"
10530                "private:\n"
10531                "  void f() {}\n"
10532                "\n"
10533                "private:\n"
10534                "  int i;\n"
10535                "\n"
10536                "public:\n"
10537                "\n"
10538                "protected:\n"
10539                "  int j;\n"
10540                "};\n",
10541                NoEmptyLines);
10542 }
10543 
TEST_F(FormatTest,FormatsAfterAccessModifiers)10544 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
10545 
10546   FormatStyle Style = getLLVMStyle();
10547   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
10548   verifyFormat("struct foo {\n"
10549                "private:\n"
10550                "  void f() {}\n"
10551                "\n"
10552                "private:\n"
10553                "  int i;\n"
10554                "\n"
10555                "protected:\n"
10556                "  int j;\n"
10557                "};\n",
10558                Style);
10559 
10560   // Check if lines are removed.
10561   verifyFormat("struct foo {\n"
10562                "private:\n"
10563                "  void f() {}\n"
10564                "\n"
10565                "private:\n"
10566                "  int i;\n"
10567                "\n"
10568                "protected:\n"
10569                "  int j;\n"
10570                "};\n",
10571                "struct foo {\n"
10572                "private:\n"
10573                "\n"
10574                "  void f() {}\n"
10575                "\n"
10576                "private:\n"
10577                "\n"
10578                "  int i;\n"
10579                "\n"
10580                "protected:\n"
10581                "\n"
10582                "  int j;\n"
10583                "};\n",
10584                Style);
10585 
10586   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10587   verifyFormat("struct foo {\n"
10588                "private:\n"
10589                "\n"
10590                "  void f() {}\n"
10591                "\n"
10592                "private:\n"
10593                "\n"
10594                "  int i;\n"
10595                "\n"
10596                "protected:\n"
10597                "\n"
10598                "  int j;\n"
10599                "};\n",
10600                Style);
10601 
10602   // Check if lines are added.
10603   verifyFormat("struct foo {\n"
10604                "private:\n"
10605                "\n"
10606                "  void f() {}\n"
10607                "\n"
10608                "private:\n"
10609                "\n"
10610                "  int i;\n"
10611                "\n"
10612                "protected:\n"
10613                "\n"
10614                "  int j;\n"
10615                "};\n",
10616                "struct foo {\n"
10617                "private:\n"
10618                "  void f() {}\n"
10619                "\n"
10620                "private:\n"
10621                "  int i;\n"
10622                "\n"
10623                "protected:\n"
10624                "  int j;\n"
10625                "};\n",
10626                Style);
10627 
10628   // Leave tests rely on the code layout, test::messUp can not be used.
10629   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10630   Style.MaxEmptyLinesToKeep = 0u;
10631   verifyFormat("struct foo {\n"
10632                "private:\n"
10633                "  void f() {}\n"
10634                "\n"
10635                "private:\n"
10636                "  int i;\n"
10637                "\n"
10638                "protected:\n"
10639                "  int j;\n"
10640                "};\n",
10641                Style);
10642 
10643   // Check if MaxEmptyLinesToKeep is respected.
10644   EXPECT_EQ("struct foo {\n"
10645             "private:\n"
10646             "  void f() {}\n"
10647             "\n"
10648             "private:\n"
10649             "  int i;\n"
10650             "\n"
10651             "protected:\n"
10652             "  int j;\n"
10653             "};\n",
10654             format("struct foo {\n"
10655                    "private:\n"
10656                    "\n\n\n"
10657                    "  void f() {}\n"
10658                    "\n"
10659                    "private:\n"
10660                    "\n\n\n"
10661                    "  int i;\n"
10662                    "\n"
10663                    "protected:\n"
10664                    "\n\n\n"
10665                    "  int j;\n"
10666                    "};\n",
10667                    Style));
10668 
10669   Style.MaxEmptyLinesToKeep = 1u;
10670   EXPECT_EQ("struct foo {\n"
10671             "private:\n"
10672             "\n"
10673             "  void f() {}\n"
10674             "\n"
10675             "private:\n"
10676             "\n"
10677             "  int i;\n"
10678             "\n"
10679             "protected:\n"
10680             "\n"
10681             "  int j;\n"
10682             "};\n",
10683             format("struct foo {\n"
10684                    "private:\n"
10685                    "\n"
10686                    "  void f() {}\n"
10687                    "\n"
10688                    "private:\n"
10689                    "\n"
10690                    "  int i;\n"
10691                    "\n"
10692                    "protected:\n"
10693                    "\n"
10694                    "  int j;\n"
10695                    "};\n",
10696                    Style));
10697   // Check if no lines are kept.
10698   EXPECT_EQ("struct foo {\n"
10699             "private:\n"
10700             "  void f() {}\n"
10701             "\n"
10702             "private:\n"
10703             "  int i;\n"
10704             "\n"
10705             "protected:\n"
10706             "  int j;\n"
10707             "};\n",
10708             format("struct foo {\n"
10709                    "private:\n"
10710                    "  void f() {}\n"
10711                    "\n"
10712                    "private:\n"
10713                    "  int i;\n"
10714                    "\n"
10715                    "protected:\n"
10716                    "  int j;\n"
10717                    "};\n",
10718                    Style));
10719   // Check if MaxEmptyLinesToKeep is respected.
10720   EXPECT_EQ("struct foo {\n"
10721             "private:\n"
10722             "\n"
10723             "  void f() {}\n"
10724             "\n"
10725             "private:\n"
10726             "\n"
10727             "  int i;\n"
10728             "\n"
10729             "protected:\n"
10730             "\n"
10731             "  int j;\n"
10732             "};\n",
10733             format("struct foo {\n"
10734                    "private:\n"
10735                    "\n\n\n"
10736                    "  void f() {}\n"
10737                    "\n"
10738                    "private:\n"
10739                    "\n\n\n"
10740                    "  int i;\n"
10741                    "\n"
10742                    "protected:\n"
10743                    "\n\n\n"
10744                    "  int j;\n"
10745                    "};\n",
10746                    Style));
10747 
10748   Style.MaxEmptyLinesToKeep = 10u;
10749   EXPECT_EQ("struct foo {\n"
10750             "private:\n"
10751             "\n\n\n"
10752             "  void f() {}\n"
10753             "\n"
10754             "private:\n"
10755             "\n\n\n"
10756             "  int i;\n"
10757             "\n"
10758             "protected:\n"
10759             "\n\n\n"
10760             "  int j;\n"
10761             "};\n",
10762             format("struct foo {\n"
10763                    "private:\n"
10764                    "\n\n\n"
10765                    "  void f() {}\n"
10766                    "\n"
10767                    "private:\n"
10768                    "\n\n\n"
10769                    "  int i;\n"
10770                    "\n"
10771                    "protected:\n"
10772                    "\n\n\n"
10773                    "  int j;\n"
10774                    "};\n",
10775                    Style));
10776 
10777   // Test with comments.
10778   Style = getLLVMStyle();
10779   verifyFormat("struct foo {\n"
10780                "private:\n"
10781                "  // comment\n"
10782                "  void f() {}\n"
10783                "\n"
10784                "private: /* comment */\n"
10785                "  int i;\n"
10786                "};\n",
10787                Style);
10788   verifyFormat("struct foo {\n"
10789                "private:\n"
10790                "  // comment\n"
10791                "  void f() {}\n"
10792                "\n"
10793                "private: /* comment */\n"
10794                "  int i;\n"
10795                "};\n",
10796                "struct foo {\n"
10797                "private:\n"
10798                "\n"
10799                "  // comment\n"
10800                "  void f() {}\n"
10801                "\n"
10802                "private: /* comment */\n"
10803                "\n"
10804                "  int i;\n"
10805                "};\n",
10806                Style);
10807 
10808   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10809   verifyFormat("struct foo {\n"
10810                "private:\n"
10811                "\n"
10812                "  // comment\n"
10813                "  void f() {}\n"
10814                "\n"
10815                "private: /* comment */\n"
10816                "\n"
10817                "  int i;\n"
10818                "};\n",
10819                "struct foo {\n"
10820                "private:\n"
10821                "  // comment\n"
10822                "  void f() {}\n"
10823                "\n"
10824                "private: /* comment */\n"
10825                "  int i;\n"
10826                "};\n",
10827                Style);
10828   verifyFormat("struct foo {\n"
10829                "private:\n"
10830                "\n"
10831                "  // comment\n"
10832                "  void f() {}\n"
10833                "\n"
10834                "private: /* comment */\n"
10835                "\n"
10836                "  int i;\n"
10837                "};\n",
10838                Style);
10839 
10840   // Test with preprocessor defines.
10841   Style = getLLVMStyle();
10842   verifyFormat("struct foo {\n"
10843                "private:\n"
10844                "#ifdef FOO\n"
10845                "#endif\n"
10846                "  void f() {}\n"
10847                "};\n",
10848                Style);
10849   verifyFormat("struct foo {\n"
10850                "private:\n"
10851                "#ifdef FOO\n"
10852                "#endif\n"
10853                "  void f() {}\n"
10854                "};\n",
10855                "struct foo {\n"
10856                "private:\n"
10857                "\n"
10858                "#ifdef FOO\n"
10859                "#endif\n"
10860                "  void f() {}\n"
10861                "};\n",
10862                Style);
10863 
10864   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10865   verifyFormat("struct foo {\n"
10866                "private:\n"
10867                "\n"
10868                "#ifdef FOO\n"
10869                "#endif\n"
10870                "  void f() {}\n"
10871                "};\n",
10872                "struct foo {\n"
10873                "private:\n"
10874                "#ifdef FOO\n"
10875                "#endif\n"
10876                "  void f() {}\n"
10877                "};\n",
10878                Style);
10879   verifyFormat("struct foo {\n"
10880                "private:\n"
10881                "\n"
10882                "#ifdef FOO\n"
10883                "#endif\n"
10884                "  void f() {}\n"
10885                "};\n",
10886                Style);
10887 }
10888 
TEST_F(FormatTest,FormatsAfterAndBeforeAccessModifiersInteraction)10889 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
10890   // Combined tests of EmptyLineAfterAccessModifier and
10891   // EmptyLineBeforeAccessModifier.
10892   FormatStyle Style = getLLVMStyle();
10893   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10894   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10895   verifyFormat("struct foo {\n"
10896                "private:\n"
10897                "\n"
10898                "protected:\n"
10899                "};\n",
10900                Style);
10901 
10902   Style.MaxEmptyLinesToKeep = 10u;
10903   // Both remove all new lines.
10904   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
10905   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
10906   verifyFormat("struct foo {\n"
10907                "private:\n"
10908                "protected:\n"
10909                "};\n",
10910                "struct foo {\n"
10911                "private:\n"
10912                "\n\n\n"
10913                "protected:\n"
10914                "};\n",
10915                Style);
10916 
10917   // Leave tests rely on the code layout, test::messUp can not be used.
10918   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10919   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10920   Style.MaxEmptyLinesToKeep = 10u;
10921   EXPECT_EQ("struct foo {\n"
10922             "private:\n"
10923             "\n\n\n"
10924             "protected:\n"
10925             "};\n",
10926             format("struct foo {\n"
10927                    "private:\n"
10928                    "\n\n\n"
10929                    "protected:\n"
10930                    "};\n",
10931                    Style));
10932   Style.MaxEmptyLinesToKeep = 3u;
10933   EXPECT_EQ("struct foo {\n"
10934             "private:\n"
10935             "\n\n\n"
10936             "protected:\n"
10937             "};\n",
10938             format("struct foo {\n"
10939                    "private:\n"
10940                    "\n\n\n"
10941                    "protected:\n"
10942                    "};\n",
10943                    Style));
10944   Style.MaxEmptyLinesToKeep = 1u;
10945   EXPECT_EQ("struct foo {\n"
10946             "private:\n"
10947             "\n\n\n"
10948             "protected:\n"
10949             "};\n",
10950             format("struct foo {\n"
10951                    "private:\n"
10952                    "\n\n\n"
10953                    "protected:\n"
10954                    "};\n",
10955                    Style)); // Based on new lines in original document and not
10956                             // on the setting.
10957 
10958   Style.MaxEmptyLinesToKeep = 10u;
10959   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
10960   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
10961   // Newlines are kept if they are greater than zero,
10962   // test::messUp removes all new lines which changes the logic
10963   EXPECT_EQ("struct foo {\n"
10964             "private:\n"
10965             "\n\n\n"
10966             "protected:\n"
10967             "};\n",
10968             format("struct foo {\n"
10969                    "private:\n"
10970                    "\n\n\n"
10971                    "protected:\n"
10972                    "};\n",
10973                    Style));
10974 
10975   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10976   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
10977   // test::messUp removes all new lines which changes the logic
10978   EXPECT_EQ("struct foo {\n"
10979             "private:\n"
10980             "\n\n\n"
10981             "protected:\n"
10982             "};\n",
10983             format("struct foo {\n"
10984                    "private:\n"
10985                    "\n\n\n"
10986                    "protected:\n"
10987                    "};\n",
10988                    Style));
10989 
10990   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
10991   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
10992   EXPECT_EQ("struct foo {\n"
10993             "private:\n"
10994             "\n\n\n"
10995             "protected:\n"
10996             "};\n",
10997             format("struct foo {\n"
10998                    "private:\n"
10999                    "\n\n\n"
11000                    "protected:\n"
11001                    "};\n",
11002                    Style)); // test::messUp removes all new lines which changes
11003                             // the logic.
11004 
11005   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11006   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11007   verifyFormat("struct foo {\n"
11008                "private:\n"
11009                "protected:\n"
11010                "};\n",
11011                "struct foo {\n"
11012                "private:\n"
11013                "\n\n\n"
11014                "protected:\n"
11015                "};\n",
11016                Style);
11017 
11018   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
11019   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11020   EXPECT_EQ("struct foo {\n"
11021             "private:\n"
11022             "\n\n\n"
11023             "protected:\n"
11024             "};\n",
11025             format("struct foo {\n"
11026                    "private:\n"
11027                    "\n\n\n"
11028                    "protected:\n"
11029                    "};\n",
11030                    Style)); // test::messUp removes all new lines which changes
11031                             // the logic.
11032 
11033   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
11034   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11035   verifyFormat("struct foo {\n"
11036                "private:\n"
11037                "protected:\n"
11038                "};\n",
11039                "struct foo {\n"
11040                "private:\n"
11041                "\n\n\n"
11042                "protected:\n"
11043                "};\n",
11044                Style);
11045 
11046   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11047   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
11048   verifyFormat("struct foo {\n"
11049                "private:\n"
11050                "protected:\n"
11051                "};\n",
11052                "struct foo {\n"
11053                "private:\n"
11054                "\n\n\n"
11055                "protected:\n"
11056                "};\n",
11057                Style);
11058 
11059   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11060   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
11061   verifyFormat("struct foo {\n"
11062                "private:\n"
11063                "protected:\n"
11064                "};\n",
11065                "struct foo {\n"
11066                "private:\n"
11067                "\n\n\n"
11068                "protected:\n"
11069                "};\n",
11070                Style);
11071 
11072   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
11073   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
11074   verifyFormat("struct foo {\n"
11075                "private:\n"
11076                "protected:\n"
11077                "};\n",
11078                "struct foo {\n"
11079                "private:\n"
11080                "\n\n\n"
11081                "protected:\n"
11082                "};\n",
11083                Style);
11084 }
11085 
TEST_F(FormatTest,FormatsArrays)11086 TEST_F(FormatTest, FormatsArrays) {
11087   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11088                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
11089   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
11090                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
11091   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
11092                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
11093   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11094                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11095   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11096                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
11097   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11098                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11099                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
11100   verifyFormat(
11101       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
11102       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
11103       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
11104   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
11105                "    .aaaaaaaaaaaaaaaaaaaaaa();");
11106 
11107   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
11108                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
11109   verifyFormat(
11110       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
11111       "                                  .aaaaaaa[0]\n"
11112       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
11113   verifyFormat("a[::b::c];");
11114 
11115   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
11116 
11117   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
11118   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
11119 }
11120 
TEST_F(FormatTest,LineStartsWithSpecialCharacter)11121 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
11122   verifyFormat("(a)->b();");
11123   verifyFormat("--a;");
11124 }
11125 
TEST_F(FormatTest,HandlesIncludeDirectives)11126 TEST_F(FormatTest, HandlesIncludeDirectives) {
11127   verifyFormat("#include <string>\n"
11128                "#include <a/b/c.h>\n"
11129                "#include \"a/b/string\"\n"
11130                "#include \"string.h\"\n"
11131                "#include \"string.h\"\n"
11132                "#include <a-a>\n"
11133                "#include < path with space >\n"
11134                "#include_next <test.h>"
11135                "#include \"abc.h\" // this is included for ABC\n"
11136                "#include \"some long include\" // with a comment\n"
11137                "#include \"some very long include path\"\n"
11138                "#include <some/very/long/include/path>\n",
11139                getLLVMStyleWithColumns(35));
11140   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
11141   EXPECT_EQ("#include <a>", format("#include<a>"));
11142 
11143   verifyFormat("#import <string>");
11144   verifyFormat("#import <a/b/c.h>");
11145   verifyFormat("#import \"a/b/string\"");
11146   verifyFormat("#import \"string.h\"");
11147   verifyFormat("#import \"string.h\"");
11148   verifyFormat("#if __has_include(<strstream>)\n"
11149                "#include <strstream>\n"
11150                "#endif");
11151 
11152   verifyFormat("#define MY_IMPORT <a/b>");
11153 
11154   verifyFormat("#if __has_include(<a/b>)");
11155   verifyFormat("#if __has_include_next(<a/b>)");
11156   verifyFormat("#define F __has_include(<a/b>)");
11157   verifyFormat("#define F __has_include_next(<a/b>)");
11158 
11159   // Protocol buffer definition or missing "#".
11160   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
11161                getLLVMStyleWithColumns(30));
11162 
11163   FormatStyle Style = getLLVMStyle();
11164   Style.AlwaysBreakBeforeMultilineStrings = true;
11165   Style.ColumnLimit = 0;
11166   verifyFormat("#import \"abc.h\"", Style);
11167 
11168   // But 'import' might also be a regular C++ namespace.
11169   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11170                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
11171 }
11172 
11173 //===----------------------------------------------------------------------===//
11174 // Error recovery tests.
11175 //===----------------------------------------------------------------------===//
11176 
TEST_F(FormatTest,IncompleteParameterLists)11177 TEST_F(FormatTest, IncompleteParameterLists) {
11178   FormatStyle NoBinPacking = getLLVMStyle();
11179   NoBinPacking.BinPackParameters = false;
11180   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
11181                "                        double *min_x,\n"
11182                "                        double *max_x,\n"
11183                "                        double *min_y,\n"
11184                "                        double *max_y,\n"
11185                "                        double *min_z,\n"
11186                "                        double *max_z, ) {}",
11187                NoBinPacking);
11188 }
11189 
TEST_F(FormatTest,IncorrectCodeTrailingStuff)11190 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
11191   verifyFormat("void f() { return; }\n42");
11192   verifyFormat("void f() {\n"
11193                "  if (0)\n"
11194                "    return;\n"
11195                "}\n"
11196                "42");
11197   verifyFormat("void f() { return }\n42");
11198   verifyFormat("void f() {\n"
11199                "  if (0)\n"
11200                "    return\n"
11201                "}\n"
11202                "42");
11203 }
11204 
TEST_F(FormatTest,IncorrectCodeMissingSemicolon)11205 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
11206   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
11207   EXPECT_EQ("void f() {\n"
11208             "  if (a)\n"
11209             "    return\n"
11210             "}",
11211             format("void  f  (  )  {  if  ( a )  return  }"));
11212   EXPECT_EQ("namespace N {\n"
11213             "void f()\n"
11214             "}",
11215             format("namespace  N  {  void f()  }"));
11216   EXPECT_EQ("namespace N {\n"
11217             "void f() {}\n"
11218             "void g()\n"
11219             "} // namespace N",
11220             format("namespace N  { void f( ) { } void g( ) }"));
11221 }
11222 
TEST_F(FormatTest,IndentationWithinColumnLimitNotPossible)11223 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
11224   verifyFormat("int aaaaaaaa =\n"
11225                "    // Overlylongcomment\n"
11226                "    b;",
11227                getLLVMStyleWithColumns(20));
11228   verifyFormat("function(\n"
11229                "    ShortArgument,\n"
11230                "    LoooooooooooongArgument);\n",
11231                getLLVMStyleWithColumns(20));
11232 }
11233 
TEST_F(FormatTest,IncorrectAccessSpecifier)11234 TEST_F(FormatTest, IncorrectAccessSpecifier) {
11235   verifyFormat("public:");
11236   verifyFormat("class A {\n"
11237                "public\n"
11238                "  void f() {}\n"
11239                "};");
11240   verifyFormat("public\n"
11241                "int qwerty;");
11242   verifyFormat("public\n"
11243                "B {}");
11244   verifyFormat("public\n"
11245                "{}");
11246   verifyFormat("public\n"
11247                "B { int x; }");
11248 }
11249 
TEST_F(FormatTest,IncorrectCodeUnbalancedBraces)11250 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
11251   verifyFormat("{");
11252   verifyFormat("#})");
11253   verifyNoCrash("(/**/[:!] ?[).");
11254 }
11255 
TEST_F(FormatTest,IncorrectUnbalancedBracesInMacrosWithUnicode)11256 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
11257   // Found by oss-fuzz:
11258   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
11259   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
11260   Style.ColumnLimit = 60;
11261   verifyNoCrash(
11262       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
11263       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
11264       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
11265       Style);
11266 }
11267 
TEST_F(FormatTest,IncorrectCodeDoNoWhile)11268 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
11269   verifyFormat("do {\n}");
11270   verifyFormat("do {\n}\n"
11271                "f();");
11272   verifyFormat("do {\n}\n"
11273                "wheeee(fun);");
11274   verifyFormat("do {\n"
11275                "  f();\n"
11276                "}");
11277 }
11278 
TEST_F(FormatTest,IncorrectCodeMissingParens)11279 TEST_F(FormatTest, IncorrectCodeMissingParens) {
11280   verifyFormat("if {\n  foo;\n  foo();\n}");
11281   verifyFormat("switch {\n  foo;\n  foo();\n}");
11282   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
11283   verifyFormat("while {\n  foo;\n  foo();\n}");
11284   verifyFormat("do {\n  foo;\n  foo();\n} while;");
11285 }
11286 
TEST_F(FormatTest,DoesNotTouchUnwrappedLinesWithErrors)11287 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
11288   verifyIncompleteFormat("namespace {\n"
11289                          "class Foo { Foo (\n"
11290                          "};\n"
11291                          "} // namespace");
11292 }
11293 
TEST_F(FormatTest,IncorrectCodeErrorDetection)11294 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
11295   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
11296   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
11297   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
11298   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
11299 
11300   EXPECT_EQ("{\n"
11301             "  {\n"
11302             "    breakme(\n"
11303             "        qwe);\n"
11304             "  }\n",
11305             format("{\n"
11306                    "    {\n"
11307                    " breakme(qwe);\n"
11308                    "}\n",
11309                    getLLVMStyleWithColumns(10)));
11310 }
11311 
TEST_F(FormatTest,LayoutCallsInsideBraceInitializers)11312 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
11313   verifyFormat("int x = {\n"
11314                "    avariable,\n"
11315                "    b(alongervariable)};",
11316                getLLVMStyleWithColumns(25));
11317 }
11318 
TEST_F(FormatTest,LayoutBraceInitializersInReturnStatement)11319 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
11320   verifyFormat("return (a)(b){1, 2, 3};");
11321 }
11322 
TEST_F(FormatTest,LayoutCxx11BraceInitializers)11323 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
11324   verifyFormat("vector<int> x{1, 2, 3, 4};");
11325   verifyFormat("vector<int> x{\n"
11326                "    1,\n"
11327                "    2,\n"
11328                "    3,\n"
11329                "    4,\n"
11330                "};");
11331   verifyFormat("vector<T> x{{}, {}, {}, {}};");
11332   verifyFormat("f({1, 2});");
11333   verifyFormat("auto v = Foo{-1};");
11334   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
11335   verifyFormat("Class::Class : member{1, 2, 3} {}");
11336   verifyFormat("new vector<int>{1, 2, 3};");
11337   verifyFormat("new int[3]{1, 2, 3};");
11338   verifyFormat("new int{1};");
11339   verifyFormat("return {arg1, arg2};");
11340   verifyFormat("return {arg1, SomeType{parameter}};");
11341   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
11342   verifyFormat("new T{arg1, arg2};");
11343   verifyFormat("f(MyMap[{composite, key}]);");
11344   verifyFormat("class Class {\n"
11345                "  T member = {arg1, arg2};\n"
11346                "};");
11347   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
11348   verifyFormat("const struct A a = {.a = 1, .b = 2};");
11349   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
11350   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
11351   verifyFormat("int a = std::is_integral<int>{} + 0;");
11352 
11353   verifyFormat("int foo(int i) { return fo1{}(i); }");
11354   verifyFormat("int foo(int i) { return fo1{}(i); }");
11355   verifyFormat("auto i = decltype(x){};");
11356   verifyFormat("auto i = typeof(x){};");
11357   verifyFormat("auto i = _Atomic(x){};");
11358   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
11359   verifyFormat("Node n{1, Node{1000}, //\n"
11360                "       2};");
11361   verifyFormat("Aaaa aaaaaaa{\n"
11362                "    {\n"
11363                "        aaaa,\n"
11364                "    },\n"
11365                "};");
11366   verifyFormat("class C : public D {\n"
11367                "  SomeClass SC{2};\n"
11368                "};");
11369   verifyFormat("class C : public A {\n"
11370                "  class D : public B {\n"
11371                "    void f() { int i{2}; }\n"
11372                "  };\n"
11373                "};");
11374   verifyFormat("#define A {a, a},");
11375 
11376   // Avoid breaking between equal sign and opening brace
11377   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
11378   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
11379   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
11380                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
11381                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
11382                "     {\"ccccccccccccccccccccc\", 2}};",
11383                AvoidBreakingFirstArgument);
11384 
11385   // Binpacking only if there is no trailing comma
11386   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
11387                "                      cccccccccc, dddddddddd};",
11388                getLLVMStyleWithColumns(50));
11389   verifyFormat("const Aaaaaa aaaaa = {\n"
11390                "    aaaaaaaaaaa,\n"
11391                "    bbbbbbbbbbb,\n"
11392                "    ccccccccccc,\n"
11393                "    ddddddddddd,\n"
11394                "};",
11395                getLLVMStyleWithColumns(50));
11396 
11397   // Cases where distinguising braced lists and blocks is hard.
11398   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
11399   verifyFormat("void f() {\n"
11400                "  return; // comment\n"
11401                "}\n"
11402                "SomeType t;");
11403   verifyFormat("void f() {\n"
11404                "  if (a) {\n"
11405                "    f();\n"
11406                "  }\n"
11407                "}\n"
11408                "SomeType t;");
11409 
11410   // In combination with BinPackArguments = false.
11411   FormatStyle NoBinPacking = getLLVMStyle();
11412   NoBinPacking.BinPackArguments = false;
11413   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
11414                "                      bbbbb,\n"
11415                "                      ccccc,\n"
11416                "                      ddddd,\n"
11417                "                      eeeee,\n"
11418                "                      ffffff,\n"
11419                "                      ggggg,\n"
11420                "                      hhhhhh,\n"
11421                "                      iiiiii,\n"
11422                "                      jjjjjj,\n"
11423                "                      kkkkkk};",
11424                NoBinPacking);
11425   verifyFormat("const Aaaaaa aaaaa = {\n"
11426                "    aaaaa,\n"
11427                "    bbbbb,\n"
11428                "    ccccc,\n"
11429                "    ddddd,\n"
11430                "    eeeee,\n"
11431                "    ffffff,\n"
11432                "    ggggg,\n"
11433                "    hhhhhh,\n"
11434                "    iiiiii,\n"
11435                "    jjjjjj,\n"
11436                "    kkkkkk,\n"
11437                "};",
11438                NoBinPacking);
11439   verifyFormat(
11440       "const Aaaaaa aaaaa = {\n"
11441       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
11442       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
11443       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
11444       "};",
11445       NoBinPacking);
11446 
11447   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
11448   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
11449             "    CDDDP83848_BMCR_REGISTER,\n"
11450             "    CDDDP83848_BMSR_REGISTER,\n"
11451             "    CDDDP83848_RBR_REGISTER};",
11452             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
11453                    "                                CDDDP83848_BMSR_REGISTER,\n"
11454                    "                                CDDDP83848_RBR_REGISTER};",
11455                    NoBinPacking));
11456 
11457   // FIXME: The alignment of these trailing comments might be bad. Then again,
11458   // this might be utterly useless in real code.
11459   verifyFormat("Constructor::Constructor()\n"
11460                "    : some_value{         //\n"
11461                "                 aaaaaaa, //\n"
11462                "                 bbbbbbb} {}");
11463 
11464   // In braced lists, the first comment is always assumed to belong to the
11465   // first element. Thus, it can be moved to the next or previous line as
11466   // appropriate.
11467   EXPECT_EQ("function({// First element:\n"
11468             "          1,\n"
11469             "          // Second element:\n"
11470             "          2});",
11471             format("function({\n"
11472                    "    // First element:\n"
11473                    "    1,\n"
11474                    "    // Second element:\n"
11475                    "    2});"));
11476   EXPECT_EQ("std::vector<int> MyNumbers{\n"
11477             "    // First element:\n"
11478             "    1,\n"
11479             "    // Second element:\n"
11480             "    2};",
11481             format("std::vector<int> MyNumbers{// First element:\n"
11482                    "                           1,\n"
11483                    "                           // Second element:\n"
11484                    "                           2};",
11485                    getLLVMStyleWithColumns(30)));
11486   // A trailing comma should still lead to an enforced line break and no
11487   // binpacking.
11488   EXPECT_EQ("vector<int> SomeVector = {\n"
11489             "    // aaa\n"
11490             "    1,\n"
11491             "    2,\n"
11492             "};",
11493             format("vector<int> SomeVector = { // aaa\n"
11494                    "    1, 2, };"));
11495 
11496   // C++11 brace initializer list l-braces should not be treated any differently
11497   // when breaking before lambda bodies is enabled
11498   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
11499   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
11500   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
11501   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
11502   verifyFormat(
11503       "std::runtime_error{\n"
11504       "    \"Long string which will force a break onto the next line...\"};",
11505       BreakBeforeLambdaBody);
11506 
11507   FormatStyle ExtraSpaces = getLLVMStyle();
11508   ExtraSpaces.Cpp11BracedListStyle = false;
11509   ExtraSpaces.ColumnLimit = 75;
11510   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
11511   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
11512   verifyFormat("f({ 1, 2 });", ExtraSpaces);
11513   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
11514   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
11515   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
11516   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
11517   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
11518   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
11519   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
11520   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
11521   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
11522   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
11523   verifyFormat("class Class {\n"
11524                "  T member = { arg1, arg2 };\n"
11525                "};",
11526                ExtraSpaces);
11527   verifyFormat(
11528       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11529       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
11530       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
11531       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
11532       ExtraSpaces);
11533   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
11534   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
11535                ExtraSpaces);
11536   verifyFormat(
11537       "someFunction(OtherParam,\n"
11538       "             BracedList{ // comment 1 (Forcing interesting break)\n"
11539       "                         param1, param2,\n"
11540       "                         // comment 2\n"
11541       "                         param3, param4 });",
11542       ExtraSpaces);
11543   verifyFormat(
11544       "std::this_thread::sleep_for(\n"
11545       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
11546       ExtraSpaces);
11547   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
11548                "    aaaaaaa,\n"
11549                "    aaaaaaaaaa,\n"
11550                "    aaaaa,\n"
11551                "    aaaaaaaaaaaaaaa,\n"
11552                "    aaa,\n"
11553                "    aaaaaaaaaa,\n"
11554                "    a,\n"
11555                "    aaaaaaaaaaaaaaaaaaaaa,\n"
11556                "    aaaaaaaaaaaa,\n"
11557                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
11558                "    aaaaaaa,\n"
11559                "    a};");
11560   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
11561   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
11562   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
11563 
11564   // Avoid breaking between initializer/equal sign and opening brace
11565   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
11566   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
11567                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11568                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11569                "  { \"ccccccccccccccccccccc\", 2 }\n"
11570                "};",
11571                ExtraSpaces);
11572   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
11573                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
11574                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
11575                "  { \"ccccccccccccccccccccc\", 2 }\n"
11576                "};",
11577                ExtraSpaces);
11578 
11579   FormatStyle SpaceBeforeBrace = getLLVMStyle();
11580   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
11581   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
11582   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
11583 
11584   FormatStyle SpaceBetweenBraces = getLLVMStyle();
11585   SpaceBetweenBraces.SpacesInAngles = FormatStyle::SIAS_Always;
11586   SpaceBetweenBraces.SpacesInParentheses = true;
11587   SpaceBetweenBraces.SpacesInSquareBrackets = true;
11588   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
11589   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
11590   verifyFormat("vector< int > x{ // comment 1\n"
11591                "                 1, 2, 3, 4 };",
11592                SpaceBetweenBraces);
11593   SpaceBetweenBraces.ColumnLimit = 20;
11594   EXPECT_EQ("vector< int > x{\n"
11595             "    1, 2, 3, 4 };",
11596             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11597   SpaceBetweenBraces.ColumnLimit = 24;
11598   EXPECT_EQ("vector< int > x{ 1, 2,\n"
11599             "                 3, 4 };",
11600             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
11601   EXPECT_EQ("vector< int > x{\n"
11602             "    1,\n"
11603             "    2,\n"
11604             "    3,\n"
11605             "    4,\n"
11606             "};",
11607             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
11608   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
11609   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
11610   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
11611 }
11612 
TEST_F(FormatTest,FormatsBracedListsInColumnLayout)11613 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
11614   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11615                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11616                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11617                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11618                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11619                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
11620   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
11621                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11622                "                 1, 22, 333, 4444, 55555, //\n"
11623                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11624                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
11625   verifyFormat(
11626       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
11627       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
11628       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
11629       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11630       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11631       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
11632       "                 7777777};");
11633   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11634                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11635                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
11636   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11637                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11638                "    // Separating comment.\n"
11639                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
11640   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
11641                "    // Leading comment\n"
11642                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
11643                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
11644   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11645                "                 1, 1, 1, 1};",
11646                getLLVMStyleWithColumns(39));
11647   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11648                "                 1, 1, 1, 1};",
11649                getLLVMStyleWithColumns(38));
11650   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
11651                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
11652                getLLVMStyleWithColumns(43));
11653   verifyFormat(
11654       "static unsigned SomeValues[10][3] = {\n"
11655       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
11656       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
11657   verifyFormat("static auto fields = new vector<string>{\n"
11658                "    \"aaaaaaaaaaaaa\",\n"
11659                "    \"aaaaaaaaaaaaa\",\n"
11660                "    \"aaaaaaaaaaaa\",\n"
11661                "    \"aaaaaaaaaaaaaa\",\n"
11662                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
11663                "    \"aaaaaaaaaaaa\",\n"
11664                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
11665                "};");
11666   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
11667   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
11668                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
11669                "                 3, cccccccccccccccccccccc};",
11670                getLLVMStyleWithColumns(60));
11671 
11672   // Trailing commas.
11673   verifyFormat("vector<int> x = {\n"
11674                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
11675                "};",
11676                getLLVMStyleWithColumns(39));
11677   verifyFormat("vector<int> x = {\n"
11678                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
11679                "};",
11680                getLLVMStyleWithColumns(39));
11681   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
11682                "                 1, 1, 1, 1,\n"
11683                "                 /**/ /**/};",
11684                getLLVMStyleWithColumns(39));
11685 
11686   // Trailing comment in the first line.
11687   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
11688                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
11689                "    111111111,  222222222,  3333333333,  444444444,  //\n"
11690                "    11111111,   22222222,   333333333,   44444444};");
11691   // Trailing comment in the last line.
11692   verifyFormat("int aaaaa[] = {\n"
11693                "    1, 2, 3, // comment\n"
11694                "    4, 5, 6  // comment\n"
11695                "};");
11696 
11697   // With nested lists, we should either format one item per line or all nested
11698   // lists one on line.
11699   // FIXME: For some nested lists, we can do better.
11700   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
11701                "        {aaaaaaaaaaaaaaaaaaa},\n"
11702                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
11703                "        {aaaaaaaaaaaaaaaaa}};",
11704                getLLVMStyleWithColumns(60));
11705   verifyFormat(
11706       "SomeStruct my_struct_array = {\n"
11707       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
11708       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
11709       "    {aaa, aaa},\n"
11710       "    {aaa, aaa},\n"
11711       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
11712       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
11713       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
11714 
11715   // No column layout should be used here.
11716   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
11717                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
11718 
11719   verifyNoCrash("a<,");
11720 
11721   // No braced initializer here.
11722   verifyFormat("void f() {\n"
11723                "  struct Dummy {};\n"
11724                "  f(v);\n"
11725                "}");
11726 
11727   // Long lists should be formatted in columns even if they are nested.
11728   verifyFormat(
11729       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11730       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11731       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11732       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11733       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
11734       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
11735 
11736   // Allow "single-column" layout even if that violates the column limit. There
11737   // isn't going to be a better way.
11738   verifyFormat("std::vector<int> a = {\n"
11739                "    aaaaaaaa,\n"
11740                "    aaaaaaaa,\n"
11741                "    aaaaaaaa,\n"
11742                "    aaaaaaaa,\n"
11743                "    aaaaaaaaaa,\n"
11744                "    aaaaaaaa,\n"
11745                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
11746                getLLVMStyleWithColumns(30));
11747   verifyFormat("vector<int> aaaa = {\n"
11748                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11749                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
11750                "    aaaaaa.aaaaaaa,\n"
11751                "    aaaaaa.aaaaaaa,\n"
11752                "    aaaaaa.aaaaaaa,\n"
11753                "    aaaaaa.aaaaaaa,\n"
11754                "};");
11755 
11756   // Don't create hanging lists.
11757   verifyFormat("someFunction(Param, {List1, List2,\n"
11758                "                     List3});",
11759                getLLVMStyleWithColumns(35));
11760   verifyFormat("someFunction(Param, Param,\n"
11761                "             {List1, List2,\n"
11762                "              List3});",
11763                getLLVMStyleWithColumns(35));
11764   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
11765                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
11766 }
11767 
TEST_F(FormatTest,PullTrivialFunctionDefinitionsIntoSingleLine)11768 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
11769   FormatStyle DoNotMerge = getLLVMStyle();
11770   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
11771 
11772   verifyFormat("void f() { return 42; }");
11773   verifyFormat("void f() {\n"
11774                "  return 42;\n"
11775                "}",
11776                DoNotMerge);
11777   verifyFormat("void f() {\n"
11778                "  // Comment\n"
11779                "}");
11780   verifyFormat("{\n"
11781                "#error {\n"
11782                "  int a;\n"
11783                "}");
11784   verifyFormat("{\n"
11785                "  int a;\n"
11786                "#error {\n"
11787                "}");
11788   verifyFormat("void f() {} // comment");
11789   verifyFormat("void f() { int a; } // comment");
11790   verifyFormat("void f() {\n"
11791                "} // comment",
11792                DoNotMerge);
11793   verifyFormat("void f() {\n"
11794                "  int a;\n"
11795                "} // comment",
11796                DoNotMerge);
11797   verifyFormat("void f() {\n"
11798                "} // comment",
11799                getLLVMStyleWithColumns(15));
11800 
11801   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
11802   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
11803 
11804   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
11805   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
11806   verifyFormat("class C {\n"
11807                "  C()\n"
11808                "      : iiiiiiii(nullptr),\n"
11809                "        kkkkkkk(nullptr),\n"
11810                "        mmmmmmm(nullptr),\n"
11811                "        nnnnnnn(nullptr) {}\n"
11812                "};",
11813                getGoogleStyle());
11814 
11815   FormatStyle NoColumnLimit = getLLVMStyle();
11816   NoColumnLimit.ColumnLimit = 0;
11817   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
11818   EXPECT_EQ("class C {\n"
11819             "  A() : b(0) {}\n"
11820             "};",
11821             format("class C{A():b(0){}};", NoColumnLimit));
11822   EXPECT_EQ("A()\n"
11823             "    : b(0) {\n"
11824             "}",
11825             format("A()\n:b(0)\n{\n}", NoColumnLimit));
11826 
11827   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
11828   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
11829       FormatStyle::SFS_None;
11830   EXPECT_EQ("A()\n"
11831             "    : b(0) {\n"
11832             "}",
11833             format("A():b(0){}", DoNotMergeNoColumnLimit));
11834   EXPECT_EQ("A()\n"
11835             "    : b(0) {\n"
11836             "}",
11837             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
11838 
11839   verifyFormat("#define A          \\\n"
11840                "  void f() {       \\\n"
11841                "    int i;         \\\n"
11842                "  }",
11843                getLLVMStyleWithColumns(20));
11844   verifyFormat("#define A           \\\n"
11845                "  void f() { int i; }",
11846                getLLVMStyleWithColumns(21));
11847   verifyFormat("#define A            \\\n"
11848                "  void f() {         \\\n"
11849                "    int i;           \\\n"
11850                "  }                  \\\n"
11851                "  int j;",
11852                getLLVMStyleWithColumns(22));
11853   verifyFormat("#define A             \\\n"
11854                "  void f() { int i; } \\\n"
11855                "  int j;",
11856                getLLVMStyleWithColumns(23));
11857 }
11858 
TEST_F(FormatTest,PullEmptyFunctionDefinitionsIntoSingleLine)11859 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
11860   FormatStyle MergeEmptyOnly = getLLVMStyle();
11861   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
11862   verifyFormat("class C {\n"
11863                "  int f() {}\n"
11864                "};",
11865                MergeEmptyOnly);
11866   verifyFormat("class C {\n"
11867                "  int f() {\n"
11868                "    return 42;\n"
11869                "  }\n"
11870                "};",
11871                MergeEmptyOnly);
11872   verifyFormat("int f() {}", MergeEmptyOnly);
11873   verifyFormat("int f() {\n"
11874                "  return 42;\n"
11875                "}",
11876                MergeEmptyOnly);
11877 
11878   // Also verify behavior when BraceWrapping.AfterFunction = true
11879   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
11880   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
11881   verifyFormat("int f() {}", MergeEmptyOnly);
11882   verifyFormat("class C {\n"
11883                "  int f() {}\n"
11884                "};",
11885                MergeEmptyOnly);
11886 }
11887 
TEST_F(FormatTest,PullInlineFunctionDefinitionsIntoSingleLine)11888 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
11889   FormatStyle MergeInlineOnly = getLLVMStyle();
11890   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
11891   verifyFormat("class C {\n"
11892                "  int f() { return 42; }\n"
11893                "};",
11894                MergeInlineOnly);
11895   verifyFormat("int f() {\n"
11896                "  return 42;\n"
11897                "}",
11898                MergeInlineOnly);
11899 
11900   // SFS_Inline implies SFS_Empty
11901   verifyFormat("class C {\n"
11902                "  int f() {}\n"
11903                "};",
11904                MergeInlineOnly);
11905   verifyFormat("int f() {}", MergeInlineOnly);
11906 
11907   // Also verify behavior when BraceWrapping.AfterFunction = true
11908   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
11909   MergeInlineOnly.BraceWrapping.AfterFunction = true;
11910   verifyFormat("class C {\n"
11911                "  int f() { return 42; }\n"
11912                "};",
11913                MergeInlineOnly);
11914   verifyFormat("int f()\n"
11915                "{\n"
11916                "  return 42;\n"
11917                "}",
11918                MergeInlineOnly);
11919 
11920   // SFS_Inline implies SFS_Empty
11921   verifyFormat("int f() {}", MergeInlineOnly);
11922   verifyFormat("class C {\n"
11923                "  int f() {}\n"
11924                "};",
11925                MergeInlineOnly);
11926 }
11927 
TEST_F(FormatTest,PullInlineOnlyFunctionDefinitionsIntoSingleLine)11928 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
11929   FormatStyle MergeInlineOnly = getLLVMStyle();
11930   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
11931       FormatStyle::SFS_InlineOnly;
11932   verifyFormat("class C {\n"
11933                "  int f() { return 42; }\n"
11934                "};",
11935                MergeInlineOnly);
11936   verifyFormat("int f() {\n"
11937                "  return 42;\n"
11938                "}",
11939                MergeInlineOnly);
11940 
11941   // SFS_InlineOnly does not imply SFS_Empty
11942   verifyFormat("class C {\n"
11943                "  int f() {}\n"
11944                "};",
11945                MergeInlineOnly);
11946   verifyFormat("int f() {\n"
11947                "}",
11948                MergeInlineOnly);
11949 
11950   // Also verify behavior when BraceWrapping.AfterFunction = true
11951   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
11952   MergeInlineOnly.BraceWrapping.AfterFunction = true;
11953   verifyFormat("class C {\n"
11954                "  int f() { return 42; }\n"
11955                "};",
11956                MergeInlineOnly);
11957   verifyFormat("int f()\n"
11958                "{\n"
11959                "  return 42;\n"
11960                "}",
11961                MergeInlineOnly);
11962 
11963   // SFS_InlineOnly does not imply SFS_Empty
11964   verifyFormat("int f()\n"
11965                "{\n"
11966                "}",
11967                MergeInlineOnly);
11968   verifyFormat("class C {\n"
11969                "  int f() {}\n"
11970                "};",
11971                MergeInlineOnly);
11972 }
11973 
TEST_F(FormatTest,SplitEmptyFunction)11974 TEST_F(FormatTest, SplitEmptyFunction) {
11975   FormatStyle Style = getLLVMStyle();
11976   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
11977   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
11978   Style.BraceWrapping.AfterFunction = true;
11979   Style.BraceWrapping.SplitEmptyFunction = false;
11980   Style.ColumnLimit = 40;
11981 
11982   verifyFormat("int f()\n"
11983                "{}",
11984                Style);
11985   verifyFormat("int f()\n"
11986                "{\n"
11987                "  return 42;\n"
11988                "}",
11989                Style);
11990   verifyFormat("int f()\n"
11991                "{\n"
11992                "  // some comment\n"
11993                "}",
11994                Style);
11995 
11996   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
11997   verifyFormat("int f() {}", Style);
11998   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
11999                "{}",
12000                Style);
12001   verifyFormat("int f()\n"
12002                "{\n"
12003                "  return 0;\n"
12004                "}",
12005                Style);
12006 
12007   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
12008   verifyFormat("class Foo {\n"
12009                "  int f() {}\n"
12010                "};\n",
12011                Style);
12012   verifyFormat("class Foo {\n"
12013                "  int f() { return 0; }\n"
12014                "};\n",
12015                Style);
12016   verifyFormat("class Foo {\n"
12017                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12018                "  {}\n"
12019                "};\n",
12020                Style);
12021   verifyFormat("class Foo {\n"
12022                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12023                "  {\n"
12024                "    return 0;\n"
12025                "  }\n"
12026                "};\n",
12027                Style);
12028 
12029   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12030   verifyFormat("int f() {}", Style);
12031   verifyFormat("int f() { return 0; }", Style);
12032   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12033                "{}",
12034                Style);
12035   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
12036                "{\n"
12037                "  return 0;\n"
12038                "}",
12039                Style);
12040 }
TEST_F(FormatTest,KeepShortFunctionAfterPPElse)12041 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
12042   FormatStyle Style = getLLVMStyle();
12043   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
12044   verifyFormat("#ifdef A\n"
12045                "int f() {}\n"
12046                "#else\n"
12047                "int g() {}\n"
12048                "#endif",
12049                Style);
12050 }
12051 
TEST_F(FormatTest,SplitEmptyClass)12052 TEST_F(FormatTest, SplitEmptyClass) {
12053   FormatStyle Style = getLLVMStyle();
12054   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12055   Style.BraceWrapping.AfterClass = true;
12056   Style.BraceWrapping.SplitEmptyRecord = false;
12057 
12058   verifyFormat("class Foo\n"
12059                "{};",
12060                Style);
12061   verifyFormat("/* something */ class Foo\n"
12062                "{};",
12063                Style);
12064   verifyFormat("template <typename X> class Foo\n"
12065                "{};",
12066                Style);
12067   verifyFormat("class Foo\n"
12068                "{\n"
12069                "  Foo();\n"
12070                "};",
12071                Style);
12072   verifyFormat("typedef class Foo\n"
12073                "{\n"
12074                "} Foo_t;",
12075                Style);
12076 
12077   Style.BraceWrapping.SplitEmptyRecord = true;
12078   Style.BraceWrapping.AfterStruct = true;
12079   verifyFormat("class rep\n"
12080                "{\n"
12081                "};",
12082                Style);
12083   verifyFormat("struct rep\n"
12084                "{\n"
12085                "};",
12086                Style);
12087   verifyFormat("template <typename T> class rep\n"
12088                "{\n"
12089                "};",
12090                Style);
12091   verifyFormat("template <typename T> struct rep\n"
12092                "{\n"
12093                "};",
12094                Style);
12095   verifyFormat("class rep\n"
12096                "{\n"
12097                "  int x;\n"
12098                "};",
12099                Style);
12100   verifyFormat("struct rep\n"
12101                "{\n"
12102                "  int x;\n"
12103                "};",
12104                Style);
12105   verifyFormat("template <typename T> class rep\n"
12106                "{\n"
12107                "  int x;\n"
12108                "};",
12109                Style);
12110   verifyFormat("template <typename T> struct rep\n"
12111                "{\n"
12112                "  int x;\n"
12113                "};",
12114                Style);
12115   verifyFormat("template <typename T> class rep // Foo\n"
12116                "{\n"
12117                "  int x;\n"
12118                "};",
12119                Style);
12120   verifyFormat("template <typename T> struct rep // Bar\n"
12121                "{\n"
12122                "  int x;\n"
12123                "};",
12124                Style);
12125 
12126   verifyFormat("template <typename T> class rep<T>\n"
12127                "{\n"
12128                "  int x;\n"
12129                "};",
12130                Style);
12131 
12132   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12133                "{\n"
12134                "  int x;\n"
12135                "};",
12136                Style);
12137   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
12138                "{\n"
12139                "};",
12140                Style);
12141 
12142   verifyFormat("#include \"stdint.h\"\n"
12143                "namespace rep {}",
12144                Style);
12145   verifyFormat("#include <stdint.h>\n"
12146                "namespace rep {}",
12147                Style);
12148   verifyFormat("#include <stdint.h>\n"
12149                "namespace rep {}",
12150                "#include <stdint.h>\n"
12151                "namespace rep {\n"
12152                "\n"
12153                "\n"
12154                "}",
12155                Style);
12156 }
12157 
TEST_F(FormatTest,SplitEmptyStruct)12158 TEST_F(FormatTest, SplitEmptyStruct) {
12159   FormatStyle Style = getLLVMStyle();
12160   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12161   Style.BraceWrapping.AfterStruct = true;
12162   Style.BraceWrapping.SplitEmptyRecord = false;
12163 
12164   verifyFormat("struct Foo\n"
12165                "{};",
12166                Style);
12167   verifyFormat("/* something */ struct Foo\n"
12168                "{};",
12169                Style);
12170   verifyFormat("template <typename X> struct Foo\n"
12171                "{};",
12172                Style);
12173   verifyFormat("struct Foo\n"
12174                "{\n"
12175                "  Foo();\n"
12176                "};",
12177                Style);
12178   verifyFormat("typedef struct Foo\n"
12179                "{\n"
12180                "} Foo_t;",
12181                Style);
12182   // typedef struct Bar {} Bar_t;
12183 }
12184 
TEST_F(FormatTest,SplitEmptyUnion)12185 TEST_F(FormatTest, SplitEmptyUnion) {
12186   FormatStyle Style = getLLVMStyle();
12187   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12188   Style.BraceWrapping.AfterUnion = true;
12189   Style.BraceWrapping.SplitEmptyRecord = false;
12190 
12191   verifyFormat("union Foo\n"
12192                "{};",
12193                Style);
12194   verifyFormat("/* something */ union Foo\n"
12195                "{};",
12196                Style);
12197   verifyFormat("union Foo\n"
12198                "{\n"
12199                "  A,\n"
12200                "};",
12201                Style);
12202   verifyFormat("typedef union Foo\n"
12203                "{\n"
12204                "} Foo_t;",
12205                Style);
12206 }
12207 
TEST_F(FormatTest,SplitEmptyNamespace)12208 TEST_F(FormatTest, SplitEmptyNamespace) {
12209   FormatStyle Style = getLLVMStyle();
12210   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12211   Style.BraceWrapping.AfterNamespace = true;
12212   Style.BraceWrapping.SplitEmptyNamespace = false;
12213 
12214   verifyFormat("namespace Foo\n"
12215                "{};",
12216                Style);
12217   verifyFormat("/* something */ namespace Foo\n"
12218                "{};",
12219                Style);
12220   verifyFormat("inline namespace Foo\n"
12221                "{};",
12222                Style);
12223   verifyFormat("/* something */ inline namespace Foo\n"
12224                "{};",
12225                Style);
12226   verifyFormat("export namespace Foo\n"
12227                "{};",
12228                Style);
12229   verifyFormat("namespace Foo\n"
12230                "{\n"
12231                "void Bar();\n"
12232                "};",
12233                Style);
12234 }
12235 
TEST_F(FormatTest,NeverMergeShortRecords)12236 TEST_F(FormatTest, NeverMergeShortRecords) {
12237   FormatStyle Style = getLLVMStyle();
12238 
12239   verifyFormat("class Foo {\n"
12240                "  Foo();\n"
12241                "};",
12242                Style);
12243   verifyFormat("typedef class Foo {\n"
12244                "  Foo();\n"
12245                "} Foo_t;",
12246                Style);
12247   verifyFormat("struct Foo {\n"
12248                "  Foo();\n"
12249                "};",
12250                Style);
12251   verifyFormat("typedef struct Foo {\n"
12252                "  Foo();\n"
12253                "} Foo_t;",
12254                Style);
12255   verifyFormat("union Foo {\n"
12256                "  A,\n"
12257                "};",
12258                Style);
12259   verifyFormat("typedef union Foo {\n"
12260                "  A,\n"
12261                "} Foo_t;",
12262                Style);
12263   verifyFormat("namespace Foo {\n"
12264                "void Bar();\n"
12265                "};",
12266                Style);
12267 
12268   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
12269   Style.BraceWrapping.AfterClass = true;
12270   Style.BraceWrapping.AfterStruct = true;
12271   Style.BraceWrapping.AfterUnion = true;
12272   Style.BraceWrapping.AfterNamespace = true;
12273   verifyFormat("class Foo\n"
12274                "{\n"
12275                "  Foo();\n"
12276                "};",
12277                Style);
12278   verifyFormat("typedef class Foo\n"
12279                "{\n"
12280                "  Foo();\n"
12281                "} Foo_t;",
12282                Style);
12283   verifyFormat("struct Foo\n"
12284                "{\n"
12285                "  Foo();\n"
12286                "};",
12287                Style);
12288   verifyFormat("typedef struct Foo\n"
12289                "{\n"
12290                "  Foo();\n"
12291                "} Foo_t;",
12292                Style);
12293   verifyFormat("union Foo\n"
12294                "{\n"
12295                "  A,\n"
12296                "};",
12297                Style);
12298   verifyFormat("typedef union Foo\n"
12299                "{\n"
12300                "  A,\n"
12301                "} Foo_t;",
12302                Style);
12303   verifyFormat("namespace Foo\n"
12304                "{\n"
12305                "void Bar();\n"
12306                "};",
12307                Style);
12308 }
12309 
TEST_F(FormatTest,UnderstandContextOfRecordTypeKeywords)12310 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
12311   // Elaborate type variable declarations.
12312   verifyFormat("struct foo a = {bar};\nint n;");
12313   verifyFormat("class foo a = {bar};\nint n;");
12314   verifyFormat("union foo a = {bar};\nint n;");
12315 
12316   // Elaborate types inside function definitions.
12317   verifyFormat("struct foo f() {}\nint n;");
12318   verifyFormat("class foo f() {}\nint n;");
12319   verifyFormat("union foo f() {}\nint n;");
12320 
12321   // Templates.
12322   verifyFormat("template <class X> void f() {}\nint n;");
12323   verifyFormat("template <struct X> void f() {}\nint n;");
12324   verifyFormat("template <union X> void f() {}\nint n;");
12325 
12326   // Actual definitions...
12327   verifyFormat("struct {\n} n;");
12328   verifyFormat(
12329       "template <template <class T, class Y>, class Z> class X {\n} n;");
12330   verifyFormat("union Z {\n  int n;\n} x;");
12331   verifyFormat("class MACRO Z {\n} n;");
12332   verifyFormat("class MACRO(X) Z {\n} n;");
12333   verifyFormat("class __attribute__(X) Z {\n} n;");
12334   verifyFormat("class __declspec(X) Z {\n} n;");
12335   verifyFormat("class A##B##C {\n} n;");
12336   verifyFormat("class alignas(16) Z {\n} n;");
12337   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
12338   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
12339 
12340   // Redefinition from nested context:
12341   verifyFormat("class A::B::C {\n} n;");
12342 
12343   // Template definitions.
12344   verifyFormat(
12345       "template <typename F>\n"
12346       "Matcher(const Matcher<F> &Other,\n"
12347       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
12348       "                             !is_same<F, T>::value>::type * = 0)\n"
12349       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
12350 
12351   // FIXME: This is still incorrectly handled at the formatter side.
12352   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
12353   verifyFormat("int i = SomeFunction(a<b, a> b);");
12354 
12355   // FIXME:
12356   // This now gets parsed incorrectly as class definition.
12357   // verifyFormat("class A<int> f() {\n}\nint n;");
12358 
12359   // Elaborate types where incorrectly parsing the structural element would
12360   // break the indent.
12361   verifyFormat("if (true)\n"
12362                "  class X x;\n"
12363                "else\n"
12364                "  f();\n");
12365 
12366   // This is simply incomplete. Formatting is not important, but must not crash.
12367   verifyFormat("class A:");
12368 }
12369 
TEST_F(FormatTest,DoNotInterfereWithErrorAndWarning)12370 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
12371   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
12372             format("#error Leave     all         white!!!!! space* alone!\n"));
12373   EXPECT_EQ(
12374       "#warning Leave     all         white!!!!! space* alone!\n",
12375       format("#warning Leave     all         white!!!!! space* alone!\n"));
12376   EXPECT_EQ("#error 1", format("  #  error   1"));
12377   EXPECT_EQ("#warning 1", format("  #  warning 1"));
12378 }
12379 
TEST_F(FormatTest,FormatHashIfExpressions)12380 TEST_F(FormatTest, FormatHashIfExpressions) {
12381   verifyFormat("#if AAAA && BBBB");
12382   verifyFormat("#if (AAAA && BBBB)");
12383   verifyFormat("#elif (AAAA && BBBB)");
12384   // FIXME: Come up with a better indentation for #elif.
12385   verifyFormat(
12386       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
12387       "    defined(BBBBBBBB)\n"
12388       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
12389       "    defined(BBBBBBBB)\n"
12390       "#endif",
12391       getLLVMStyleWithColumns(65));
12392 }
12393 
TEST_F(FormatTest,MergeHandlingInTheFaceOfPreprocessorDirectives)12394 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
12395   FormatStyle AllowsMergedIf = getGoogleStyle();
12396   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
12397       FormatStyle::SIS_WithoutElse;
12398   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
12399   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
12400   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
12401   EXPECT_EQ("if (true) return 42;",
12402             format("if (true)\nreturn 42;", AllowsMergedIf));
12403   FormatStyle ShortMergedIf = AllowsMergedIf;
12404   ShortMergedIf.ColumnLimit = 25;
12405   verifyFormat("#define A \\\n"
12406                "  if (true) return 42;",
12407                ShortMergedIf);
12408   verifyFormat("#define A \\\n"
12409                "  f();    \\\n"
12410                "  if (true)\n"
12411                "#define B",
12412                ShortMergedIf);
12413   verifyFormat("#define A \\\n"
12414                "  f();    \\\n"
12415                "  if (true)\n"
12416                "g();",
12417                ShortMergedIf);
12418   verifyFormat("{\n"
12419                "#ifdef A\n"
12420                "  // Comment\n"
12421                "  if (true) continue;\n"
12422                "#endif\n"
12423                "  // Comment\n"
12424                "  if (true) continue;\n"
12425                "}",
12426                ShortMergedIf);
12427   ShortMergedIf.ColumnLimit = 33;
12428   verifyFormat("#define A \\\n"
12429                "  if constexpr (true) return 42;",
12430                ShortMergedIf);
12431   verifyFormat("#define A \\\n"
12432                "  if CONSTEXPR (true) return 42;",
12433                ShortMergedIf);
12434   ShortMergedIf.ColumnLimit = 29;
12435   verifyFormat("#define A                   \\\n"
12436                "  if (aaaaaaaaaa) return 1; \\\n"
12437                "  return 2;",
12438                ShortMergedIf);
12439   ShortMergedIf.ColumnLimit = 28;
12440   verifyFormat("#define A         \\\n"
12441                "  if (aaaaaaaaaa) \\\n"
12442                "    return 1;     \\\n"
12443                "  return 2;",
12444                ShortMergedIf);
12445   verifyFormat("#define A                \\\n"
12446                "  if constexpr (aaaaaaa) \\\n"
12447                "    return 1;            \\\n"
12448                "  return 2;",
12449                ShortMergedIf);
12450   verifyFormat("#define A                \\\n"
12451                "  if CONSTEXPR (aaaaaaa) \\\n"
12452                "    return 1;            \\\n"
12453                "  return 2;",
12454                ShortMergedIf);
12455 }
12456 
TEST_F(FormatTest,FormatStarDependingOnContext)12457 TEST_F(FormatTest, FormatStarDependingOnContext) {
12458   verifyFormat("void f(int *a);");
12459   verifyFormat("void f() { f(fint * b); }");
12460   verifyFormat("class A {\n  void f(int *a);\n};");
12461   verifyFormat("class A {\n  int *a;\n};");
12462   verifyFormat("namespace a {\n"
12463                "namespace b {\n"
12464                "class A {\n"
12465                "  void f() {}\n"
12466                "  int *a;\n"
12467                "};\n"
12468                "} // namespace b\n"
12469                "} // namespace a");
12470 }
12471 
TEST_F(FormatTest,SpecialTokensAtEndOfLine)12472 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
12473   verifyFormat("while");
12474   verifyFormat("operator");
12475 }
12476 
TEST_F(FormatTest,SkipsDeeplyNestedLines)12477 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
12478   // This code would be painfully slow to format if we didn't skip it.
12479   std::string Code("A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n" // 20x
12480                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12481                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12482                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12483                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
12484                    "A(1, 1)\n"
12485                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
12486                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12487                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12488                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12489                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12490                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12491                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12492                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12493                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
12494                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
12495   // Deeply nested part is untouched, rest is formatted.
12496   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
12497             format(std::string("int    i;\n") + Code + "int    j;\n",
12498                    getLLVMStyle(), SC_ExpectIncomplete));
12499 }
12500 
12501 //===----------------------------------------------------------------------===//
12502 // Objective-C tests.
12503 //===----------------------------------------------------------------------===//
12504 
TEST_F(FormatTest,FormatForObjectiveCMethodDecls)12505 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
12506   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
12507   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
12508             format("-(NSUInteger)indexOfObject:(id)anObject;"));
12509   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
12510   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
12511   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
12512             format("-(NSInteger)Method3:(id)anObject;"));
12513   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
12514             format("-(NSInteger)Method4:(id)anObject;"));
12515   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
12516             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
12517   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
12518             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
12519   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12520             "forAllCells:(BOOL)flag;",
12521             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
12522                    "forAllCells:(BOOL)flag;"));
12523 
12524   // Very long objectiveC method declaration.
12525   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
12526                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
12527   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
12528                "                    inRange:(NSRange)range\n"
12529                "                   outRange:(NSRange)out_range\n"
12530                "                  outRange1:(NSRange)out_range1\n"
12531                "                  outRange2:(NSRange)out_range2\n"
12532                "                  outRange3:(NSRange)out_range3\n"
12533                "                  outRange4:(NSRange)out_range4\n"
12534                "                  outRange5:(NSRange)out_range5\n"
12535                "                  outRange6:(NSRange)out_range6\n"
12536                "                  outRange7:(NSRange)out_range7\n"
12537                "                  outRange8:(NSRange)out_range8\n"
12538                "                  outRange9:(NSRange)out_range9;");
12539 
12540   // When the function name has to be wrapped.
12541   FormatStyle Style = getLLVMStyle();
12542   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
12543   // and always indents instead.
12544   Style.IndentWrappedFunctionNames = false;
12545   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12546                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
12547                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
12548                "}",
12549                Style);
12550   Style.IndentWrappedFunctionNames = true;
12551   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
12552                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
12553                "               anotherName:(NSString)dddddddddddddd {\n"
12554                "}",
12555                Style);
12556 
12557   verifyFormat("- (int)sum:(vector<int>)numbers;");
12558   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
12559   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
12560   // protocol lists (but not for template classes):
12561   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
12562 
12563   verifyFormat("- (int (*)())foo:(int (*)())f;");
12564   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
12565 
12566   // If there's no return type (very rare in practice!), LLVM and Google style
12567   // agree.
12568   verifyFormat("- foo;");
12569   verifyFormat("- foo:(int)f;");
12570   verifyGoogleFormat("- foo:(int)foo;");
12571 }
12572 
TEST_F(FormatTest,BreaksStringLiterals)12573 TEST_F(FormatTest, BreaksStringLiterals) {
12574   EXPECT_EQ("\"some text \"\n"
12575             "\"other\";",
12576             format("\"some text other\";", getLLVMStyleWithColumns(12)));
12577   EXPECT_EQ("\"some text \"\n"
12578             "\"other\";",
12579             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
12580   EXPECT_EQ(
12581       "#define A  \\\n"
12582       "  \"some \"  \\\n"
12583       "  \"text \"  \\\n"
12584       "  \"other\";",
12585       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
12586   EXPECT_EQ(
12587       "#define A  \\\n"
12588       "  \"so \"    \\\n"
12589       "  \"text \"  \\\n"
12590       "  \"other\";",
12591       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
12592 
12593   EXPECT_EQ("\"some text\"",
12594             format("\"some text\"", getLLVMStyleWithColumns(1)));
12595   EXPECT_EQ("\"some text\"",
12596             format("\"some text\"", getLLVMStyleWithColumns(11)));
12597   EXPECT_EQ("\"some \"\n"
12598             "\"text\"",
12599             format("\"some text\"", getLLVMStyleWithColumns(10)));
12600   EXPECT_EQ("\"some \"\n"
12601             "\"text\"",
12602             format("\"some text\"", getLLVMStyleWithColumns(7)));
12603   EXPECT_EQ("\"some\"\n"
12604             "\" tex\"\n"
12605             "\"t\"",
12606             format("\"some text\"", getLLVMStyleWithColumns(6)));
12607   EXPECT_EQ("\"some\"\n"
12608             "\" tex\"\n"
12609             "\" and\"",
12610             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
12611   EXPECT_EQ("\"some\"\n"
12612             "\"/tex\"\n"
12613             "\"/and\"",
12614             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
12615 
12616   EXPECT_EQ("variable =\n"
12617             "    \"long string \"\n"
12618             "    \"literal\";",
12619             format("variable = \"long string literal\";",
12620                    getLLVMStyleWithColumns(20)));
12621 
12622   EXPECT_EQ("variable = f(\n"
12623             "    \"long string \"\n"
12624             "    \"literal\",\n"
12625             "    short,\n"
12626             "    loooooooooooooooooooong);",
12627             format("variable = f(\"long string literal\", short, "
12628                    "loooooooooooooooooooong);",
12629                    getLLVMStyleWithColumns(20)));
12630 
12631   EXPECT_EQ(
12632       "f(g(\"long string \"\n"
12633       "    \"literal\"),\n"
12634       "  b);",
12635       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
12636   EXPECT_EQ("f(g(\"long string \"\n"
12637             "    \"literal\",\n"
12638             "    a),\n"
12639             "  b);",
12640             format("f(g(\"long string literal\", a), b);",
12641                    getLLVMStyleWithColumns(20)));
12642   EXPECT_EQ(
12643       "f(\"one two\".split(\n"
12644       "    variable));",
12645       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
12646   EXPECT_EQ("f(\"one two three four five six \"\n"
12647             "  \"seven\".split(\n"
12648             "      really_looooong_variable));",
12649             format("f(\"one two three four five six seven\"."
12650                    "split(really_looooong_variable));",
12651                    getLLVMStyleWithColumns(33)));
12652 
12653   EXPECT_EQ("f(\"some \"\n"
12654             "  \"text\",\n"
12655             "  other);",
12656             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
12657 
12658   // Only break as a last resort.
12659   verifyFormat(
12660       "aaaaaaaaaaaaaaaaaaaa(\n"
12661       "    aaaaaaaaaaaaaaaaaaaa,\n"
12662       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
12663 
12664   EXPECT_EQ("\"splitmea\"\n"
12665             "\"trandomp\"\n"
12666             "\"oint\"",
12667             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
12668 
12669   EXPECT_EQ("\"split/\"\n"
12670             "\"pathat/\"\n"
12671             "\"slashes\"",
12672             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
12673 
12674   EXPECT_EQ("\"split/\"\n"
12675             "\"pathat/\"\n"
12676             "\"slashes\"",
12677             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
12678   EXPECT_EQ("\"split at \"\n"
12679             "\"spaces/at/\"\n"
12680             "\"slashes.at.any$\"\n"
12681             "\"non-alphanumeric%\"\n"
12682             "\"1111111111characte\"\n"
12683             "\"rs\"",
12684             format("\"split at "
12685                    "spaces/at/"
12686                    "slashes.at."
12687                    "any$non-"
12688                    "alphanumeric%"
12689                    "1111111111characte"
12690                    "rs\"",
12691                    getLLVMStyleWithColumns(20)));
12692 
12693   // Verify that splitting the strings understands
12694   // Style::AlwaysBreakBeforeMultilineStrings.
12695   EXPECT_EQ("aaaaaaaaaaaa(\n"
12696             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
12697             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
12698             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
12699                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
12700                    "aaaaaaaaaaaaaaaaaaaaaa\");",
12701                    getGoogleStyle()));
12702   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12703             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
12704             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
12705                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
12706                    "aaaaaaaaaaaaaaaaaaaaaa\";",
12707                    getGoogleStyle()));
12708   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12709             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
12710             format("llvm::outs() << "
12711                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
12712                    "aaaaaaaaaaaaaaaaaaa\";"));
12713   EXPECT_EQ("ffff(\n"
12714             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
12715             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
12716             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
12717                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
12718                    getGoogleStyle()));
12719 
12720   FormatStyle Style = getLLVMStyleWithColumns(12);
12721   Style.BreakStringLiterals = false;
12722   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
12723 
12724   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
12725   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
12726   EXPECT_EQ("#define A \\\n"
12727             "  \"some \" \\\n"
12728             "  \"text \" \\\n"
12729             "  \"other\";",
12730             format("#define A \"some text other\";", AlignLeft));
12731 }
12732 
TEST_F(FormatTest,BreaksStringLiteralsAtColumnLimit)12733 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
12734   EXPECT_EQ("C a = \"some more \"\n"
12735             "      \"text\";",
12736             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
12737 }
12738 
TEST_F(FormatTest,FullyRemoveEmptyLines)12739 TEST_F(FormatTest, FullyRemoveEmptyLines) {
12740   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
12741   NoEmptyLines.MaxEmptyLinesToKeep = 0;
12742   EXPECT_EQ("int i = a(b());",
12743             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
12744 }
12745 
TEST_F(FormatTest,BreaksStringLiteralsWithTabs)12746 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
12747   EXPECT_EQ(
12748       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
12749       "(\n"
12750       "    \"x\t\");",
12751       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
12752              "aaaaaaa("
12753              "\"x\t\");"));
12754 }
12755 
TEST_F(FormatTest,BreaksWideAndNSStringLiterals)12756 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
12757   EXPECT_EQ(
12758       "u8\"utf8 string \"\n"
12759       "u8\"literal\";",
12760       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
12761   EXPECT_EQ(
12762       "u\"utf16 string \"\n"
12763       "u\"literal\";",
12764       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
12765   EXPECT_EQ(
12766       "U\"utf32 string \"\n"
12767       "U\"literal\";",
12768       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
12769   EXPECT_EQ("L\"wide string \"\n"
12770             "L\"literal\";",
12771             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
12772   EXPECT_EQ("@\"NSString \"\n"
12773             "@\"literal\";",
12774             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
12775   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
12776 
12777   // This input makes clang-format try to split the incomplete unicode escape
12778   // sequence, which used to lead to a crasher.
12779   verifyNoCrash(
12780       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
12781       getLLVMStyleWithColumns(60));
12782 }
12783 
TEST_F(FormatTest,DoesNotBreakRawStringLiterals)12784 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
12785   FormatStyle Style = getGoogleStyleWithColumns(15);
12786   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
12787   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
12788   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
12789   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
12790   EXPECT_EQ("u8R\"x(raw literal)x\";",
12791             format("u8R\"x(raw literal)x\";", Style));
12792 }
12793 
TEST_F(FormatTest,BreaksStringLiteralsWithin_TMacro)12794 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
12795   FormatStyle Style = getLLVMStyleWithColumns(20);
12796   EXPECT_EQ(
12797       "_T(\"aaaaaaaaaaaaaa\")\n"
12798       "_T(\"aaaaaaaaaaaaaa\")\n"
12799       "_T(\"aaaaaaaaaaaa\")",
12800       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
12801   EXPECT_EQ("f(x,\n"
12802             "  _T(\"aaaaaaaaaaaa\")\n"
12803             "  _T(\"aaa\"),\n"
12804             "  z);",
12805             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
12806 
12807   // FIXME: Handle embedded spaces in one iteration.
12808   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
12809   //            "_T(\"aaaaaaaaaaaaa\")\n"
12810   //            "_T(\"aaaaaaaaaaaaa\")\n"
12811   //            "_T(\"a\")",
12812   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
12813   //                   getLLVMStyleWithColumns(20)));
12814   EXPECT_EQ(
12815       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
12816       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
12817   EXPECT_EQ("f(\n"
12818             "#if !TEST\n"
12819             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
12820             "#endif\n"
12821             ");",
12822             format("f(\n"
12823                    "#if !TEST\n"
12824                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
12825                    "#endif\n"
12826                    ");"));
12827   EXPECT_EQ("f(\n"
12828             "\n"
12829             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
12830             format("f(\n"
12831                    "\n"
12832                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
12833 }
12834 
TEST_F(FormatTest,BreaksStringLiteralOperands)12835 TEST_F(FormatTest, BreaksStringLiteralOperands) {
12836   // In a function call with two operands, the second can be broken with no line
12837   // break before it.
12838   EXPECT_EQ(
12839       "func(a, \"long long \"\n"
12840       "        \"long long\");",
12841       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
12842   // In a function call with three operands, the second must be broken with a
12843   // line break before it.
12844   EXPECT_EQ("func(a,\n"
12845             "     \"long long long \"\n"
12846             "     \"long\",\n"
12847             "     c);",
12848             format("func(a, \"long long long long\", c);",
12849                    getLLVMStyleWithColumns(24)));
12850   // In a function call with three operands, the third must be broken with a
12851   // line break before it.
12852   EXPECT_EQ("func(a, b,\n"
12853             "     \"long long long \"\n"
12854             "     \"long\");",
12855             format("func(a, b, \"long long long long\");",
12856                    getLLVMStyleWithColumns(24)));
12857   // In a function call with three operands, both the second and the third must
12858   // be broken with a line break before them.
12859   EXPECT_EQ("func(a,\n"
12860             "     \"long long long \"\n"
12861             "     \"long\",\n"
12862             "     \"long long long \"\n"
12863             "     \"long\");",
12864             format("func(a, \"long long long long\", \"long long long long\");",
12865                    getLLVMStyleWithColumns(24)));
12866   // In a chain of << with two operands, the second can be broken with no line
12867   // break before it.
12868   EXPECT_EQ("a << \"line line \"\n"
12869             "     \"line\";",
12870             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
12871   // In a chain of << with three operands, the second can be broken with no line
12872   // break before it.
12873   EXPECT_EQ(
12874       "abcde << \"line \"\n"
12875       "         \"line line\"\n"
12876       "      << c;",
12877       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
12878   // In a chain of << with three operands, the third must be broken with a line
12879   // break before it.
12880   EXPECT_EQ(
12881       "a << b\n"
12882       "  << \"line line \"\n"
12883       "     \"line\";",
12884       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
12885   // In a chain of << with three operands, the second can be broken with no line
12886   // break before it and the third must be broken with a line break before it.
12887   EXPECT_EQ("abcd << \"line line \"\n"
12888             "        \"line\"\n"
12889             "     << \"line line \"\n"
12890             "        \"line\";",
12891             format("abcd << \"line line line\" << \"line line line\";",
12892                    getLLVMStyleWithColumns(20)));
12893   // In a chain of binary operators with two operands, the second can be broken
12894   // with no line break before it.
12895   EXPECT_EQ(
12896       "abcd + \"line line \"\n"
12897       "       \"line line\";",
12898       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
12899   // In a chain of binary operators with three operands, the second must be
12900   // broken with a line break before it.
12901   EXPECT_EQ("abcd +\n"
12902             "    \"line line \"\n"
12903             "    \"line line\" +\n"
12904             "    e;",
12905             format("abcd + \"line line line line\" + e;",
12906                    getLLVMStyleWithColumns(20)));
12907   // In a function call with two operands, with AlignAfterOpenBracket enabled,
12908   // the first must be broken with a line break before it.
12909   FormatStyle Style = getLLVMStyleWithColumns(25);
12910   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
12911   EXPECT_EQ("someFunction(\n"
12912             "    \"long long long \"\n"
12913             "    \"long\",\n"
12914             "    a);",
12915             format("someFunction(\"long long long long\", a);", Style));
12916 }
12917 
TEST_F(FormatTest,DontSplitStringLiteralsWithEscapedNewlines)12918 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
12919   EXPECT_EQ(
12920       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12921       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12922       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
12923       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12924              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
12925              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
12926 }
12927 
TEST_F(FormatTest,CountsCharactersInMultilineRawStringLiterals)12928 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
12929   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
12930             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
12931   EXPECT_EQ("fffffffffff(g(R\"x(\n"
12932             "multiline raw string literal xxxxxxxxxxxxxx\n"
12933             ")x\",\n"
12934             "              a),\n"
12935             "            b);",
12936             format("fffffffffff(g(R\"x(\n"
12937                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12938                    ")x\", a), b);",
12939                    getGoogleStyleWithColumns(20)));
12940   EXPECT_EQ("fffffffffff(\n"
12941             "    g(R\"x(qqq\n"
12942             "multiline raw string literal xxxxxxxxxxxxxx\n"
12943             ")x\",\n"
12944             "      a),\n"
12945             "    b);",
12946             format("fffffffffff(g(R\"x(qqq\n"
12947                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12948                    ")x\", a), b);",
12949                    getGoogleStyleWithColumns(20)));
12950 
12951   EXPECT_EQ("fffffffffff(R\"x(\n"
12952             "multiline raw string literal xxxxxxxxxxxxxx\n"
12953             ")x\");",
12954             format("fffffffffff(R\"x(\n"
12955                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12956                    ")x\");",
12957                    getGoogleStyleWithColumns(20)));
12958   EXPECT_EQ("fffffffffff(R\"x(\n"
12959             "multiline raw string literal xxxxxxxxxxxxxx\n"
12960             ")x\" + bbbbbb);",
12961             format("fffffffffff(R\"x(\n"
12962                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12963                    ")x\" +   bbbbbb);",
12964                    getGoogleStyleWithColumns(20)));
12965   EXPECT_EQ("fffffffffff(\n"
12966             "    R\"x(\n"
12967             "multiline raw string literal xxxxxxxxxxxxxx\n"
12968             ")x\" +\n"
12969             "    bbbbbb);",
12970             format("fffffffffff(\n"
12971                    " R\"x(\n"
12972                    "multiline raw string literal xxxxxxxxxxxxxx\n"
12973                    ")x\" + bbbbbb);",
12974                    getGoogleStyleWithColumns(20)));
12975   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
12976             format("fffffffffff(\n"
12977                    " R\"(single line raw string)\" + bbbbbb);"));
12978 }
12979 
TEST_F(FormatTest,SkipsUnknownStringLiterals)12980 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
12981   verifyFormat("string a = \"unterminated;");
12982   EXPECT_EQ("function(\"unterminated,\n"
12983             "         OtherParameter);",
12984             format("function(  \"unterminated,\n"
12985                    "    OtherParameter);"));
12986 }
12987 
TEST_F(FormatTest,DoesNotTryToParseUDLiteralsInPreCpp11Code)12988 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
12989   FormatStyle Style = getLLVMStyle();
12990   Style.Standard = FormatStyle::LS_Cpp03;
12991   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
12992             format("#define x(_a) printf(\"foo\"_a);", Style));
12993 }
12994 
TEST_F(FormatTest,CppLexVersion)12995 TEST_F(FormatTest, CppLexVersion) {
12996   FormatStyle Style = getLLVMStyle();
12997   // Formatting of x * y differs if x is a type.
12998   verifyFormat("void foo() { MACRO(a * b); }", Style);
12999   verifyFormat("void foo() { MACRO(int *b); }", Style);
13000 
13001   // LLVM style uses latest lexer.
13002   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
13003   Style.Standard = FormatStyle::LS_Cpp17;
13004   // But in c++17, char8_t isn't a keyword.
13005   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
13006 }
13007 
TEST_F(FormatTest,UnderstandsCpp1y)13008 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
13009 
TEST_F(FormatTest,BreakStringLiteralsBeforeUnbreakableTokenSequence)13010 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
13011   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
13012             "             \"ddeeefff\");",
13013             format("someFunction(\"aaabbbcccdddeeefff\");",
13014                    getLLVMStyleWithColumns(25)));
13015   EXPECT_EQ("someFunction1234567890(\n"
13016             "    \"aaabbbcccdddeeefff\");",
13017             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13018                    getLLVMStyleWithColumns(26)));
13019   EXPECT_EQ("someFunction1234567890(\n"
13020             "    \"aaabbbcccdddeeeff\"\n"
13021             "    \"f\");",
13022             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13023                    getLLVMStyleWithColumns(25)));
13024   EXPECT_EQ("someFunction1234567890(\n"
13025             "    \"aaabbbcccdddeeeff\"\n"
13026             "    \"f\");",
13027             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
13028                    getLLVMStyleWithColumns(24)));
13029   EXPECT_EQ("someFunction(\n"
13030             "    \"aaabbbcc ddde \"\n"
13031             "    \"efff\");",
13032             format("someFunction(\"aaabbbcc ddde efff\");",
13033                    getLLVMStyleWithColumns(25)));
13034   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
13035             "             \"ddeeefff\");",
13036             format("someFunction(\"aaabbbccc ddeeefff\");",
13037                    getLLVMStyleWithColumns(25)));
13038   EXPECT_EQ("someFunction1234567890(\n"
13039             "    \"aaabb \"\n"
13040             "    \"cccdddeeefff\");",
13041             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
13042                    getLLVMStyleWithColumns(25)));
13043   EXPECT_EQ("#define A          \\\n"
13044             "  string s =       \\\n"
13045             "      \"123456789\"  \\\n"
13046             "      \"0\";         \\\n"
13047             "  int i;",
13048             format("#define A string s = \"1234567890\"; int i;",
13049                    getLLVMStyleWithColumns(20)));
13050   EXPECT_EQ("someFunction(\n"
13051             "    \"aaabbbcc \"\n"
13052             "    \"dddeeefff\");",
13053             format("someFunction(\"aaabbbcc dddeeefff\");",
13054                    getLLVMStyleWithColumns(25)));
13055 }
13056 
TEST_F(FormatTest,DoNotBreakStringLiteralsInEscapeSequence)13057 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
13058   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
13059   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
13060   EXPECT_EQ("\"test\"\n"
13061             "\"\\n\"",
13062             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
13063   EXPECT_EQ("\"tes\\\\\"\n"
13064             "\"n\"",
13065             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
13066   EXPECT_EQ("\"\\\\\\\\\"\n"
13067             "\"\\n\"",
13068             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
13069   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
13070   EXPECT_EQ("\"\\uff01\"\n"
13071             "\"test\"",
13072             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
13073   EXPECT_EQ("\"\\Uff01ff02\"",
13074             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
13075   EXPECT_EQ("\"\\x000000000001\"\n"
13076             "\"next\"",
13077             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
13078   EXPECT_EQ("\"\\x000000000001next\"",
13079             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
13080   EXPECT_EQ("\"\\x000000000001\"",
13081             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
13082   EXPECT_EQ("\"test\"\n"
13083             "\"\\000000\"\n"
13084             "\"000001\"",
13085             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
13086   EXPECT_EQ("\"test\\000\"\n"
13087             "\"00000000\"\n"
13088             "\"1\"",
13089             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
13090 }
13091 
TEST_F(FormatTest,DoNotCreateUnreasonableUnwrappedLines)13092 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
13093   verifyFormat("void f() {\n"
13094                "  return g() {}\n"
13095                "  void h() {}");
13096   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
13097                "g();\n"
13098                "}");
13099 }
13100 
TEST_F(FormatTest,DoNotPrematurelyEndUnwrappedLineForReturnStatements)13101 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
13102   verifyFormat(
13103       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
13104 }
13105 
TEST_F(FormatTest,FormatsClosingBracesInEmptyNestedBlocks)13106 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
13107   verifyFormat("class X {\n"
13108                "  void f() {\n"
13109                "  }\n"
13110                "};",
13111                getLLVMStyleWithColumns(12));
13112 }
13113 
TEST_F(FormatTest,ConfigurableIndentWidth)13114 TEST_F(FormatTest, ConfigurableIndentWidth) {
13115   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
13116   EightIndent.IndentWidth = 8;
13117   EightIndent.ContinuationIndentWidth = 8;
13118   verifyFormat("void f() {\n"
13119                "        someFunction();\n"
13120                "        if (true) {\n"
13121                "                f();\n"
13122                "        }\n"
13123                "}",
13124                EightIndent);
13125   verifyFormat("class X {\n"
13126                "        void f() {\n"
13127                "        }\n"
13128                "};",
13129                EightIndent);
13130   verifyFormat("int x[] = {\n"
13131                "        call(),\n"
13132                "        call()};",
13133                EightIndent);
13134 }
13135 
TEST_F(FormatTest,ConfigurableFunctionDeclarationIndentAfterType)13136 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
13137   verifyFormat("double\n"
13138                "f();",
13139                getLLVMStyleWithColumns(8));
13140 }
13141 
TEST_F(FormatTest,ConfigurableUseOfTab)13142 TEST_F(FormatTest, ConfigurableUseOfTab) {
13143   FormatStyle Tab = getLLVMStyleWithColumns(42);
13144   Tab.IndentWidth = 8;
13145   Tab.UseTab = FormatStyle::UT_Always;
13146   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13147 
13148   EXPECT_EQ("if (aaaaaaaa && // q\n"
13149             "    bb)\t\t// w\n"
13150             "\t;",
13151             format("if (aaaaaaaa &&// q\n"
13152                    "bb)// w\n"
13153                    ";",
13154                    Tab));
13155   EXPECT_EQ("if (aaa && bbb) // w\n"
13156             "\t;",
13157             format("if(aaa&&bbb)// w\n"
13158                    ";",
13159                    Tab));
13160 
13161   verifyFormat("class X {\n"
13162                "\tvoid f() {\n"
13163                "\t\tsomeFunction(parameter1,\n"
13164                "\t\t\t     parameter2);\n"
13165                "\t}\n"
13166                "};",
13167                Tab);
13168   verifyFormat("#define A                        \\\n"
13169                "\tvoid f() {               \\\n"
13170                "\t\tsomeFunction(    \\\n"
13171                "\t\t    parameter1,  \\\n"
13172                "\t\t    parameter2); \\\n"
13173                "\t}",
13174                Tab);
13175   verifyFormat("int a;\t      // x\n"
13176                "int bbbbbbbb; // x\n",
13177                Tab);
13178 
13179   Tab.TabWidth = 4;
13180   Tab.IndentWidth = 8;
13181   verifyFormat("class TabWidth4Indent8 {\n"
13182                "\t\tvoid f() {\n"
13183                "\t\t\t\tsomeFunction(parameter1,\n"
13184                "\t\t\t\t\t\t\t parameter2);\n"
13185                "\t\t}\n"
13186                "};",
13187                Tab);
13188 
13189   Tab.TabWidth = 4;
13190   Tab.IndentWidth = 4;
13191   verifyFormat("class TabWidth4Indent4 {\n"
13192                "\tvoid f() {\n"
13193                "\t\tsomeFunction(parameter1,\n"
13194                "\t\t\t\t\t parameter2);\n"
13195                "\t}\n"
13196                "};",
13197                Tab);
13198 
13199   Tab.TabWidth = 8;
13200   Tab.IndentWidth = 4;
13201   verifyFormat("class TabWidth8Indent4 {\n"
13202                "    void f() {\n"
13203                "\tsomeFunction(parameter1,\n"
13204                "\t\t     parameter2);\n"
13205                "    }\n"
13206                "};",
13207                Tab);
13208 
13209   Tab.TabWidth = 8;
13210   Tab.IndentWidth = 8;
13211   EXPECT_EQ("/*\n"
13212             "\t      a\t\tcomment\n"
13213             "\t      in multiple lines\n"
13214             "       */",
13215             format("   /*\t \t \n"
13216                    " \t \t a\t\tcomment\t \t\n"
13217                    " \t \t in multiple lines\t\n"
13218                    " \t  */",
13219                    Tab));
13220 
13221   Tab.UseTab = FormatStyle::UT_ForIndentation;
13222   verifyFormat("{\n"
13223                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13224                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13225                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13226                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13227                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13228                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13229                "};",
13230                Tab);
13231   verifyFormat("enum AA {\n"
13232                "\ta1, // Force multiple lines\n"
13233                "\ta2,\n"
13234                "\ta3\n"
13235                "};",
13236                Tab);
13237   EXPECT_EQ("if (aaaaaaaa && // q\n"
13238             "    bb)         // w\n"
13239             "\t;",
13240             format("if (aaaaaaaa &&// q\n"
13241                    "bb)// w\n"
13242                    ";",
13243                    Tab));
13244   verifyFormat("class X {\n"
13245                "\tvoid f() {\n"
13246                "\t\tsomeFunction(parameter1,\n"
13247                "\t\t             parameter2);\n"
13248                "\t}\n"
13249                "};",
13250                Tab);
13251   verifyFormat("{\n"
13252                "\tQ(\n"
13253                "\t    {\n"
13254                "\t\t    int a;\n"
13255                "\t\t    someFunction(aaaaaaaa,\n"
13256                "\t\t                 bbbbbbb);\n"
13257                "\t    },\n"
13258                "\t    p);\n"
13259                "}",
13260                Tab);
13261   EXPECT_EQ("{\n"
13262             "\t/* aaaa\n"
13263             "\t   bbbb */\n"
13264             "}",
13265             format("{\n"
13266                    "/* aaaa\n"
13267                    "   bbbb */\n"
13268                    "}",
13269                    Tab));
13270   EXPECT_EQ("{\n"
13271             "\t/*\n"
13272             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13273             "\t  bbbbbbbbbbbbb\n"
13274             "\t*/\n"
13275             "}",
13276             format("{\n"
13277                    "/*\n"
13278                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13279                    "*/\n"
13280                    "}",
13281                    Tab));
13282   EXPECT_EQ("{\n"
13283             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13284             "\t// bbbbbbbbbbbbb\n"
13285             "}",
13286             format("{\n"
13287                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13288                    "}",
13289                    Tab));
13290   EXPECT_EQ("{\n"
13291             "\t/*\n"
13292             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13293             "\t  bbbbbbbbbbbbb\n"
13294             "\t*/\n"
13295             "}",
13296             format("{\n"
13297                    "\t/*\n"
13298                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13299                    "\t*/\n"
13300                    "}",
13301                    Tab));
13302   EXPECT_EQ("{\n"
13303             "\t/*\n"
13304             "\n"
13305             "\t*/\n"
13306             "}",
13307             format("{\n"
13308                    "\t/*\n"
13309                    "\n"
13310                    "\t*/\n"
13311                    "}",
13312                    Tab));
13313   EXPECT_EQ("{\n"
13314             "\t/*\n"
13315             " asdf\n"
13316             "\t*/\n"
13317             "}",
13318             format("{\n"
13319                    "\t/*\n"
13320                    " asdf\n"
13321                    "\t*/\n"
13322                    "}",
13323                    Tab));
13324 
13325   Tab.UseTab = FormatStyle::UT_Never;
13326   EXPECT_EQ("/*\n"
13327             "              a\t\tcomment\n"
13328             "              in multiple lines\n"
13329             "       */",
13330             format("   /*\t \t \n"
13331                    " \t \t a\t\tcomment\t \t\n"
13332                    " \t \t in multiple lines\t\n"
13333                    " \t  */",
13334                    Tab));
13335   EXPECT_EQ("/* some\n"
13336             "   comment */",
13337             format(" \t \t /* some\n"
13338                    " \t \t    comment */",
13339                    Tab));
13340   EXPECT_EQ("int a; /* some\n"
13341             "   comment */",
13342             format(" \t \t int a; /* some\n"
13343                    " \t \t    comment */",
13344                    Tab));
13345 
13346   EXPECT_EQ("int a; /* some\n"
13347             "comment */",
13348             format(" \t \t int\ta; /* some\n"
13349                    " \t \t    comment */",
13350                    Tab));
13351   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13352             "    comment */",
13353             format(" \t \t f(\"\t\t\"); /* some\n"
13354                    " \t \t    comment */",
13355                    Tab));
13356   EXPECT_EQ("{\n"
13357             "        /*\n"
13358             "         * Comment\n"
13359             "         */\n"
13360             "        int i;\n"
13361             "}",
13362             format("{\n"
13363                    "\t/*\n"
13364                    "\t * Comment\n"
13365                    "\t */\n"
13366                    "\t int i;\n"
13367                    "}",
13368                    Tab));
13369 
13370   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
13371   Tab.TabWidth = 8;
13372   Tab.IndentWidth = 8;
13373   EXPECT_EQ("if (aaaaaaaa && // q\n"
13374             "    bb)         // w\n"
13375             "\t;",
13376             format("if (aaaaaaaa &&// q\n"
13377                    "bb)// w\n"
13378                    ";",
13379                    Tab));
13380   EXPECT_EQ("if (aaa && bbb) // w\n"
13381             "\t;",
13382             format("if(aaa&&bbb)// w\n"
13383                    ";",
13384                    Tab));
13385   verifyFormat("class X {\n"
13386                "\tvoid f() {\n"
13387                "\t\tsomeFunction(parameter1,\n"
13388                "\t\t\t     parameter2);\n"
13389                "\t}\n"
13390                "};",
13391                Tab);
13392   verifyFormat("#define A                        \\\n"
13393                "\tvoid f() {               \\\n"
13394                "\t\tsomeFunction(    \\\n"
13395                "\t\t    parameter1,  \\\n"
13396                "\t\t    parameter2); \\\n"
13397                "\t}",
13398                Tab);
13399   Tab.TabWidth = 4;
13400   Tab.IndentWidth = 8;
13401   verifyFormat("class TabWidth4Indent8 {\n"
13402                "\t\tvoid f() {\n"
13403                "\t\t\t\tsomeFunction(parameter1,\n"
13404                "\t\t\t\t\t\t\t parameter2);\n"
13405                "\t\t}\n"
13406                "};",
13407                Tab);
13408   Tab.TabWidth = 4;
13409   Tab.IndentWidth = 4;
13410   verifyFormat("class TabWidth4Indent4 {\n"
13411                "\tvoid f() {\n"
13412                "\t\tsomeFunction(parameter1,\n"
13413                "\t\t\t\t\t parameter2);\n"
13414                "\t}\n"
13415                "};",
13416                Tab);
13417   Tab.TabWidth = 8;
13418   Tab.IndentWidth = 4;
13419   verifyFormat("class TabWidth8Indent4 {\n"
13420                "    void f() {\n"
13421                "\tsomeFunction(parameter1,\n"
13422                "\t\t     parameter2);\n"
13423                "    }\n"
13424                "};",
13425                Tab);
13426   Tab.TabWidth = 8;
13427   Tab.IndentWidth = 8;
13428   EXPECT_EQ("/*\n"
13429             "\t      a\t\tcomment\n"
13430             "\t      in multiple lines\n"
13431             "       */",
13432             format("   /*\t \t \n"
13433                    " \t \t a\t\tcomment\t \t\n"
13434                    " \t \t in multiple lines\t\n"
13435                    " \t  */",
13436                    Tab));
13437   verifyFormat("{\n"
13438                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13439                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13440                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13441                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13442                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13443                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13444                "};",
13445                Tab);
13446   verifyFormat("enum AA {\n"
13447                "\ta1, // Force multiple lines\n"
13448                "\ta2,\n"
13449                "\ta3\n"
13450                "};",
13451                Tab);
13452   EXPECT_EQ("if (aaaaaaaa && // q\n"
13453             "    bb)         // w\n"
13454             "\t;",
13455             format("if (aaaaaaaa &&// q\n"
13456                    "bb)// w\n"
13457                    ";",
13458                    Tab));
13459   verifyFormat("class X {\n"
13460                "\tvoid f() {\n"
13461                "\t\tsomeFunction(parameter1,\n"
13462                "\t\t\t     parameter2);\n"
13463                "\t}\n"
13464                "};",
13465                Tab);
13466   verifyFormat("{\n"
13467                "\tQ(\n"
13468                "\t    {\n"
13469                "\t\t    int a;\n"
13470                "\t\t    someFunction(aaaaaaaa,\n"
13471                "\t\t\t\t bbbbbbb);\n"
13472                "\t    },\n"
13473                "\t    p);\n"
13474                "}",
13475                Tab);
13476   EXPECT_EQ("{\n"
13477             "\t/* aaaa\n"
13478             "\t   bbbb */\n"
13479             "}",
13480             format("{\n"
13481                    "/* aaaa\n"
13482                    "   bbbb */\n"
13483                    "}",
13484                    Tab));
13485   EXPECT_EQ("{\n"
13486             "\t/*\n"
13487             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13488             "\t  bbbbbbbbbbbbb\n"
13489             "\t*/\n"
13490             "}",
13491             format("{\n"
13492                    "/*\n"
13493                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13494                    "*/\n"
13495                    "}",
13496                    Tab));
13497   EXPECT_EQ("{\n"
13498             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13499             "\t// bbbbbbbbbbbbb\n"
13500             "}",
13501             format("{\n"
13502                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13503                    "}",
13504                    Tab));
13505   EXPECT_EQ("{\n"
13506             "\t/*\n"
13507             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13508             "\t  bbbbbbbbbbbbb\n"
13509             "\t*/\n"
13510             "}",
13511             format("{\n"
13512                    "\t/*\n"
13513                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13514                    "\t*/\n"
13515                    "}",
13516                    Tab));
13517   EXPECT_EQ("{\n"
13518             "\t/*\n"
13519             "\n"
13520             "\t*/\n"
13521             "}",
13522             format("{\n"
13523                    "\t/*\n"
13524                    "\n"
13525                    "\t*/\n"
13526                    "}",
13527                    Tab));
13528   EXPECT_EQ("{\n"
13529             "\t/*\n"
13530             " asdf\n"
13531             "\t*/\n"
13532             "}",
13533             format("{\n"
13534                    "\t/*\n"
13535                    " asdf\n"
13536                    "\t*/\n"
13537                    "}",
13538                    Tab));
13539   EXPECT_EQ("/* some\n"
13540             "   comment */",
13541             format(" \t \t /* some\n"
13542                    " \t \t    comment */",
13543                    Tab));
13544   EXPECT_EQ("int a; /* some\n"
13545             "   comment */",
13546             format(" \t \t int a; /* some\n"
13547                    " \t \t    comment */",
13548                    Tab));
13549   EXPECT_EQ("int a; /* some\n"
13550             "comment */",
13551             format(" \t \t int\ta; /* some\n"
13552                    " \t \t    comment */",
13553                    Tab));
13554   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13555             "    comment */",
13556             format(" \t \t f(\"\t\t\"); /* some\n"
13557                    " \t \t    comment */",
13558                    Tab));
13559   EXPECT_EQ("{\n"
13560             "\t/*\n"
13561             "\t * Comment\n"
13562             "\t */\n"
13563             "\tint i;\n"
13564             "}",
13565             format("{\n"
13566                    "\t/*\n"
13567                    "\t * Comment\n"
13568                    "\t */\n"
13569                    "\t int i;\n"
13570                    "}",
13571                    Tab));
13572   Tab.TabWidth = 2;
13573   Tab.IndentWidth = 2;
13574   EXPECT_EQ("{\n"
13575             "\t/* aaaa\n"
13576             "\t\t bbbb */\n"
13577             "}",
13578             format("{\n"
13579                    "/* aaaa\n"
13580                    "\t bbbb */\n"
13581                    "}",
13582                    Tab));
13583   EXPECT_EQ("{\n"
13584             "\t/*\n"
13585             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13586             "\t\tbbbbbbbbbbbbb\n"
13587             "\t*/\n"
13588             "}",
13589             format("{\n"
13590                    "/*\n"
13591                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13592                    "*/\n"
13593                    "}",
13594                    Tab));
13595   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13596   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13597   Tab.TabWidth = 4;
13598   Tab.IndentWidth = 4;
13599   verifyFormat("class Assign {\n"
13600                "\tvoid f() {\n"
13601                "\t\tint         x      = 123;\n"
13602                "\t\tint         random = 4;\n"
13603                "\t\tstd::string alphabet =\n"
13604                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
13605                "\t}\n"
13606                "};",
13607                Tab);
13608 
13609   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
13610   Tab.TabWidth = 8;
13611   Tab.IndentWidth = 8;
13612   EXPECT_EQ("if (aaaaaaaa && // q\n"
13613             "    bb)         // w\n"
13614             "\t;",
13615             format("if (aaaaaaaa &&// q\n"
13616                    "bb)// w\n"
13617                    ";",
13618                    Tab));
13619   EXPECT_EQ("if (aaa && bbb) // w\n"
13620             "\t;",
13621             format("if(aaa&&bbb)// w\n"
13622                    ";",
13623                    Tab));
13624   verifyFormat("class X {\n"
13625                "\tvoid f() {\n"
13626                "\t\tsomeFunction(parameter1,\n"
13627                "\t\t             parameter2);\n"
13628                "\t}\n"
13629                "};",
13630                Tab);
13631   verifyFormat("#define A                        \\\n"
13632                "\tvoid f() {               \\\n"
13633                "\t\tsomeFunction(    \\\n"
13634                "\t\t    parameter1,  \\\n"
13635                "\t\t    parameter2); \\\n"
13636                "\t}",
13637                Tab);
13638   Tab.TabWidth = 4;
13639   Tab.IndentWidth = 8;
13640   verifyFormat("class TabWidth4Indent8 {\n"
13641                "\t\tvoid f() {\n"
13642                "\t\t\t\tsomeFunction(parameter1,\n"
13643                "\t\t\t\t             parameter2);\n"
13644                "\t\t}\n"
13645                "};",
13646                Tab);
13647   Tab.TabWidth = 4;
13648   Tab.IndentWidth = 4;
13649   verifyFormat("class TabWidth4Indent4 {\n"
13650                "\tvoid f() {\n"
13651                "\t\tsomeFunction(parameter1,\n"
13652                "\t\t             parameter2);\n"
13653                "\t}\n"
13654                "};",
13655                Tab);
13656   Tab.TabWidth = 8;
13657   Tab.IndentWidth = 4;
13658   verifyFormat("class TabWidth8Indent4 {\n"
13659                "    void f() {\n"
13660                "\tsomeFunction(parameter1,\n"
13661                "\t             parameter2);\n"
13662                "    }\n"
13663                "};",
13664                Tab);
13665   Tab.TabWidth = 8;
13666   Tab.IndentWidth = 8;
13667   EXPECT_EQ("/*\n"
13668             "              a\t\tcomment\n"
13669             "              in multiple lines\n"
13670             "       */",
13671             format("   /*\t \t \n"
13672                    " \t \t a\t\tcomment\t \t\n"
13673                    " \t \t in multiple lines\t\n"
13674                    " \t  */",
13675                    Tab));
13676   verifyFormat("{\n"
13677                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13678                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13679                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13680                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13681                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13682                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
13683                "};",
13684                Tab);
13685   verifyFormat("enum AA {\n"
13686                "\ta1, // Force multiple lines\n"
13687                "\ta2,\n"
13688                "\ta3\n"
13689                "};",
13690                Tab);
13691   EXPECT_EQ("if (aaaaaaaa && // q\n"
13692             "    bb)         // w\n"
13693             "\t;",
13694             format("if (aaaaaaaa &&// q\n"
13695                    "bb)// w\n"
13696                    ";",
13697                    Tab));
13698   verifyFormat("class X {\n"
13699                "\tvoid f() {\n"
13700                "\t\tsomeFunction(parameter1,\n"
13701                "\t\t             parameter2);\n"
13702                "\t}\n"
13703                "};",
13704                Tab);
13705   verifyFormat("{\n"
13706                "\tQ(\n"
13707                "\t    {\n"
13708                "\t\t    int a;\n"
13709                "\t\t    someFunction(aaaaaaaa,\n"
13710                "\t\t                 bbbbbbb);\n"
13711                "\t    },\n"
13712                "\t    p);\n"
13713                "}",
13714                Tab);
13715   EXPECT_EQ("{\n"
13716             "\t/* aaaa\n"
13717             "\t   bbbb */\n"
13718             "}",
13719             format("{\n"
13720                    "/* aaaa\n"
13721                    "   bbbb */\n"
13722                    "}",
13723                    Tab));
13724   EXPECT_EQ("{\n"
13725             "\t/*\n"
13726             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13727             "\t  bbbbbbbbbbbbb\n"
13728             "\t*/\n"
13729             "}",
13730             format("{\n"
13731                    "/*\n"
13732                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13733                    "*/\n"
13734                    "}",
13735                    Tab));
13736   EXPECT_EQ("{\n"
13737             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13738             "\t// bbbbbbbbbbbbb\n"
13739             "}",
13740             format("{\n"
13741                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13742                    "}",
13743                    Tab));
13744   EXPECT_EQ("{\n"
13745             "\t/*\n"
13746             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13747             "\t  bbbbbbbbbbbbb\n"
13748             "\t*/\n"
13749             "}",
13750             format("{\n"
13751                    "\t/*\n"
13752                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13753                    "\t*/\n"
13754                    "}",
13755                    Tab));
13756   EXPECT_EQ("{\n"
13757             "\t/*\n"
13758             "\n"
13759             "\t*/\n"
13760             "}",
13761             format("{\n"
13762                    "\t/*\n"
13763                    "\n"
13764                    "\t*/\n"
13765                    "}",
13766                    Tab));
13767   EXPECT_EQ("{\n"
13768             "\t/*\n"
13769             " asdf\n"
13770             "\t*/\n"
13771             "}",
13772             format("{\n"
13773                    "\t/*\n"
13774                    " asdf\n"
13775                    "\t*/\n"
13776                    "}",
13777                    Tab));
13778   EXPECT_EQ("/* some\n"
13779             "   comment */",
13780             format(" \t \t /* some\n"
13781                    " \t \t    comment */",
13782                    Tab));
13783   EXPECT_EQ("int a; /* some\n"
13784             "   comment */",
13785             format(" \t \t int a; /* some\n"
13786                    " \t \t    comment */",
13787                    Tab));
13788   EXPECT_EQ("int a; /* some\n"
13789             "comment */",
13790             format(" \t \t int\ta; /* some\n"
13791                    " \t \t    comment */",
13792                    Tab));
13793   EXPECT_EQ("f(\"\t\t\"); /* some\n"
13794             "    comment */",
13795             format(" \t \t f(\"\t\t\"); /* some\n"
13796                    " \t \t    comment */",
13797                    Tab));
13798   EXPECT_EQ("{\n"
13799             "\t/*\n"
13800             "\t * Comment\n"
13801             "\t */\n"
13802             "\tint i;\n"
13803             "}",
13804             format("{\n"
13805                    "\t/*\n"
13806                    "\t * Comment\n"
13807                    "\t */\n"
13808                    "\t int i;\n"
13809                    "}",
13810                    Tab));
13811   Tab.TabWidth = 2;
13812   Tab.IndentWidth = 2;
13813   EXPECT_EQ("{\n"
13814             "\t/* aaaa\n"
13815             "\t   bbbb */\n"
13816             "}",
13817             format("{\n"
13818                    "/* aaaa\n"
13819                    "   bbbb */\n"
13820                    "}",
13821                    Tab));
13822   EXPECT_EQ("{\n"
13823             "\t/*\n"
13824             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
13825             "\t  bbbbbbbbbbbbb\n"
13826             "\t*/\n"
13827             "}",
13828             format("{\n"
13829                    "/*\n"
13830                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
13831                    "*/\n"
13832                    "}",
13833                    Tab));
13834   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13835   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13836   Tab.TabWidth = 4;
13837   Tab.IndentWidth = 4;
13838   verifyFormat("class Assign {\n"
13839                "\tvoid f() {\n"
13840                "\t\tint         x      = 123;\n"
13841                "\t\tint         random = 4;\n"
13842                "\t\tstd::string alphabet =\n"
13843                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
13844                "\t}\n"
13845                "};",
13846                Tab);
13847   Tab.AlignOperands = FormatStyle::OAS_Align;
13848   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
13849                "                 cccccccccccccccccccc;",
13850                Tab);
13851   // no alignment
13852   verifyFormat("int aaaaaaaaaa =\n"
13853                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
13854                Tab);
13855   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
13856                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
13857                "                        : 333333333333333;",
13858                Tab);
13859   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
13860   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
13861   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
13862                "               + cccccccccccccccccccc;",
13863                Tab);
13864 }
13865 
TEST_F(FormatTest,ZeroTabWidth)13866 TEST_F(FormatTest, ZeroTabWidth) {
13867   FormatStyle Tab = getLLVMStyleWithColumns(42);
13868   Tab.IndentWidth = 8;
13869   Tab.UseTab = FormatStyle::UT_Never;
13870   Tab.TabWidth = 0;
13871   EXPECT_EQ("void a(){\n"
13872             "    // line starts with '\t'\n"
13873             "};",
13874             format("void a(){\n"
13875                    "\t// line starts with '\t'\n"
13876                    "};",
13877                    Tab));
13878 
13879   EXPECT_EQ("void a(){\n"
13880             "    // line starts with '\t'\n"
13881             "};",
13882             format("void a(){\n"
13883                    "\t\t// line starts with '\t'\n"
13884                    "};",
13885                    Tab));
13886 
13887   Tab.UseTab = FormatStyle::UT_ForIndentation;
13888   EXPECT_EQ("void a(){\n"
13889             "    // line starts with '\t'\n"
13890             "};",
13891             format("void a(){\n"
13892                    "\t// line starts with '\t'\n"
13893                    "};",
13894                    Tab));
13895 
13896   EXPECT_EQ("void a(){\n"
13897             "    // line starts with '\t'\n"
13898             "};",
13899             format("void a(){\n"
13900                    "\t\t// line starts with '\t'\n"
13901                    "};",
13902                    Tab));
13903 
13904   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
13905   EXPECT_EQ("void a(){\n"
13906             "    // line starts with '\t'\n"
13907             "};",
13908             format("void a(){\n"
13909                    "\t// line starts with '\t'\n"
13910                    "};",
13911                    Tab));
13912 
13913   EXPECT_EQ("void a(){\n"
13914             "    // line starts with '\t'\n"
13915             "};",
13916             format("void a(){\n"
13917                    "\t\t// line starts with '\t'\n"
13918                    "};",
13919                    Tab));
13920 
13921   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
13922   EXPECT_EQ("void a(){\n"
13923             "    // line starts with '\t'\n"
13924             "};",
13925             format("void a(){\n"
13926                    "\t// line starts with '\t'\n"
13927                    "};",
13928                    Tab));
13929 
13930   EXPECT_EQ("void a(){\n"
13931             "    // line starts with '\t'\n"
13932             "};",
13933             format("void a(){\n"
13934                    "\t\t// line starts with '\t'\n"
13935                    "};",
13936                    Tab));
13937 
13938   Tab.UseTab = FormatStyle::UT_Always;
13939   EXPECT_EQ("void a(){\n"
13940             "// line starts with '\t'\n"
13941             "};",
13942             format("void a(){\n"
13943                    "\t// line starts with '\t'\n"
13944                    "};",
13945                    Tab));
13946 
13947   EXPECT_EQ("void a(){\n"
13948             "// line starts with '\t'\n"
13949             "};",
13950             format("void a(){\n"
13951                    "\t\t// line starts with '\t'\n"
13952                    "};",
13953                    Tab));
13954 }
13955 
TEST_F(FormatTest,CalculatesOriginalColumn)13956 TEST_F(FormatTest, CalculatesOriginalColumn) {
13957   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13958             "q\"; /* some\n"
13959             "       comment */",
13960             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13961                    "q\"; /* some\n"
13962                    "       comment */",
13963                    getLLVMStyle()));
13964   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
13965             "/* some\n"
13966             "   comment */",
13967             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
13968                    " /* some\n"
13969                    "    comment */",
13970                    getLLVMStyle()));
13971   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13972             "qqq\n"
13973             "/* some\n"
13974             "   comment */",
13975             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13976                    "qqq\n"
13977                    " /* some\n"
13978                    "    comment */",
13979                    getLLVMStyle()));
13980   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13981             "wwww; /* some\n"
13982             "         comment */",
13983             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
13984                    "wwww; /* some\n"
13985                    "         comment */",
13986                    getLLVMStyle()));
13987 }
13988 
TEST_F(FormatTest,ConfigurableSpaceBeforeParens)13989 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
13990   FormatStyle NoSpace = getLLVMStyle();
13991   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
13992 
13993   verifyFormat("while(true)\n"
13994                "  continue;",
13995                NoSpace);
13996   verifyFormat("for(;;)\n"
13997                "  continue;",
13998                NoSpace);
13999   verifyFormat("if(true)\n"
14000                "  f();\n"
14001                "else if(true)\n"
14002                "  f();",
14003                NoSpace);
14004   verifyFormat("do {\n"
14005                "  do_something();\n"
14006                "} while(something());",
14007                NoSpace);
14008   verifyFormat("switch(x) {\n"
14009                "default:\n"
14010                "  break;\n"
14011                "}",
14012                NoSpace);
14013   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
14014   verifyFormat("size_t x = sizeof(x);", NoSpace);
14015   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
14016   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
14017   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
14018   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
14019   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
14020   verifyFormat("alignas(128) char a[128];", NoSpace);
14021   verifyFormat("size_t x = alignof(MyType);", NoSpace);
14022   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
14023   verifyFormat("int f() throw(Deprecated);", NoSpace);
14024   verifyFormat("typedef void (*cb)(int);", NoSpace);
14025   verifyFormat("T A::operator()();", NoSpace);
14026   verifyFormat("X A::operator++(T);", NoSpace);
14027   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
14028 
14029   FormatStyle Space = getLLVMStyle();
14030   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
14031 
14032   verifyFormat("int f ();", Space);
14033   verifyFormat("void f (int a, T b) {\n"
14034                "  while (true)\n"
14035                "    continue;\n"
14036                "}",
14037                Space);
14038   verifyFormat("if (true)\n"
14039                "  f ();\n"
14040                "else if (true)\n"
14041                "  f ();",
14042                Space);
14043   verifyFormat("do {\n"
14044                "  do_something ();\n"
14045                "} while (something ());",
14046                Space);
14047   verifyFormat("switch (x) {\n"
14048                "default:\n"
14049                "  break;\n"
14050                "}",
14051                Space);
14052   verifyFormat("A::A () : a (1) {}", Space);
14053   verifyFormat("void f () __attribute__ ((asdf));", Space);
14054   verifyFormat("*(&a + 1);\n"
14055                "&((&a)[1]);\n"
14056                "a[(b + c) * d];\n"
14057                "(((a + 1) * 2) + 3) * 4;",
14058                Space);
14059   verifyFormat("#define A(x) x", Space);
14060   verifyFormat("#define A (x) x", Space);
14061   verifyFormat("#if defined(x)\n"
14062                "#endif",
14063                Space);
14064   verifyFormat("auto i = std::make_unique<int> (5);", Space);
14065   verifyFormat("size_t x = sizeof (x);", Space);
14066   verifyFormat("auto f (int x) -> decltype (x);", Space);
14067   verifyFormat("auto f (int x) -> typeof (x);", Space);
14068   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
14069   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
14070   verifyFormat("int f (T x) noexcept (x.create ());", Space);
14071   verifyFormat("alignas (128) char a[128];", Space);
14072   verifyFormat("size_t x = alignof (MyType);", Space);
14073   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
14074   verifyFormat("int f () throw (Deprecated);", Space);
14075   verifyFormat("typedef void (*cb) (int);", Space);
14076   verifyFormat("T A::operator() ();", Space);
14077   verifyFormat("X A::operator++ (T);", Space);
14078   verifyFormat("auto lambda = [] () { return 0; };", Space);
14079   verifyFormat("int x = int (y);", Space);
14080 
14081   FormatStyle SomeSpace = getLLVMStyle();
14082   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
14083 
14084   verifyFormat("[]() -> float {}", SomeSpace);
14085   verifyFormat("[] (auto foo) {}", SomeSpace);
14086   verifyFormat("[foo]() -> int {}", SomeSpace);
14087   verifyFormat("int f();", SomeSpace);
14088   verifyFormat("void f (int a, T b) {\n"
14089                "  while (true)\n"
14090                "    continue;\n"
14091                "}",
14092                SomeSpace);
14093   verifyFormat("if (true)\n"
14094                "  f();\n"
14095                "else if (true)\n"
14096                "  f();",
14097                SomeSpace);
14098   verifyFormat("do {\n"
14099                "  do_something();\n"
14100                "} while (something());",
14101                SomeSpace);
14102   verifyFormat("switch (x) {\n"
14103                "default:\n"
14104                "  break;\n"
14105                "}",
14106                SomeSpace);
14107   verifyFormat("A::A() : a (1) {}", SomeSpace);
14108   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
14109   verifyFormat("*(&a + 1);\n"
14110                "&((&a)[1]);\n"
14111                "a[(b + c) * d];\n"
14112                "(((a + 1) * 2) + 3) * 4;",
14113                SomeSpace);
14114   verifyFormat("#define A(x) x", SomeSpace);
14115   verifyFormat("#define A (x) x", SomeSpace);
14116   verifyFormat("#if defined(x)\n"
14117                "#endif",
14118                SomeSpace);
14119   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
14120   verifyFormat("size_t x = sizeof (x);", SomeSpace);
14121   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
14122   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
14123   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
14124   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
14125   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
14126   verifyFormat("alignas (128) char a[128];", SomeSpace);
14127   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
14128   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
14129                SomeSpace);
14130   verifyFormat("int f() throw (Deprecated);", SomeSpace);
14131   verifyFormat("typedef void (*cb) (int);", SomeSpace);
14132   verifyFormat("T A::operator()();", SomeSpace);
14133   verifyFormat("X A::operator++ (T);", SomeSpace);
14134   verifyFormat("int x = int (y);", SomeSpace);
14135   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
14136 }
14137 
TEST_F(FormatTest,SpaceAfterLogicalNot)14138 TEST_F(FormatTest, SpaceAfterLogicalNot) {
14139   FormatStyle Spaces = getLLVMStyle();
14140   Spaces.SpaceAfterLogicalNot = true;
14141 
14142   verifyFormat("bool x = ! y", Spaces);
14143   verifyFormat("if (! isFailure())", Spaces);
14144   verifyFormat("if (! (a && b))", Spaces);
14145   verifyFormat("\"Error!\"", Spaces);
14146   verifyFormat("! ! x", Spaces);
14147 }
14148 
TEST_F(FormatTest,ConfigurableSpacesInParentheses)14149 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
14150   FormatStyle Spaces = getLLVMStyle();
14151 
14152   Spaces.SpacesInParentheses = true;
14153   verifyFormat("do_something( ::globalVar );", Spaces);
14154   verifyFormat("call( x, y, z );", Spaces);
14155   verifyFormat("call();", Spaces);
14156   verifyFormat("std::function<void( int, int )> callback;", Spaces);
14157   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
14158                Spaces);
14159   verifyFormat("while ( (bool)1 )\n"
14160                "  continue;",
14161                Spaces);
14162   verifyFormat("for ( ;; )\n"
14163                "  continue;",
14164                Spaces);
14165   verifyFormat("if ( true )\n"
14166                "  f();\n"
14167                "else if ( true )\n"
14168                "  f();",
14169                Spaces);
14170   verifyFormat("do {\n"
14171                "  do_something( (int)i );\n"
14172                "} while ( something() );",
14173                Spaces);
14174   verifyFormat("switch ( x ) {\n"
14175                "default:\n"
14176                "  break;\n"
14177                "}",
14178                Spaces);
14179 
14180   Spaces.SpacesInParentheses = false;
14181   Spaces.SpacesInCStyleCastParentheses = true;
14182   verifyFormat("Type *A = ( Type * )P;", Spaces);
14183   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
14184   verifyFormat("x = ( int32 )y;", Spaces);
14185   verifyFormat("int a = ( int )(2.0f);", Spaces);
14186   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
14187   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
14188   verifyFormat("#define x (( int )-1)", Spaces);
14189 
14190   // Run the first set of tests again with:
14191   Spaces.SpacesInParentheses = false;
14192   Spaces.SpaceInEmptyParentheses = true;
14193   Spaces.SpacesInCStyleCastParentheses = true;
14194   verifyFormat("call(x, y, z);", Spaces);
14195   verifyFormat("call( );", Spaces);
14196   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14197   verifyFormat("while (( bool )1)\n"
14198                "  continue;",
14199                Spaces);
14200   verifyFormat("for (;;)\n"
14201                "  continue;",
14202                Spaces);
14203   verifyFormat("if (true)\n"
14204                "  f( );\n"
14205                "else if (true)\n"
14206                "  f( );",
14207                Spaces);
14208   verifyFormat("do {\n"
14209                "  do_something(( int )i);\n"
14210                "} while (something( ));",
14211                Spaces);
14212   verifyFormat("switch (x) {\n"
14213                "default:\n"
14214                "  break;\n"
14215                "}",
14216                Spaces);
14217 
14218   // Run the first set of tests again with:
14219   Spaces.SpaceAfterCStyleCast = true;
14220   verifyFormat("call(x, y, z);", Spaces);
14221   verifyFormat("call( );", Spaces);
14222   verifyFormat("std::function<void(int, int)> callback;", Spaces);
14223   verifyFormat("while (( bool ) 1)\n"
14224                "  continue;",
14225                Spaces);
14226   verifyFormat("for (;;)\n"
14227                "  continue;",
14228                Spaces);
14229   verifyFormat("if (true)\n"
14230                "  f( );\n"
14231                "else if (true)\n"
14232                "  f( );",
14233                Spaces);
14234   verifyFormat("do {\n"
14235                "  do_something(( int ) i);\n"
14236                "} while (something( ));",
14237                Spaces);
14238   verifyFormat("switch (x) {\n"
14239                "default:\n"
14240                "  break;\n"
14241                "}",
14242                Spaces);
14243 
14244   // Run subset of tests again with:
14245   Spaces.SpacesInCStyleCastParentheses = false;
14246   Spaces.SpaceAfterCStyleCast = true;
14247   verifyFormat("while ((bool) 1)\n"
14248                "  continue;",
14249                Spaces);
14250   verifyFormat("do {\n"
14251                "  do_something((int) i);\n"
14252                "} while (something( ));",
14253                Spaces);
14254 
14255   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
14256   verifyFormat("size_t idx = (size_t) a;", Spaces);
14257   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
14258   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14259   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14260   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14261   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14262   Spaces.ColumnLimit = 80;
14263   Spaces.IndentWidth = 4;
14264   Spaces.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
14265   verifyFormat("void foo( ) {\n"
14266                "    size_t foo = (*(function))(\n"
14267                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14268                "BarrrrrrrrrrrrLong,\n"
14269                "        FoooooooooLooooong);\n"
14270                "}",
14271                Spaces);
14272   Spaces.SpaceAfterCStyleCast = false;
14273   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
14274   verifyFormat("size_t idx = (size_t)a;", Spaces);
14275   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
14276   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
14277   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
14278   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
14279   verifyFormat("size_t idx = (*(foo))(a - 1);", Spaces);
14280 
14281   verifyFormat("void foo( ) {\n"
14282                "    size_t foo = (*(function))(\n"
14283                "        Foooo, Barrrrr, Foooo, Barrrr, FoooooooooLooooong, "
14284                "BarrrrrrrrrrrrLong,\n"
14285                "        FoooooooooLooooong);\n"
14286                "}",
14287                Spaces);
14288 }
14289 
TEST_F(FormatTest,ConfigurableSpacesInSquareBrackets)14290 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
14291   verifyFormat("int a[5];");
14292   verifyFormat("a[3] += 42;");
14293 
14294   FormatStyle Spaces = getLLVMStyle();
14295   Spaces.SpacesInSquareBrackets = true;
14296   // Not lambdas.
14297   verifyFormat("int a[ 5 ];", Spaces);
14298   verifyFormat("a[ 3 ] += 42;", Spaces);
14299   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
14300   verifyFormat("double &operator[](int i) { return 0; }\n"
14301                "int i;",
14302                Spaces);
14303   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
14304   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
14305   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
14306   // Lambdas.
14307   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
14308   verifyFormat("return [ i, args... ] {};", Spaces);
14309   verifyFormat("int foo = [ &bar ]() {};", Spaces);
14310   verifyFormat("int foo = [ = ]() {};", Spaces);
14311   verifyFormat("int foo = [ & ]() {};", Spaces);
14312   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
14313   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
14314 }
14315 
TEST_F(FormatTest,ConfigurableSpaceBeforeBrackets)14316 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
14317   FormatStyle NoSpaceStyle = getLLVMStyle();
14318   verifyFormat("int a[5];", NoSpaceStyle);
14319   verifyFormat("a[3] += 42;", NoSpaceStyle);
14320 
14321   verifyFormat("int a[1];", NoSpaceStyle);
14322   verifyFormat("int 1 [a];", NoSpaceStyle);
14323   verifyFormat("int a[1][2];", NoSpaceStyle);
14324   verifyFormat("a[7] = 5;", NoSpaceStyle);
14325   verifyFormat("int a = (f())[23];", NoSpaceStyle);
14326   verifyFormat("f([] {})", NoSpaceStyle);
14327 
14328   FormatStyle Space = getLLVMStyle();
14329   Space.SpaceBeforeSquareBrackets = true;
14330   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
14331   verifyFormat("return [i, args...] {};", Space);
14332 
14333   verifyFormat("int a [5];", Space);
14334   verifyFormat("a [3] += 42;", Space);
14335   verifyFormat("constexpr char hello []{\"hello\"};", Space);
14336   verifyFormat("double &operator[](int i) { return 0; }\n"
14337                "int i;",
14338                Space);
14339   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
14340   verifyFormat("int i = a [a][a]->f();", Space);
14341   verifyFormat("int i = (*b) [a]->f();", Space);
14342 
14343   verifyFormat("int a [1];", Space);
14344   verifyFormat("int 1 [a];", Space);
14345   verifyFormat("int a [1][2];", Space);
14346   verifyFormat("a [7] = 5;", Space);
14347   verifyFormat("int a = (f()) [23];", Space);
14348   verifyFormat("f([] {})", Space);
14349 }
14350 
TEST_F(FormatTest,ConfigurableSpaceBeforeAssignmentOperators)14351 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
14352   verifyFormat("int a = 5;");
14353   verifyFormat("a += 42;");
14354   verifyFormat("a or_eq 8;");
14355 
14356   FormatStyle Spaces = getLLVMStyle();
14357   Spaces.SpaceBeforeAssignmentOperators = false;
14358   verifyFormat("int a= 5;", Spaces);
14359   verifyFormat("a+= 42;", Spaces);
14360   verifyFormat("a or_eq 8;", Spaces);
14361 }
14362 
TEST_F(FormatTest,ConfigurableSpaceBeforeColon)14363 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
14364   verifyFormat("class Foo : public Bar {};");
14365   verifyFormat("Foo::Foo() : foo(1) {}");
14366   verifyFormat("for (auto a : b) {\n}");
14367   verifyFormat("int x = a ? b : c;");
14368   verifyFormat("{\n"
14369                "label0:\n"
14370                "  int x = 0;\n"
14371                "}");
14372   verifyFormat("switch (x) {\n"
14373                "case 1:\n"
14374                "default:\n"
14375                "}");
14376   verifyFormat("switch (allBraces) {\n"
14377                "case 1: {\n"
14378                "  break;\n"
14379                "}\n"
14380                "case 2: {\n"
14381                "  [[fallthrough]];\n"
14382                "}\n"
14383                "default: {\n"
14384                "  break;\n"
14385                "}\n"
14386                "}");
14387 
14388   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
14389   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
14390   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
14391   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
14392   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
14393   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
14394   verifyFormat("{\n"
14395                "label1:\n"
14396                "  int x = 0;\n"
14397                "}",
14398                CtorInitializerStyle);
14399   verifyFormat("switch (x) {\n"
14400                "case 1:\n"
14401                "default:\n"
14402                "}",
14403                CtorInitializerStyle);
14404   verifyFormat("switch (allBraces) {\n"
14405                "case 1: {\n"
14406                "  break;\n"
14407                "}\n"
14408                "case 2: {\n"
14409                "  [[fallthrough]];\n"
14410                "}\n"
14411                "default: {\n"
14412                "  break;\n"
14413                "}\n"
14414                "}",
14415                CtorInitializerStyle);
14416   CtorInitializerStyle.BreakConstructorInitializers =
14417       FormatStyle::BCIS_AfterColon;
14418   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
14419                "    aaaaaaaaaaaaaaaa(1),\n"
14420                "    bbbbbbbbbbbbbbbb(2) {}",
14421                CtorInitializerStyle);
14422   CtorInitializerStyle.BreakConstructorInitializers =
14423       FormatStyle::BCIS_BeforeComma;
14424   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14425                "    : aaaaaaaaaaaaaaaa(1)\n"
14426                "    , bbbbbbbbbbbbbbbb(2) {}",
14427                CtorInitializerStyle);
14428   CtorInitializerStyle.BreakConstructorInitializers =
14429       FormatStyle::BCIS_BeforeColon;
14430   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14431                "    : aaaaaaaaaaaaaaaa(1),\n"
14432                "      bbbbbbbbbbbbbbbb(2) {}",
14433                CtorInitializerStyle);
14434   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
14435   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
14436                ": aaaaaaaaaaaaaaaa(1),\n"
14437                "  bbbbbbbbbbbbbbbb(2) {}",
14438                CtorInitializerStyle);
14439 
14440   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
14441   InheritanceStyle.SpaceBeforeInheritanceColon = false;
14442   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
14443   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
14444   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
14445   verifyFormat("int x = a ? b : c;", InheritanceStyle);
14446   verifyFormat("{\n"
14447                "label2:\n"
14448                "  int x = 0;\n"
14449                "}",
14450                InheritanceStyle);
14451   verifyFormat("switch (x) {\n"
14452                "case 1:\n"
14453                "default:\n"
14454                "}",
14455                InheritanceStyle);
14456   verifyFormat("switch (allBraces) {\n"
14457                "case 1: {\n"
14458                "  break;\n"
14459                "}\n"
14460                "case 2: {\n"
14461                "  [[fallthrough]];\n"
14462                "}\n"
14463                "default: {\n"
14464                "  break;\n"
14465                "}\n"
14466                "}",
14467                InheritanceStyle);
14468   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterComma;
14469   verifyFormat("class Foooooooooooooooooooooo\n"
14470                "    : public aaaaaaaaaaaaaaaaaa,\n"
14471                "      public bbbbbbbbbbbbbbbbbb {\n"
14472                "}",
14473                InheritanceStyle);
14474   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
14475   verifyFormat("class Foooooooooooooooooooooo:\n"
14476                "    public aaaaaaaaaaaaaaaaaa,\n"
14477                "    public bbbbbbbbbbbbbbbbbb {\n"
14478                "}",
14479                InheritanceStyle);
14480   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
14481   verifyFormat("class Foooooooooooooooooooooo\n"
14482                "    : public aaaaaaaaaaaaaaaaaa\n"
14483                "    , public bbbbbbbbbbbbbbbbbb {\n"
14484                "}",
14485                InheritanceStyle);
14486   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
14487   verifyFormat("class Foooooooooooooooooooooo\n"
14488                "    : public aaaaaaaaaaaaaaaaaa,\n"
14489                "      public bbbbbbbbbbbbbbbbbb {\n"
14490                "}",
14491                InheritanceStyle);
14492   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
14493   verifyFormat("class Foooooooooooooooooooooo\n"
14494                ": public aaaaaaaaaaaaaaaaaa,\n"
14495                "  public bbbbbbbbbbbbbbbbbb {}",
14496                InheritanceStyle);
14497 
14498   FormatStyle ForLoopStyle = getLLVMStyle();
14499   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
14500   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
14501   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
14502   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
14503   verifyFormat("int x = a ? b : c;", ForLoopStyle);
14504   verifyFormat("{\n"
14505                "label2:\n"
14506                "  int x = 0;\n"
14507                "}",
14508                ForLoopStyle);
14509   verifyFormat("switch (x) {\n"
14510                "case 1:\n"
14511                "default:\n"
14512                "}",
14513                ForLoopStyle);
14514   verifyFormat("switch (allBraces) {\n"
14515                "case 1: {\n"
14516                "  break;\n"
14517                "}\n"
14518                "case 2: {\n"
14519                "  [[fallthrough]];\n"
14520                "}\n"
14521                "default: {\n"
14522                "  break;\n"
14523                "}\n"
14524                "}",
14525                ForLoopStyle);
14526 
14527   FormatStyle CaseStyle = getLLVMStyle();
14528   CaseStyle.SpaceBeforeCaseColon = true;
14529   verifyFormat("class Foo : public Bar {};", CaseStyle);
14530   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
14531   verifyFormat("for (auto a : b) {\n}", CaseStyle);
14532   verifyFormat("int x = a ? b : c;", CaseStyle);
14533   verifyFormat("switch (x) {\n"
14534                "case 1 :\n"
14535                "default :\n"
14536                "}",
14537                CaseStyle);
14538   verifyFormat("switch (allBraces) {\n"
14539                "case 1 : {\n"
14540                "  break;\n"
14541                "}\n"
14542                "case 2 : {\n"
14543                "  [[fallthrough]];\n"
14544                "}\n"
14545                "default : {\n"
14546                "  break;\n"
14547                "}\n"
14548                "}",
14549                CaseStyle);
14550 
14551   FormatStyle NoSpaceStyle = getLLVMStyle();
14552   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
14553   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
14554   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
14555   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
14556   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
14557   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
14558   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
14559   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
14560   verifyFormat("{\n"
14561                "label3:\n"
14562                "  int x = 0;\n"
14563                "}",
14564                NoSpaceStyle);
14565   verifyFormat("switch (x) {\n"
14566                "case 1:\n"
14567                "default:\n"
14568                "}",
14569                NoSpaceStyle);
14570   verifyFormat("switch (allBraces) {\n"
14571                "case 1: {\n"
14572                "  break;\n"
14573                "}\n"
14574                "case 2: {\n"
14575                "  [[fallthrough]];\n"
14576                "}\n"
14577                "default: {\n"
14578                "  break;\n"
14579                "}\n"
14580                "}",
14581                NoSpaceStyle);
14582 
14583   FormatStyle InvertedSpaceStyle = getLLVMStyle();
14584   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
14585   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
14586   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
14587   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
14588   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
14589   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
14590   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
14591   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
14592   verifyFormat("{\n"
14593                "label3:\n"
14594                "  int x = 0;\n"
14595                "}",
14596                InvertedSpaceStyle);
14597   verifyFormat("switch (x) {\n"
14598                "case 1 :\n"
14599                "case 2 : {\n"
14600                "  break;\n"
14601                "}\n"
14602                "default :\n"
14603                "  break;\n"
14604                "}",
14605                InvertedSpaceStyle);
14606   verifyFormat("switch (allBraces) {\n"
14607                "case 1 : {\n"
14608                "  break;\n"
14609                "}\n"
14610                "case 2 : {\n"
14611                "  [[fallthrough]];\n"
14612                "}\n"
14613                "default : {\n"
14614                "  break;\n"
14615                "}\n"
14616                "}",
14617                InvertedSpaceStyle);
14618 }
14619 
TEST_F(FormatTest,ConfigurableSpaceAroundPointerQualifiers)14620 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
14621   FormatStyle Style = getLLVMStyle();
14622 
14623   Style.PointerAlignment = FormatStyle::PAS_Left;
14624   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
14625   verifyFormat("void* const* x = NULL;", Style);
14626 
14627 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
14628   do {                                                                         \
14629     Style.PointerAlignment = FormatStyle::Pointers;                            \
14630     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
14631     verifyFormat(Code, Style);                                                 \
14632   } while (false)
14633 
14634   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
14635   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
14636   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
14637 
14638   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
14639   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
14640   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
14641 
14642   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
14643   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
14644   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
14645 
14646   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
14647   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
14648   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
14649 
14650   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
14651   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
14652                         SAPQ_Default);
14653   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
14654                         SAPQ_Default);
14655 
14656   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
14657   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
14658                         SAPQ_Before);
14659   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
14660                         SAPQ_Before);
14661 
14662   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
14663   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
14664   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
14665                         SAPQ_After);
14666 
14667   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
14668   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
14669   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
14670 
14671 #undef verifyQualifierSpaces
14672 
14673   FormatStyle Spaces = getLLVMStyle();
14674   Spaces.AttributeMacros.push_back("qualified");
14675   Spaces.PointerAlignment = FormatStyle::PAS_Right;
14676   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
14677   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
14678   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
14679   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
14680   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
14681   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14682   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
14683   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
14684   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
14685   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
14686   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
14687   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14688 
14689   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
14690   Spaces.PointerAlignment = FormatStyle::PAS_Left;
14691   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
14692   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
14693   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
14694   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
14695   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
14696   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14697   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
14698   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
14699   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
14700   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
14701   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
14702   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
14703   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14704 
14705   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
14706   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
14707   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
14708   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
14709   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
14710   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
14711   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
14712   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
14713 }
14714 
TEST_F(FormatTest,AlignConsecutiveMacros)14715 TEST_F(FormatTest, AlignConsecutiveMacros) {
14716   FormatStyle Style = getLLVMStyle();
14717   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14718   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14719   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
14720 
14721   verifyFormat("#define a 3\n"
14722                "#define bbbb 4\n"
14723                "#define ccc (5)",
14724                Style);
14725 
14726   verifyFormat("#define f(x) (x * x)\n"
14727                "#define fff(x, y, z) (x * y + z)\n"
14728                "#define ffff(x, y) (x - y)",
14729                Style);
14730 
14731   verifyFormat("#define foo(x, y) (x + y)\n"
14732                "#define bar (5, 6)(2 + 2)",
14733                Style);
14734 
14735   verifyFormat("#define a 3\n"
14736                "#define bbbb 4\n"
14737                "#define ccc (5)\n"
14738                "#define f(x) (x * x)\n"
14739                "#define fff(x, y, z) (x * y + z)\n"
14740                "#define ffff(x, y) (x - y)",
14741                Style);
14742 
14743   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14744   verifyFormat("#define a    3\n"
14745                "#define bbbb 4\n"
14746                "#define ccc  (5)",
14747                Style);
14748 
14749   verifyFormat("#define f(x)         (x * x)\n"
14750                "#define fff(x, y, z) (x * y + z)\n"
14751                "#define ffff(x, y)   (x - y)",
14752                Style);
14753 
14754   verifyFormat("#define foo(x, y) (x + y)\n"
14755                "#define bar       (5, 6)(2 + 2)",
14756                Style);
14757 
14758   verifyFormat("#define a            3\n"
14759                "#define bbbb         4\n"
14760                "#define ccc          (5)\n"
14761                "#define f(x)         (x * x)\n"
14762                "#define fff(x, y, z) (x * y + z)\n"
14763                "#define ffff(x, y)   (x - y)",
14764                Style);
14765 
14766   verifyFormat("#define a         5\n"
14767                "#define foo(x, y) (x + y)\n"
14768                "#define CCC       (6)\n"
14769                "auto lambda = []() {\n"
14770                "  auto  ii = 0;\n"
14771                "  float j  = 0;\n"
14772                "  return 0;\n"
14773                "};\n"
14774                "int   i  = 0;\n"
14775                "float i2 = 0;\n"
14776                "auto  v  = type{\n"
14777                "    i = 1,   //\n"
14778                "    (i = 2), //\n"
14779                "    i = 3    //\n"
14780                "};",
14781                Style);
14782 
14783   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
14784   Style.ColumnLimit = 20;
14785 
14786   verifyFormat("#define a          \\\n"
14787                "  \"aabbbbbbbbbbbb\"\n"
14788                "#define D          \\\n"
14789                "  \"aabbbbbbbbbbbb\" \\\n"
14790                "  \"ccddeeeeeeeee\"\n"
14791                "#define B          \\\n"
14792                "  \"QQQQQQQQQQQQQ\"  \\\n"
14793                "  \"FFFFFFFFFFFFF\"  \\\n"
14794                "  \"LLLLLLLL\"\n",
14795                Style);
14796 
14797   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14798   verifyFormat("#define a          \\\n"
14799                "  \"aabbbbbbbbbbbb\"\n"
14800                "#define D          \\\n"
14801                "  \"aabbbbbbbbbbbb\" \\\n"
14802                "  \"ccddeeeeeeeee\"\n"
14803                "#define B          \\\n"
14804                "  \"QQQQQQQQQQQQQ\"  \\\n"
14805                "  \"FFFFFFFFFFFFF\"  \\\n"
14806                "  \"LLLLLLLL\"\n",
14807                Style);
14808 
14809   // Test across comments
14810   Style.MaxEmptyLinesToKeep = 10;
14811   Style.ReflowComments = false;
14812   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
14813   EXPECT_EQ("#define a    3\n"
14814             "// line comment\n"
14815             "#define bbbb 4\n"
14816             "#define ccc  (5)",
14817             format("#define a 3\n"
14818                    "// line comment\n"
14819                    "#define bbbb 4\n"
14820                    "#define ccc (5)",
14821                    Style));
14822 
14823   EXPECT_EQ("#define a    3\n"
14824             "/* block comment */\n"
14825             "#define bbbb 4\n"
14826             "#define ccc  (5)",
14827             format("#define a  3\n"
14828                    "/* block comment */\n"
14829                    "#define bbbb 4\n"
14830                    "#define ccc (5)",
14831                    Style));
14832 
14833   EXPECT_EQ("#define a    3\n"
14834             "/* multi-line *\n"
14835             " * block comment */\n"
14836             "#define bbbb 4\n"
14837             "#define ccc  (5)",
14838             format("#define a 3\n"
14839                    "/* multi-line *\n"
14840                    " * block comment */\n"
14841                    "#define bbbb 4\n"
14842                    "#define ccc (5)",
14843                    Style));
14844 
14845   EXPECT_EQ("#define a    3\n"
14846             "// multi-line line comment\n"
14847             "//\n"
14848             "#define bbbb 4\n"
14849             "#define ccc  (5)",
14850             format("#define a  3\n"
14851                    "// multi-line line comment\n"
14852                    "//\n"
14853                    "#define bbbb 4\n"
14854                    "#define ccc (5)",
14855                    Style));
14856 
14857   EXPECT_EQ("#define a 3\n"
14858             "// empty lines still break.\n"
14859             "\n"
14860             "#define bbbb 4\n"
14861             "#define ccc  (5)",
14862             format("#define a     3\n"
14863                    "// empty lines still break.\n"
14864                    "\n"
14865                    "#define bbbb     4\n"
14866                    "#define ccc  (5)",
14867                    Style));
14868 
14869   // Test across empty lines
14870   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
14871   EXPECT_EQ("#define a    3\n"
14872             "\n"
14873             "#define bbbb 4\n"
14874             "#define ccc  (5)",
14875             format("#define a 3\n"
14876                    "\n"
14877                    "#define bbbb 4\n"
14878                    "#define ccc (5)",
14879                    Style));
14880 
14881   EXPECT_EQ("#define a    3\n"
14882             "\n"
14883             "\n"
14884             "\n"
14885             "#define bbbb 4\n"
14886             "#define ccc  (5)",
14887             format("#define a        3\n"
14888                    "\n"
14889                    "\n"
14890                    "\n"
14891                    "#define bbbb 4\n"
14892                    "#define ccc (5)",
14893                    Style));
14894 
14895   EXPECT_EQ("#define a 3\n"
14896             "// comments should break alignment\n"
14897             "//\n"
14898             "#define bbbb 4\n"
14899             "#define ccc  (5)",
14900             format("#define a        3\n"
14901                    "// comments should break alignment\n"
14902                    "//\n"
14903                    "#define bbbb 4\n"
14904                    "#define ccc (5)",
14905                    Style));
14906 
14907   // Test across empty lines and comments
14908   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
14909   verifyFormat("#define a    3\n"
14910                "\n"
14911                "// line comment\n"
14912                "#define bbbb 4\n"
14913                "#define ccc  (5)",
14914                Style);
14915 
14916   EXPECT_EQ("#define a    3\n"
14917             "\n"
14918             "\n"
14919             "/* multi-line *\n"
14920             " * block comment */\n"
14921             "\n"
14922             "\n"
14923             "#define bbbb 4\n"
14924             "#define ccc  (5)",
14925             format("#define a 3\n"
14926                    "\n"
14927                    "\n"
14928                    "/* multi-line *\n"
14929                    " * block comment */\n"
14930                    "\n"
14931                    "\n"
14932                    "#define bbbb 4\n"
14933                    "#define ccc (5)",
14934                    Style));
14935 
14936   EXPECT_EQ("#define a    3\n"
14937             "\n"
14938             "\n"
14939             "/* multi-line *\n"
14940             " * block comment */\n"
14941             "\n"
14942             "\n"
14943             "#define bbbb 4\n"
14944             "#define ccc  (5)",
14945             format("#define a 3\n"
14946                    "\n"
14947                    "\n"
14948                    "/* multi-line *\n"
14949                    " * block comment */\n"
14950                    "\n"
14951                    "\n"
14952                    "#define bbbb 4\n"
14953                    "#define ccc       (5)",
14954                    Style));
14955 }
14956 
TEST_F(FormatTest,AlignConsecutiveAssignmentsAcrossEmptyLines)14957 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
14958   FormatStyle Alignment = getLLVMStyle();
14959   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14960   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
14961 
14962   Alignment.MaxEmptyLinesToKeep = 10;
14963   /* Test alignment across empty lines */
14964   EXPECT_EQ("int a           = 5;\n"
14965             "\n"
14966             "int oneTwoThree = 123;",
14967             format("int a       = 5;\n"
14968                    "\n"
14969                    "int oneTwoThree= 123;",
14970                    Alignment));
14971   EXPECT_EQ("int a           = 5;\n"
14972             "int one         = 1;\n"
14973             "\n"
14974             "int oneTwoThree = 123;",
14975             format("int a = 5;\n"
14976                    "int one = 1;\n"
14977                    "\n"
14978                    "int oneTwoThree = 123;",
14979                    Alignment));
14980   EXPECT_EQ("int a           = 5;\n"
14981             "int one         = 1;\n"
14982             "\n"
14983             "int oneTwoThree = 123;\n"
14984             "int oneTwo      = 12;",
14985             format("int a = 5;\n"
14986                    "int one = 1;\n"
14987                    "\n"
14988                    "int oneTwoThree = 123;\n"
14989                    "int oneTwo = 12;",
14990                    Alignment));
14991 
14992   /* Test across comments */
14993   EXPECT_EQ("int a = 5;\n"
14994             "/* block comment */\n"
14995             "int oneTwoThree = 123;",
14996             format("int a = 5;\n"
14997                    "/* block comment */\n"
14998                    "int oneTwoThree=123;",
14999                    Alignment));
15000 
15001   EXPECT_EQ("int a = 5;\n"
15002             "// line comment\n"
15003             "int oneTwoThree = 123;",
15004             format("int a = 5;\n"
15005                    "// line comment\n"
15006                    "int oneTwoThree=123;",
15007                    Alignment));
15008 
15009   /* Test across comments and newlines */
15010   EXPECT_EQ("int a = 5;\n"
15011             "\n"
15012             "/* block comment */\n"
15013             "int oneTwoThree = 123;",
15014             format("int a = 5;\n"
15015                    "\n"
15016                    "/* block comment */\n"
15017                    "int oneTwoThree=123;",
15018                    Alignment));
15019 
15020   EXPECT_EQ("int a = 5;\n"
15021             "\n"
15022             "// line comment\n"
15023             "int oneTwoThree = 123;",
15024             format("int a = 5;\n"
15025                    "\n"
15026                    "// line comment\n"
15027                    "int oneTwoThree=123;",
15028                    Alignment));
15029 }
15030 
TEST_F(FormatTest,AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments)15031 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
15032   FormatStyle Alignment = getLLVMStyle();
15033   Alignment.AlignConsecutiveDeclarations =
15034       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15035   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15036 
15037   Alignment.MaxEmptyLinesToKeep = 10;
15038   /* Test alignment across empty lines */
15039   EXPECT_EQ("int         a = 5;\n"
15040             "\n"
15041             "float const oneTwoThree = 123;",
15042             format("int a = 5;\n"
15043                    "\n"
15044                    "float const oneTwoThree = 123;",
15045                    Alignment));
15046   EXPECT_EQ("int         a = 5;\n"
15047             "float const one = 1;\n"
15048             "\n"
15049             "int         oneTwoThree = 123;",
15050             format("int a = 5;\n"
15051                    "float const one = 1;\n"
15052                    "\n"
15053                    "int oneTwoThree = 123;",
15054                    Alignment));
15055 
15056   /* Test across comments */
15057   EXPECT_EQ("float const a = 5;\n"
15058             "/* block comment */\n"
15059             "int         oneTwoThree = 123;",
15060             format("float const a = 5;\n"
15061                    "/* block comment */\n"
15062                    "int oneTwoThree=123;",
15063                    Alignment));
15064 
15065   EXPECT_EQ("float const a = 5;\n"
15066             "// line comment\n"
15067             "int         oneTwoThree = 123;",
15068             format("float const a = 5;\n"
15069                    "// line comment\n"
15070                    "int oneTwoThree=123;",
15071                    Alignment));
15072 
15073   /* Test across comments and newlines */
15074   EXPECT_EQ("float const a = 5;\n"
15075             "\n"
15076             "/* block comment */\n"
15077             "int         oneTwoThree = 123;",
15078             format("float const a = 5;\n"
15079                    "\n"
15080                    "/* block comment */\n"
15081                    "int         oneTwoThree=123;",
15082                    Alignment));
15083 
15084   EXPECT_EQ("float const a = 5;\n"
15085             "\n"
15086             "// line comment\n"
15087             "int         oneTwoThree = 123;",
15088             format("float const a = 5;\n"
15089                    "\n"
15090                    "// line comment\n"
15091                    "int oneTwoThree=123;",
15092                    Alignment));
15093 }
15094 
TEST_F(FormatTest,AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments)15095 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
15096   FormatStyle Alignment = getLLVMStyle();
15097   Alignment.AlignConsecutiveBitFields =
15098       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15099 
15100   Alignment.MaxEmptyLinesToKeep = 10;
15101   /* Test alignment across empty lines */
15102   EXPECT_EQ("int a            : 5;\n"
15103             "\n"
15104             "int longbitfield : 6;",
15105             format("int a : 5;\n"
15106                    "\n"
15107                    "int longbitfield : 6;",
15108                    Alignment));
15109   EXPECT_EQ("int a            : 5;\n"
15110             "int one          : 1;\n"
15111             "\n"
15112             "int longbitfield : 6;",
15113             format("int a : 5;\n"
15114                    "int one : 1;\n"
15115                    "\n"
15116                    "int longbitfield : 6;",
15117                    Alignment));
15118 
15119   /* Test across comments */
15120   EXPECT_EQ("int a            : 5;\n"
15121             "/* block comment */\n"
15122             "int longbitfield : 6;",
15123             format("int a : 5;\n"
15124                    "/* block comment */\n"
15125                    "int longbitfield : 6;",
15126                    Alignment));
15127   EXPECT_EQ("int a            : 5;\n"
15128             "int one          : 1;\n"
15129             "// line comment\n"
15130             "int longbitfield : 6;",
15131             format("int a : 5;\n"
15132                    "int one : 1;\n"
15133                    "// line comment\n"
15134                    "int longbitfield : 6;",
15135                    Alignment));
15136 
15137   /* Test across comments and newlines */
15138   EXPECT_EQ("int a            : 5;\n"
15139             "/* block comment */\n"
15140             "\n"
15141             "int longbitfield : 6;",
15142             format("int a : 5;\n"
15143                    "/* block comment */\n"
15144                    "\n"
15145                    "int longbitfield : 6;",
15146                    Alignment));
15147   EXPECT_EQ("int a            : 5;\n"
15148             "int one          : 1;\n"
15149             "\n"
15150             "// line comment\n"
15151             "\n"
15152             "int longbitfield : 6;",
15153             format("int a : 5;\n"
15154                    "int one : 1;\n"
15155                    "\n"
15156                    "// line comment \n"
15157                    "\n"
15158                    "int longbitfield : 6;",
15159                    Alignment));
15160 }
15161 
TEST_F(FormatTest,AlignConsecutiveAssignmentsAcrossComments)15162 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
15163   FormatStyle Alignment = getLLVMStyle();
15164   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15165   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
15166 
15167   Alignment.MaxEmptyLinesToKeep = 10;
15168   /* Test alignment across empty lines */
15169   EXPECT_EQ("int a = 5;\n"
15170             "\n"
15171             "int oneTwoThree = 123;",
15172             format("int a       = 5;\n"
15173                    "\n"
15174                    "int oneTwoThree= 123;",
15175                    Alignment));
15176   EXPECT_EQ("int a   = 5;\n"
15177             "int one = 1;\n"
15178             "\n"
15179             "int oneTwoThree = 123;",
15180             format("int a = 5;\n"
15181                    "int one = 1;\n"
15182                    "\n"
15183                    "int oneTwoThree = 123;",
15184                    Alignment));
15185 
15186   /* Test across comments */
15187   EXPECT_EQ("int a           = 5;\n"
15188             "/* block comment */\n"
15189             "int oneTwoThree = 123;",
15190             format("int a = 5;\n"
15191                    "/* block comment */\n"
15192                    "int oneTwoThree=123;",
15193                    Alignment));
15194 
15195   EXPECT_EQ("int a           = 5;\n"
15196             "// line comment\n"
15197             "int oneTwoThree = 123;",
15198             format("int a = 5;\n"
15199                    "// line comment\n"
15200                    "int oneTwoThree=123;",
15201                    Alignment));
15202 
15203   EXPECT_EQ("int a           = 5;\n"
15204             "/*\n"
15205             " * multi-line block comment\n"
15206             " */\n"
15207             "int oneTwoThree = 123;",
15208             format("int a = 5;\n"
15209                    "/*\n"
15210                    " * multi-line block comment\n"
15211                    " */\n"
15212                    "int oneTwoThree=123;",
15213                    Alignment));
15214 
15215   EXPECT_EQ("int a           = 5;\n"
15216             "//\n"
15217             "// multi-line line comment\n"
15218             "//\n"
15219             "int oneTwoThree = 123;",
15220             format("int a = 5;\n"
15221                    "//\n"
15222                    "// multi-line line comment\n"
15223                    "//\n"
15224                    "int oneTwoThree=123;",
15225                    Alignment));
15226 
15227   /* Test across comments and newlines */
15228   EXPECT_EQ("int a = 5;\n"
15229             "\n"
15230             "/* block comment */\n"
15231             "int oneTwoThree = 123;",
15232             format("int a = 5;\n"
15233                    "\n"
15234                    "/* block comment */\n"
15235                    "int oneTwoThree=123;",
15236                    Alignment));
15237 
15238   EXPECT_EQ("int a = 5;\n"
15239             "\n"
15240             "// line comment\n"
15241             "int oneTwoThree = 123;",
15242             format("int a = 5;\n"
15243                    "\n"
15244                    "// line comment\n"
15245                    "int oneTwoThree=123;",
15246                    Alignment));
15247 }
15248 
TEST_F(FormatTest,AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments)15249 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
15250   FormatStyle Alignment = getLLVMStyle();
15251   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15252   Alignment.AlignConsecutiveAssignments =
15253       FormatStyle::ACS_AcrossEmptyLinesAndComments;
15254   verifyFormat("int a           = 5;\n"
15255                "int oneTwoThree = 123;",
15256                Alignment);
15257   verifyFormat("int a           = method();\n"
15258                "int oneTwoThree = 133;",
15259                Alignment);
15260   verifyFormat("a &= 5;\n"
15261                "bcd *= 5;\n"
15262                "ghtyf += 5;\n"
15263                "dvfvdb -= 5;\n"
15264                "a /= 5;\n"
15265                "vdsvsv %= 5;\n"
15266                "sfdbddfbdfbb ^= 5;\n"
15267                "dvsdsv |= 5;\n"
15268                "int dsvvdvsdvvv = 123;",
15269                Alignment);
15270   verifyFormat("int i = 1, j = 10;\n"
15271                "something = 2000;",
15272                Alignment);
15273   verifyFormat("something = 2000;\n"
15274                "int i = 1, j = 10;\n",
15275                Alignment);
15276   verifyFormat("something = 2000;\n"
15277                "another   = 911;\n"
15278                "int i = 1, j = 10;\n"
15279                "oneMore = 1;\n"
15280                "i       = 2;",
15281                Alignment);
15282   verifyFormat("int a   = 5;\n"
15283                "int one = 1;\n"
15284                "method();\n"
15285                "int oneTwoThree = 123;\n"
15286                "int oneTwo      = 12;",
15287                Alignment);
15288   verifyFormat("int oneTwoThree = 123;\n"
15289                "int oneTwo      = 12;\n"
15290                "method();\n",
15291                Alignment);
15292   verifyFormat("int oneTwoThree = 123; // comment\n"
15293                "int oneTwo      = 12;  // comment",
15294                Alignment);
15295 
15296   // Bug 25167
15297   /* Uncomment when fixed
15298     verifyFormat("#if A\n"
15299                  "#else\n"
15300                  "int aaaaaaaa = 12;\n"
15301                  "#endif\n"
15302                  "#if B\n"
15303                  "#else\n"
15304                  "int a = 12;\n"
15305                  "#endif\n",
15306                  Alignment);
15307     verifyFormat("enum foo {\n"
15308                  "#if A\n"
15309                  "#else\n"
15310                  "  aaaaaaaa = 12;\n"
15311                  "#endif\n"
15312                  "#if B\n"
15313                  "#else\n"
15314                  "  a = 12;\n"
15315                  "#endif\n"
15316                  "};\n",
15317                  Alignment);
15318   */
15319 
15320   Alignment.MaxEmptyLinesToKeep = 10;
15321   /* Test alignment across empty lines */
15322   EXPECT_EQ("int a           = 5;\n"
15323             "\n"
15324             "int oneTwoThree = 123;",
15325             format("int a       = 5;\n"
15326                    "\n"
15327                    "int oneTwoThree= 123;",
15328                    Alignment));
15329   EXPECT_EQ("int a           = 5;\n"
15330             "int one         = 1;\n"
15331             "\n"
15332             "int oneTwoThree = 123;",
15333             format("int a = 5;\n"
15334                    "int one = 1;\n"
15335                    "\n"
15336                    "int oneTwoThree = 123;",
15337                    Alignment));
15338   EXPECT_EQ("int a           = 5;\n"
15339             "int one         = 1;\n"
15340             "\n"
15341             "int oneTwoThree = 123;\n"
15342             "int oneTwo      = 12;",
15343             format("int a = 5;\n"
15344                    "int one = 1;\n"
15345                    "\n"
15346                    "int oneTwoThree = 123;\n"
15347                    "int oneTwo = 12;",
15348                    Alignment));
15349 
15350   /* Test across comments */
15351   EXPECT_EQ("int a           = 5;\n"
15352             "/* block comment */\n"
15353             "int oneTwoThree = 123;",
15354             format("int a = 5;\n"
15355                    "/* block comment */\n"
15356                    "int oneTwoThree=123;",
15357                    Alignment));
15358 
15359   EXPECT_EQ("int a           = 5;\n"
15360             "// line comment\n"
15361             "int oneTwoThree = 123;",
15362             format("int a = 5;\n"
15363                    "// line comment\n"
15364                    "int oneTwoThree=123;",
15365                    Alignment));
15366 
15367   /* Test across comments and newlines */
15368   EXPECT_EQ("int a           = 5;\n"
15369             "\n"
15370             "/* block comment */\n"
15371             "int oneTwoThree = 123;",
15372             format("int a = 5;\n"
15373                    "\n"
15374                    "/* block comment */\n"
15375                    "int oneTwoThree=123;",
15376                    Alignment));
15377 
15378   EXPECT_EQ("int a           = 5;\n"
15379             "\n"
15380             "// line comment\n"
15381             "int oneTwoThree = 123;",
15382             format("int a = 5;\n"
15383                    "\n"
15384                    "// line comment\n"
15385                    "int oneTwoThree=123;",
15386                    Alignment));
15387 
15388   EXPECT_EQ("int a           = 5;\n"
15389             "//\n"
15390             "// multi-line line comment\n"
15391             "//\n"
15392             "int oneTwoThree = 123;",
15393             format("int a = 5;\n"
15394                    "//\n"
15395                    "// multi-line line comment\n"
15396                    "//\n"
15397                    "int oneTwoThree=123;",
15398                    Alignment));
15399 
15400   EXPECT_EQ("int a           = 5;\n"
15401             "/*\n"
15402             " *  multi-line block comment\n"
15403             " */\n"
15404             "int oneTwoThree = 123;",
15405             format("int a = 5;\n"
15406                    "/*\n"
15407                    " *  multi-line block comment\n"
15408                    " */\n"
15409                    "int oneTwoThree=123;",
15410                    Alignment));
15411 
15412   EXPECT_EQ("int a           = 5;\n"
15413             "\n"
15414             "/* block comment */\n"
15415             "\n"
15416             "\n"
15417             "\n"
15418             "int oneTwoThree = 123;",
15419             format("int a = 5;\n"
15420                    "\n"
15421                    "/* block comment */\n"
15422                    "\n"
15423                    "\n"
15424                    "\n"
15425                    "int oneTwoThree=123;",
15426                    Alignment));
15427 
15428   EXPECT_EQ("int a           = 5;\n"
15429             "\n"
15430             "// line comment\n"
15431             "\n"
15432             "\n"
15433             "\n"
15434             "int oneTwoThree = 123;",
15435             format("int a = 5;\n"
15436                    "\n"
15437                    "// line comment\n"
15438                    "\n"
15439                    "\n"
15440                    "\n"
15441                    "int oneTwoThree=123;",
15442                    Alignment));
15443 
15444   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
15445   verifyFormat("#define A \\\n"
15446                "  int aaaa       = 12; \\\n"
15447                "  int b          = 23; \\\n"
15448                "  int ccc        = 234; \\\n"
15449                "  int dddddddddd = 2345;",
15450                Alignment);
15451   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
15452   verifyFormat("#define A               \\\n"
15453                "  int aaaa       = 12;  \\\n"
15454                "  int b          = 23;  \\\n"
15455                "  int ccc        = 234; \\\n"
15456                "  int dddddddddd = 2345;",
15457                Alignment);
15458   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
15459   verifyFormat("#define A                                                      "
15460                "                \\\n"
15461                "  int aaaa       = 12;                                         "
15462                "                \\\n"
15463                "  int b          = 23;                                         "
15464                "                \\\n"
15465                "  int ccc        = 234;                                        "
15466                "                \\\n"
15467                "  int dddddddddd = 2345;",
15468                Alignment);
15469   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
15470                "k = 4, int l = 5,\n"
15471                "                  int m = 6) {\n"
15472                "  int j      = 10;\n"
15473                "  otherThing = 1;\n"
15474                "}",
15475                Alignment);
15476   verifyFormat("void SomeFunction(int parameter = 0) {\n"
15477                "  int i   = 1;\n"
15478                "  int j   = 2;\n"
15479                "  int big = 10000;\n"
15480                "}",
15481                Alignment);
15482   verifyFormat("class C {\n"
15483                "public:\n"
15484                "  int i            = 1;\n"
15485                "  virtual void f() = 0;\n"
15486                "};",
15487                Alignment);
15488   verifyFormat("int i = 1;\n"
15489                "if (SomeType t = getSomething()) {\n"
15490                "}\n"
15491                "int j   = 2;\n"
15492                "int big = 10000;",
15493                Alignment);
15494   verifyFormat("int j = 7;\n"
15495                "for (int k = 0; k < N; ++k) {\n"
15496                "}\n"
15497                "int j   = 2;\n"
15498                "int big = 10000;\n"
15499                "}",
15500                Alignment);
15501   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15502   verifyFormat("int i = 1;\n"
15503                "LooooooooooongType loooooooooooooooooooooongVariable\n"
15504                "    = someLooooooooooooooooongFunction();\n"
15505                "int j = 2;",
15506                Alignment);
15507   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
15508   verifyFormat("int i = 1;\n"
15509                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
15510                "    someLooooooooooooooooongFunction();\n"
15511                "int j = 2;",
15512                Alignment);
15513 
15514   verifyFormat("auto lambda = []() {\n"
15515                "  auto i = 0;\n"
15516                "  return 0;\n"
15517                "};\n"
15518                "int i  = 0;\n"
15519                "auto v = type{\n"
15520                "    i = 1,   //\n"
15521                "    (i = 2), //\n"
15522                "    i = 3    //\n"
15523                "};",
15524                Alignment);
15525 
15526   verifyFormat(
15527       "int i      = 1;\n"
15528       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
15529       "                          loooooooooooooooooooooongParameterB);\n"
15530       "int j      = 2;",
15531       Alignment);
15532 
15533   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
15534                "          typename B   = very_long_type_name_1,\n"
15535                "          typename T_2 = very_long_type_name_2>\n"
15536                "auto foo() {}\n",
15537                Alignment);
15538   verifyFormat("int a, b = 1;\n"
15539                "int c  = 2;\n"
15540                "int dd = 3;\n",
15541                Alignment);
15542   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
15543                "float b[1][] = {{3.f}};\n",
15544                Alignment);
15545   verifyFormat("for (int i = 0; i < 1; i++)\n"
15546                "  int x = 1;\n",
15547                Alignment);
15548   verifyFormat("for (i = 0; i < 1; i++)\n"
15549                "  x = 1;\n"
15550                "y = 1;\n",
15551                Alignment);
15552 
15553   Alignment.ReflowComments = true;
15554   Alignment.ColumnLimit = 50;
15555   EXPECT_EQ("int x   = 0;\n"
15556             "int yy  = 1; /// specificlennospace\n"
15557             "int zzz = 2;\n",
15558             format("int x   = 0;\n"
15559                    "int yy  = 1; ///specificlennospace\n"
15560                    "int zzz = 2;\n",
15561                    Alignment));
15562 }
15563 
TEST_F(FormatTest,AlignConsecutiveAssignments)15564 TEST_F(FormatTest, AlignConsecutiveAssignments) {
15565   FormatStyle Alignment = getLLVMStyle();
15566   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15567   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
15568   verifyFormat("int a = 5;\n"
15569                "int oneTwoThree = 123;",
15570                Alignment);
15571   verifyFormat("int a = 5;\n"
15572                "int oneTwoThree = 123;",
15573                Alignment);
15574 
15575   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15576   verifyFormat("int a           = 5;\n"
15577                "int oneTwoThree = 123;",
15578                Alignment);
15579   verifyFormat("int a           = method();\n"
15580                "int oneTwoThree = 133;",
15581                Alignment);
15582   verifyFormat("a &= 5;\n"
15583                "bcd *= 5;\n"
15584                "ghtyf += 5;\n"
15585                "dvfvdb -= 5;\n"
15586                "a /= 5;\n"
15587                "vdsvsv %= 5;\n"
15588                "sfdbddfbdfbb ^= 5;\n"
15589                "dvsdsv |= 5;\n"
15590                "int dsvvdvsdvvv = 123;",
15591                Alignment);
15592   verifyFormat("int i = 1, j = 10;\n"
15593                "something = 2000;",
15594                Alignment);
15595   verifyFormat("something = 2000;\n"
15596                "int i = 1, j = 10;\n",
15597                Alignment);
15598   verifyFormat("something = 2000;\n"
15599                "another   = 911;\n"
15600                "int i = 1, j = 10;\n"
15601                "oneMore = 1;\n"
15602                "i       = 2;",
15603                Alignment);
15604   verifyFormat("int a   = 5;\n"
15605                "int one = 1;\n"
15606                "method();\n"
15607                "int oneTwoThree = 123;\n"
15608                "int oneTwo      = 12;",
15609                Alignment);
15610   verifyFormat("int oneTwoThree = 123;\n"
15611                "int oneTwo      = 12;\n"
15612                "method();\n",
15613                Alignment);
15614   verifyFormat("int oneTwoThree = 123; // comment\n"
15615                "int oneTwo      = 12;  // comment",
15616                Alignment);
15617 
15618   // Bug 25167
15619   /* Uncomment when fixed
15620     verifyFormat("#if A\n"
15621                  "#else\n"
15622                  "int aaaaaaaa = 12;\n"
15623                  "#endif\n"
15624                  "#if B\n"
15625                  "#else\n"
15626                  "int a = 12;\n"
15627                  "#endif\n",
15628                  Alignment);
15629     verifyFormat("enum foo {\n"
15630                  "#if A\n"
15631                  "#else\n"
15632                  "  aaaaaaaa = 12;\n"
15633                  "#endif\n"
15634                  "#if B\n"
15635                  "#else\n"
15636                  "  a = 12;\n"
15637                  "#endif\n"
15638                  "};\n",
15639                  Alignment);
15640   */
15641 
15642   EXPECT_EQ("int a = 5;\n"
15643             "\n"
15644             "int oneTwoThree = 123;",
15645             format("int a       = 5;\n"
15646                    "\n"
15647                    "int oneTwoThree= 123;",
15648                    Alignment));
15649   EXPECT_EQ("int a   = 5;\n"
15650             "int one = 1;\n"
15651             "\n"
15652             "int oneTwoThree = 123;",
15653             format("int a = 5;\n"
15654                    "int one = 1;\n"
15655                    "\n"
15656                    "int oneTwoThree = 123;",
15657                    Alignment));
15658   EXPECT_EQ("int a   = 5;\n"
15659             "int one = 1;\n"
15660             "\n"
15661             "int oneTwoThree = 123;\n"
15662             "int oneTwo      = 12;",
15663             format("int a = 5;\n"
15664                    "int one = 1;\n"
15665                    "\n"
15666                    "int oneTwoThree = 123;\n"
15667                    "int oneTwo = 12;",
15668                    Alignment));
15669   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
15670   verifyFormat("#define A \\\n"
15671                "  int aaaa       = 12; \\\n"
15672                "  int b          = 23; \\\n"
15673                "  int ccc        = 234; \\\n"
15674                "  int dddddddddd = 2345;",
15675                Alignment);
15676   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
15677   verifyFormat("#define A               \\\n"
15678                "  int aaaa       = 12;  \\\n"
15679                "  int b          = 23;  \\\n"
15680                "  int ccc        = 234; \\\n"
15681                "  int dddddddddd = 2345;",
15682                Alignment);
15683   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
15684   verifyFormat("#define A                                                      "
15685                "                \\\n"
15686                "  int aaaa       = 12;                                         "
15687                "                \\\n"
15688                "  int b          = 23;                                         "
15689                "                \\\n"
15690                "  int ccc        = 234;                                        "
15691                "                \\\n"
15692                "  int dddddddddd = 2345;",
15693                Alignment);
15694   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
15695                "k = 4, int l = 5,\n"
15696                "                  int m = 6) {\n"
15697                "  int j      = 10;\n"
15698                "  otherThing = 1;\n"
15699                "}",
15700                Alignment);
15701   verifyFormat("void SomeFunction(int parameter = 0) {\n"
15702                "  int i   = 1;\n"
15703                "  int j   = 2;\n"
15704                "  int big = 10000;\n"
15705                "}",
15706                Alignment);
15707   verifyFormat("class C {\n"
15708                "public:\n"
15709                "  int i            = 1;\n"
15710                "  virtual void f() = 0;\n"
15711                "};",
15712                Alignment);
15713   verifyFormat("int i = 1;\n"
15714                "if (SomeType t = getSomething()) {\n"
15715                "}\n"
15716                "int j   = 2;\n"
15717                "int big = 10000;",
15718                Alignment);
15719   verifyFormat("int j = 7;\n"
15720                "for (int k = 0; k < N; ++k) {\n"
15721                "}\n"
15722                "int j   = 2;\n"
15723                "int big = 10000;\n"
15724                "}",
15725                Alignment);
15726   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15727   verifyFormat("int i = 1;\n"
15728                "LooooooooooongType loooooooooooooooooooooongVariable\n"
15729                "    = someLooooooooooooooooongFunction();\n"
15730                "int j = 2;",
15731                Alignment);
15732   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
15733   verifyFormat("int i = 1;\n"
15734                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
15735                "    someLooooooooooooooooongFunction();\n"
15736                "int j = 2;",
15737                Alignment);
15738 
15739   verifyFormat("auto lambda = []() {\n"
15740                "  auto i = 0;\n"
15741                "  return 0;\n"
15742                "};\n"
15743                "int i  = 0;\n"
15744                "auto v = type{\n"
15745                "    i = 1,   //\n"
15746                "    (i = 2), //\n"
15747                "    i = 3    //\n"
15748                "};",
15749                Alignment);
15750 
15751   verifyFormat(
15752       "int i      = 1;\n"
15753       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
15754       "                          loooooooooooooooooooooongParameterB);\n"
15755       "int j      = 2;",
15756       Alignment);
15757 
15758   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
15759                "          typename B   = very_long_type_name_1,\n"
15760                "          typename T_2 = very_long_type_name_2>\n"
15761                "auto foo() {}\n",
15762                Alignment);
15763   verifyFormat("int a, b = 1;\n"
15764                "int c  = 2;\n"
15765                "int dd = 3;\n",
15766                Alignment);
15767   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
15768                "float b[1][] = {{3.f}};\n",
15769                Alignment);
15770   verifyFormat("for (int i = 0; i < 1; i++)\n"
15771                "  int x = 1;\n",
15772                Alignment);
15773   verifyFormat("for (i = 0; i < 1; i++)\n"
15774                "  x = 1;\n"
15775                "y = 1;\n",
15776                Alignment);
15777 
15778   Alignment.ReflowComments = true;
15779   Alignment.ColumnLimit = 50;
15780   EXPECT_EQ("int x   = 0;\n"
15781             "int yy  = 1; /// specificlennospace\n"
15782             "int zzz = 2;\n",
15783             format("int x   = 0;\n"
15784                    "int yy  = 1; ///specificlennospace\n"
15785                    "int zzz = 2;\n",
15786                    Alignment));
15787 }
15788 
TEST_F(FormatTest,AlignConsecutiveBitFields)15789 TEST_F(FormatTest, AlignConsecutiveBitFields) {
15790   FormatStyle Alignment = getLLVMStyle();
15791   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
15792   verifyFormat("int const a     : 5;\n"
15793                "int oneTwoThree : 23;",
15794                Alignment);
15795 
15796   // Initializers are allowed starting with c++2a
15797   verifyFormat("int const a     : 5 = 1;\n"
15798                "int oneTwoThree : 23 = 0;",
15799                Alignment);
15800 
15801   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15802   verifyFormat("int const a           : 5;\n"
15803                "int       oneTwoThree : 23;",
15804                Alignment);
15805 
15806   verifyFormat("int const a           : 5;  // comment\n"
15807                "int       oneTwoThree : 23; // comment",
15808                Alignment);
15809 
15810   verifyFormat("int const a           : 5 = 1;\n"
15811                "int       oneTwoThree : 23 = 0;",
15812                Alignment);
15813 
15814   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15815   verifyFormat("int const a           : 5  = 1;\n"
15816                "int       oneTwoThree : 23 = 0;",
15817                Alignment);
15818   verifyFormat("int const a           : 5  = {1};\n"
15819                "int       oneTwoThree : 23 = 0;",
15820                Alignment);
15821 
15822   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
15823   verifyFormat("int const a          :5;\n"
15824                "int       oneTwoThree:23;",
15825                Alignment);
15826 
15827   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
15828   verifyFormat("int const a           :5;\n"
15829                "int       oneTwoThree :23;",
15830                Alignment);
15831 
15832   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
15833   verifyFormat("int const a          : 5;\n"
15834                "int       oneTwoThree: 23;",
15835                Alignment);
15836 
15837   // Known limitations: ':' is only recognized as a bitfield colon when
15838   // followed by a number.
15839   /*
15840   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
15841                "int a           : 5;",
15842                Alignment);
15843   */
15844 }
15845 
TEST_F(FormatTest,AlignConsecutiveDeclarations)15846 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
15847   FormatStyle Alignment = getLLVMStyle();
15848   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15849   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
15850   Alignment.PointerAlignment = FormatStyle::PAS_Right;
15851   verifyFormat("float const a = 5;\n"
15852                "int oneTwoThree = 123;",
15853                Alignment);
15854   verifyFormat("int a = 5;\n"
15855                "float const oneTwoThree = 123;",
15856                Alignment);
15857 
15858   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15859   verifyFormat("float const a = 5;\n"
15860                "int         oneTwoThree = 123;",
15861                Alignment);
15862   verifyFormat("int         a = method();\n"
15863                "float const oneTwoThree = 133;",
15864                Alignment);
15865   verifyFormat("int i = 1, j = 10;\n"
15866                "something = 2000;",
15867                Alignment);
15868   verifyFormat("something = 2000;\n"
15869                "int i = 1, j = 10;\n",
15870                Alignment);
15871   verifyFormat("float      something = 2000;\n"
15872                "double     another = 911;\n"
15873                "int        i = 1, j = 10;\n"
15874                "const int *oneMore = 1;\n"
15875                "unsigned   i = 2;",
15876                Alignment);
15877   verifyFormat("float a = 5;\n"
15878                "int   one = 1;\n"
15879                "method();\n"
15880                "const double       oneTwoThree = 123;\n"
15881                "const unsigned int oneTwo = 12;",
15882                Alignment);
15883   verifyFormat("int      oneTwoThree{0}; // comment\n"
15884                "unsigned oneTwo;         // comment",
15885                Alignment);
15886   verifyFormat("unsigned int       *a;\n"
15887                "int                *b;\n"
15888                "unsigned int Const *c;\n"
15889                "unsigned int const *d;\n"
15890                "unsigned int Const &e;\n"
15891                "unsigned int const &f;",
15892                Alignment);
15893   verifyFormat("Const unsigned int *c;\n"
15894                "const unsigned int *d;\n"
15895                "Const unsigned int &e;\n"
15896                "const unsigned int &f;\n"
15897                "const unsigned      g;\n"
15898                "Const unsigned      h;",
15899                Alignment);
15900   EXPECT_EQ("float const a = 5;\n"
15901             "\n"
15902             "int oneTwoThree = 123;",
15903             format("float const   a = 5;\n"
15904                    "\n"
15905                    "int           oneTwoThree= 123;",
15906                    Alignment));
15907   EXPECT_EQ("float a = 5;\n"
15908             "int   one = 1;\n"
15909             "\n"
15910             "unsigned oneTwoThree = 123;",
15911             format("float    a = 5;\n"
15912                    "int      one = 1;\n"
15913                    "\n"
15914                    "unsigned oneTwoThree = 123;",
15915                    Alignment));
15916   EXPECT_EQ("float a = 5;\n"
15917             "int   one = 1;\n"
15918             "\n"
15919             "unsigned oneTwoThree = 123;\n"
15920             "int      oneTwo = 12;",
15921             format("float    a = 5;\n"
15922                    "int one = 1;\n"
15923                    "\n"
15924                    "unsigned oneTwoThree = 123;\n"
15925                    "int oneTwo = 12;",
15926                    Alignment));
15927   // Function prototype alignment
15928   verifyFormat("int    a();\n"
15929                "double b();",
15930                Alignment);
15931   verifyFormat("int    a(int x);\n"
15932                "double b();",
15933                Alignment);
15934   unsigned OldColumnLimit = Alignment.ColumnLimit;
15935   // We need to set ColumnLimit to zero, in order to stress nested alignments,
15936   // otherwise the function parameters will be re-flowed onto a single line.
15937   Alignment.ColumnLimit = 0;
15938   EXPECT_EQ("int    a(int   x,\n"
15939             "         float y);\n"
15940             "double b(int    x,\n"
15941             "         double y);",
15942             format("int a(int x,\n"
15943                    " float y);\n"
15944                    "double b(int x,\n"
15945                    " double y);",
15946                    Alignment));
15947   // This ensures that function parameters of function declarations are
15948   // correctly indented when their owning functions are indented.
15949   // The failure case here is for 'double y' to not be indented enough.
15950   EXPECT_EQ("double a(int x);\n"
15951             "int    b(int    y,\n"
15952             "         double z);",
15953             format("double a(int x);\n"
15954                    "int b(int y,\n"
15955                    " double z);",
15956                    Alignment));
15957   // Set ColumnLimit low so that we induce wrapping immediately after
15958   // the function name and opening paren.
15959   Alignment.ColumnLimit = 13;
15960   verifyFormat("int function(\n"
15961                "    int  x,\n"
15962                "    bool y);",
15963                Alignment);
15964   Alignment.ColumnLimit = OldColumnLimit;
15965   // Ensure function pointers don't screw up recursive alignment
15966   verifyFormat("int    a(int x, void (*fp)(int y));\n"
15967                "double b();",
15968                Alignment);
15969   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15970   // Ensure recursive alignment is broken by function braces, so that the
15971   // "a = 1" does not align with subsequent assignments inside the function
15972   // body.
15973   verifyFormat("int func(int a = 1) {\n"
15974                "  int b  = 2;\n"
15975                "  int cc = 3;\n"
15976                "}",
15977                Alignment);
15978   verifyFormat("float      something = 2000;\n"
15979                "double     another   = 911;\n"
15980                "int        i = 1, j = 10;\n"
15981                "const int *oneMore = 1;\n"
15982                "unsigned   i       = 2;",
15983                Alignment);
15984   verifyFormat("int      oneTwoThree = {0}; // comment\n"
15985                "unsigned oneTwo      = 0;   // comment",
15986                Alignment);
15987   // Make sure that scope is correctly tracked, in the absence of braces
15988   verifyFormat("for (int i = 0; i < n; i++)\n"
15989                "  j = i;\n"
15990                "double x = 1;\n",
15991                Alignment);
15992   verifyFormat("if (int i = 0)\n"
15993                "  j = i;\n"
15994                "double x = 1;\n",
15995                Alignment);
15996   // Ensure operator[] and operator() are comprehended
15997   verifyFormat("struct test {\n"
15998                "  long long int foo();\n"
15999                "  int           operator[](int a);\n"
16000                "  double        bar();\n"
16001                "};\n",
16002                Alignment);
16003   verifyFormat("struct test {\n"
16004                "  long long int foo();\n"
16005                "  int           operator()(int a);\n"
16006                "  double        bar();\n"
16007                "};\n",
16008                Alignment);
16009 
16010   // PAS_Right
16011   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16012             "  int const i   = 1;\n"
16013             "  int      *j   = 2;\n"
16014             "  int       big = 10000;\n"
16015             "\n"
16016             "  unsigned oneTwoThree = 123;\n"
16017             "  int      oneTwo      = 12;\n"
16018             "  method();\n"
16019             "  float k  = 2;\n"
16020             "  int   ll = 10000;\n"
16021             "}",
16022             format("void SomeFunction(int parameter= 0) {\n"
16023                    " int const  i= 1;\n"
16024                    "  int *j=2;\n"
16025                    " int big  =  10000;\n"
16026                    "\n"
16027                    "unsigned oneTwoThree  =123;\n"
16028                    "int oneTwo = 12;\n"
16029                    "  method();\n"
16030                    "float k= 2;\n"
16031                    "int ll=10000;\n"
16032                    "}",
16033                    Alignment));
16034   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16035             "  int const i   = 1;\n"
16036             "  int     **j   = 2, ***k;\n"
16037             "  int      &k   = i;\n"
16038             "  int     &&l   = i + j;\n"
16039             "  int       big = 10000;\n"
16040             "\n"
16041             "  unsigned oneTwoThree = 123;\n"
16042             "  int      oneTwo      = 12;\n"
16043             "  method();\n"
16044             "  float k  = 2;\n"
16045             "  int   ll = 10000;\n"
16046             "}",
16047             format("void SomeFunction(int parameter= 0) {\n"
16048                    " int const  i= 1;\n"
16049                    "  int **j=2,***k;\n"
16050                    "int &k=i;\n"
16051                    "int &&l=i+j;\n"
16052                    " int big  =  10000;\n"
16053                    "\n"
16054                    "unsigned oneTwoThree  =123;\n"
16055                    "int oneTwo = 12;\n"
16056                    "  method();\n"
16057                    "float k= 2;\n"
16058                    "int ll=10000;\n"
16059                    "}",
16060                    Alignment));
16061   // variables are aligned at their name, pointers are at the right most
16062   // position
16063   verifyFormat("int   *a;\n"
16064                "int  **b;\n"
16065                "int ***c;\n"
16066                "int    foobar;\n",
16067                Alignment);
16068 
16069   // PAS_Left
16070   FormatStyle AlignmentLeft = Alignment;
16071   AlignmentLeft.PointerAlignment = FormatStyle::PAS_Left;
16072   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16073             "  int const i   = 1;\n"
16074             "  int*      j   = 2;\n"
16075             "  int       big = 10000;\n"
16076             "\n"
16077             "  unsigned oneTwoThree = 123;\n"
16078             "  int      oneTwo      = 12;\n"
16079             "  method();\n"
16080             "  float k  = 2;\n"
16081             "  int   ll = 10000;\n"
16082             "}",
16083             format("void SomeFunction(int parameter= 0) {\n"
16084                    " int const  i= 1;\n"
16085                    "  int *j=2;\n"
16086                    " int big  =  10000;\n"
16087                    "\n"
16088                    "unsigned oneTwoThree  =123;\n"
16089                    "int oneTwo = 12;\n"
16090                    "  method();\n"
16091                    "float k= 2;\n"
16092                    "int ll=10000;\n"
16093                    "}",
16094                    AlignmentLeft));
16095   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16096             "  int const i   = 1;\n"
16097             "  int**     j   = 2;\n"
16098             "  int&      k   = i;\n"
16099             "  int&&     l   = i + j;\n"
16100             "  int       big = 10000;\n"
16101             "\n"
16102             "  unsigned oneTwoThree = 123;\n"
16103             "  int      oneTwo      = 12;\n"
16104             "  method();\n"
16105             "  float k  = 2;\n"
16106             "  int   ll = 10000;\n"
16107             "}",
16108             format("void SomeFunction(int parameter= 0) {\n"
16109                    " int const  i= 1;\n"
16110                    "  int **j=2;\n"
16111                    "int &k=i;\n"
16112                    "int &&l=i+j;\n"
16113                    " int big  =  10000;\n"
16114                    "\n"
16115                    "unsigned oneTwoThree  =123;\n"
16116                    "int oneTwo = 12;\n"
16117                    "  method();\n"
16118                    "float k= 2;\n"
16119                    "int ll=10000;\n"
16120                    "}",
16121                    AlignmentLeft));
16122   // variables are aligned at their name, pointers are at the left most position
16123   verifyFormat("int*   a;\n"
16124                "int**  b;\n"
16125                "int*** c;\n"
16126                "int    foobar;\n",
16127                AlignmentLeft);
16128 
16129   // PAS_Middle
16130   FormatStyle AlignmentMiddle = Alignment;
16131   AlignmentMiddle.PointerAlignment = FormatStyle::PAS_Middle;
16132   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16133             "  int const i   = 1;\n"
16134             "  int *     j   = 2;\n"
16135             "  int       big = 10000;\n"
16136             "\n"
16137             "  unsigned oneTwoThree = 123;\n"
16138             "  int      oneTwo      = 12;\n"
16139             "  method();\n"
16140             "  float k  = 2;\n"
16141             "  int   ll = 10000;\n"
16142             "}",
16143             format("void SomeFunction(int parameter= 0) {\n"
16144                    " int const  i= 1;\n"
16145                    "  int *j=2;\n"
16146                    " int big  =  10000;\n"
16147                    "\n"
16148                    "unsigned oneTwoThree  =123;\n"
16149                    "int oneTwo = 12;\n"
16150                    "  method();\n"
16151                    "float k= 2;\n"
16152                    "int ll=10000;\n"
16153                    "}",
16154                    AlignmentMiddle));
16155   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
16156             "  int const i   = 1;\n"
16157             "  int **    j   = 2, ***k;\n"
16158             "  int &     k   = i;\n"
16159             "  int &&    l   = i + j;\n"
16160             "  int       big = 10000;\n"
16161             "\n"
16162             "  unsigned oneTwoThree = 123;\n"
16163             "  int      oneTwo      = 12;\n"
16164             "  method();\n"
16165             "  float k  = 2;\n"
16166             "  int   ll = 10000;\n"
16167             "}",
16168             format("void SomeFunction(int parameter= 0) {\n"
16169                    " int const  i= 1;\n"
16170                    "  int **j=2,***k;\n"
16171                    "int &k=i;\n"
16172                    "int &&l=i+j;\n"
16173                    " int big  =  10000;\n"
16174                    "\n"
16175                    "unsigned oneTwoThree  =123;\n"
16176                    "int oneTwo = 12;\n"
16177                    "  method();\n"
16178                    "float k= 2;\n"
16179                    "int ll=10000;\n"
16180                    "}",
16181                    AlignmentMiddle));
16182   // variables are aligned at their name, pointers are in the middle
16183   verifyFormat("int *   a;\n"
16184                "int *   b;\n"
16185                "int *** c;\n"
16186                "int     foobar;\n",
16187                AlignmentMiddle);
16188 
16189   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16190   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
16191   verifyFormat("#define A \\\n"
16192                "  int       aaaa = 12; \\\n"
16193                "  float     b = 23; \\\n"
16194                "  const int ccc = 234; \\\n"
16195                "  unsigned  dddddddddd = 2345;",
16196                Alignment);
16197   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16198   verifyFormat("#define A              \\\n"
16199                "  int       aaaa = 12; \\\n"
16200                "  float     b = 23;    \\\n"
16201                "  const int ccc = 234; \\\n"
16202                "  unsigned  dddddddddd = 2345;",
16203                Alignment);
16204   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
16205   Alignment.ColumnLimit = 30;
16206   verifyFormat("#define A                    \\\n"
16207                "  int       aaaa = 12;       \\\n"
16208                "  float     b = 23;          \\\n"
16209                "  const int ccc = 234;       \\\n"
16210                "  int       dddddddddd = 2345;",
16211                Alignment);
16212   Alignment.ColumnLimit = 80;
16213   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
16214                "k = 4, int l = 5,\n"
16215                "                  int m = 6) {\n"
16216                "  const int j = 10;\n"
16217                "  otherThing = 1;\n"
16218                "}",
16219                Alignment);
16220   verifyFormat("void SomeFunction(int parameter = 0) {\n"
16221                "  int const i = 1;\n"
16222                "  int      *j = 2;\n"
16223                "  int       big = 10000;\n"
16224                "}",
16225                Alignment);
16226   verifyFormat("class C {\n"
16227                "public:\n"
16228                "  int          i = 1;\n"
16229                "  virtual void f() = 0;\n"
16230                "};",
16231                Alignment);
16232   verifyFormat("float i = 1;\n"
16233                "if (SomeType t = getSomething()) {\n"
16234                "}\n"
16235                "const unsigned j = 2;\n"
16236                "int            big = 10000;",
16237                Alignment);
16238   verifyFormat("float j = 7;\n"
16239                "for (int k = 0; k < N; ++k) {\n"
16240                "}\n"
16241                "unsigned j = 2;\n"
16242                "int      big = 10000;\n"
16243                "}",
16244                Alignment);
16245   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16246   verifyFormat("float              i = 1;\n"
16247                "LooooooooooongType loooooooooooooooooooooongVariable\n"
16248                "    = someLooooooooooooooooongFunction();\n"
16249                "int j = 2;",
16250                Alignment);
16251   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
16252   verifyFormat("int                i = 1;\n"
16253                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
16254                "    someLooooooooooooooooongFunction();\n"
16255                "int j = 2;",
16256                Alignment);
16257 
16258   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16259   verifyFormat("auto lambda = []() {\n"
16260                "  auto  ii = 0;\n"
16261                "  float j  = 0;\n"
16262                "  return 0;\n"
16263                "};\n"
16264                "int   i  = 0;\n"
16265                "float i2 = 0;\n"
16266                "auto  v  = type{\n"
16267                "    i = 1,   //\n"
16268                "    (i = 2), //\n"
16269                "    i = 3    //\n"
16270                "};",
16271                Alignment);
16272   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16273 
16274   verifyFormat(
16275       "int      i = 1;\n"
16276       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
16277       "                          loooooooooooooooooooooongParameterB);\n"
16278       "int      j = 2;",
16279       Alignment);
16280 
16281   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
16282   // We expect declarations and assignments to align, as long as it doesn't
16283   // exceed the column limit, starting a new alignment sequence whenever it
16284   // happens.
16285   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16286   Alignment.ColumnLimit = 30;
16287   verifyFormat("float    ii              = 1;\n"
16288                "unsigned j               = 2;\n"
16289                "int someVerylongVariable = 1;\n"
16290                "AnotherLongType  ll = 123456;\n"
16291                "VeryVeryLongType k  = 2;\n"
16292                "int              myvar = 1;",
16293                Alignment);
16294   Alignment.ColumnLimit = 80;
16295   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16296 
16297   verifyFormat(
16298       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
16299       "          typename LongType, typename B>\n"
16300       "auto foo() {}\n",
16301       Alignment);
16302   verifyFormat("float a, b = 1;\n"
16303                "int   c = 2;\n"
16304                "int   dd = 3;\n",
16305                Alignment);
16306   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
16307                "float b[1][] = {{3.f}};\n",
16308                Alignment);
16309   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16310   verifyFormat("float a, b = 1;\n"
16311                "int   c  = 2;\n"
16312                "int   dd = 3;\n",
16313                Alignment);
16314   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
16315                "float b[1][] = {{3.f}};\n",
16316                Alignment);
16317   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16318 
16319   Alignment.ColumnLimit = 30;
16320   Alignment.BinPackParameters = false;
16321   verifyFormat("void foo(float     a,\n"
16322                "         float     b,\n"
16323                "         int       c,\n"
16324                "         uint32_t *d) {\n"
16325                "  int   *e = 0;\n"
16326                "  float  f = 0;\n"
16327                "  double g = 0;\n"
16328                "}\n"
16329                "void bar(ino_t     a,\n"
16330                "         int       b,\n"
16331                "         uint32_t *c,\n"
16332                "         bool      d) {}\n",
16333                Alignment);
16334   Alignment.BinPackParameters = true;
16335   Alignment.ColumnLimit = 80;
16336 
16337   // Bug 33507
16338   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16339   verifyFormat(
16340       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
16341       "  static const Version verVs2017;\n"
16342       "  return true;\n"
16343       "});\n",
16344       Alignment);
16345   Alignment.PointerAlignment = FormatStyle::PAS_Right;
16346 
16347   // See llvm.org/PR35641
16348   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16349   verifyFormat("int func() { //\n"
16350                "  int      b;\n"
16351                "  unsigned c;\n"
16352                "}",
16353                Alignment);
16354 
16355   // See PR37175
16356   FormatStyle Style = getMozillaStyle();
16357   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16358   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
16359             "foo(int a);",
16360             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
16361 
16362   Alignment.PointerAlignment = FormatStyle::PAS_Left;
16363   verifyFormat("unsigned int*       a;\n"
16364                "int*                b;\n"
16365                "unsigned int Const* c;\n"
16366                "unsigned int const* d;\n"
16367                "unsigned int Const& e;\n"
16368                "unsigned int const& f;",
16369                Alignment);
16370   verifyFormat("Const unsigned int* c;\n"
16371                "const unsigned int* d;\n"
16372                "Const unsigned int& e;\n"
16373                "const unsigned int& f;\n"
16374                "const unsigned      g;\n"
16375                "Const unsigned      h;",
16376                Alignment);
16377 
16378   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
16379   verifyFormat("unsigned int *       a;\n"
16380                "int *                b;\n"
16381                "unsigned int Const * c;\n"
16382                "unsigned int const * d;\n"
16383                "unsigned int Const & e;\n"
16384                "unsigned int const & f;",
16385                Alignment);
16386   verifyFormat("Const unsigned int * c;\n"
16387                "const unsigned int * d;\n"
16388                "Const unsigned int & e;\n"
16389                "const unsigned int & f;\n"
16390                "const unsigned       g;\n"
16391                "Const unsigned       h;",
16392                Alignment);
16393 }
16394 
TEST_F(FormatTest,AlignWithLineBreaks)16395 TEST_F(FormatTest, AlignWithLineBreaks) {
16396   auto Style = getLLVMStyleWithColumns(120);
16397 
16398   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
16399   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
16400   verifyFormat("void foo() {\n"
16401                "  int myVar = 5;\n"
16402                "  double x = 3.14;\n"
16403                "  auto str = \"Hello \"\n"
16404                "             \"World\";\n"
16405                "  auto s = \"Hello \"\n"
16406                "           \"Again\";\n"
16407                "}",
16408                Style);
16409 
16410   // clang-format off
16411   verifyFormat("void foo() {\n"
16412                "  const int capacityBefore = Entries.capacity();\n"
16413                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16414                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16415                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16416                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16417                "}",
16418                Style);
16419   // clang-format on
16420 
16421   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16422   verifyFormat("void foo() {\n"
16423                "  int myVar = 5;\n"
16424                "  double x  = 3.14;\n"
16425                "  auto str  = \"Hello \"\n"
16426                "              \"World\";\n"
16427                "  auto s    = \"Hello \"\n"
16428                "              \"Again\";\n"
16429                "}",
16430                Style);
16431 
16432   // clang-format off
16433   verifyFormat("void foo() {\n"
16434                "  const int capacityBefore = Entries.capacity();\n"
16435                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16436                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16437                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16438                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16439                "}",
16440                Style);
16441   // clang-format on
16442 
16443   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16444   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16445   verifyFormat("void foo() {\n"
16446                "  int    myVar = 5;\n"
16447                "  double x = 3.14;\n"
16448                "  auto   str = \"Hello \"\n"
16449                "               \"World\";\n"
16450                "  auto   s = \"Hello \"\n"
16451                "             \"Again\";\n"
16452                "}",
16453                Style);
16454 
16455   // clang-format off
16456   verifyFormat("void foo() {\n"
16457                "  const int  capacityBefore = Entries.capacity();\n"
16458                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16459                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16460                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16461                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16462                "}",
16463                Style);
16464   // clang-format on
16465 
16466   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16467   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16468 
16469   verifyFormat("void foo() {\n"
16470                "  int    myVar = 5;\n"
16471                "  double x     = 3.14;\n"
16472                "  auto   str   = \"Hello \"\n"
16473                "                 \"World\";\n"
16474                "  auto   s     = \"Hello \"\n"
16475                "                 \"Again\";\n"
16476                "}",
16477                Style);
16478 
16479   // clang-format off
16480   verifyFormat("void foo() {\n"
16481                "  const int  capacityBefore = Entries.capacity();\n"
16482                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16483                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16484                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
16485                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
16486                "}",
16487                Style);
16488   // clang-format on
16489 
16490   Style = getLLVMStyleWithColumns(120);
16491   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16492   Style.ContinuationIndentWidth = 4;
16493   Style.IndentWidth = 4;
16494 
16495   // clang-format off
16496   verifyFormat("void SomeFunc() {\n"
16497                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16498                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16499                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16500                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16501                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec),\n"
16502                "                                                        seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16503                "}",
16504                Style);
16505   // clang-format on
16506 
16507   Style.BinPackArguments = false;
16508 
16509   // clang-format off
16510   verifyFormat("void SomeFunc() {\n"
16511                "    newWatcher.maxAgeUsec = ToLegacyTimestamp(GetMaxAge(\n"
16512                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16513                "    newWatcher.maxAge     = ToLegacyTimestamp(GetMaxAge(\n"
16514                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16515                "    newWatcher.max        = ToLegacyTimestamp(GetMaxAge(\n"
16516                "        FromLegacyTimestamp<milliseconds>(monitorFrequencyUsec), seconds(std::uint64_t(maxSampleAge)), maxKeepSamples));\n"
16517                "}",
16518                Style);
16519   // clang-format on
16520 }
16521 
TEST_F(FormatTest,AlignWithInitializerPeriods)16522 TEST_F(FormatTest, AlignWithInitializerPeriods) {
16523   auto Style = getLLVMStyleWithColumns(60);
16524 
16525   verifyFormat("void foo1(void) {\n"
16526                "  BYTE p[1] = 1;\n"
16527                "  A B = {.one_foooooooooooooooo = 2,\n"
16528                "         .two_fooooooooooooo = 3,\n"
16529                "         .three_fooooooooooooo = 4};\n"
16530                "  BYTE payload = 2;\n"
16531                "}",
16532                Style);
16533 
16534   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16535   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
16536   verifyFormat("void foo2(void) {\n"
16537                "  BYTE p[1]    = 1;\n"
16538                "  A B          = {.one_foooooooooooooooo = 2,\n"
16539                "                  .two_fooooooooooooo    = 3,\n"
16540                "                  .three_fooooooooooooo  = 4};\n"
16541                "  BYTE payload = 2;\n"
16542                "}",
16543                Style);
16544 
16545   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
16546   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16547   verifyFormat("void foo3(void) {\n"
16548                "  BYTE p[1] = 1;\n"
16549                "  A    B = {.one_foooooooooooooooo = 2,\n"
16550                "            .two_fooooooooooooo = 3,\n"
16551                "            .three_fooooooooooooo = 4};\n"
16552                "  BYTE payload = 2;\n"
16553                "}",
16554                Style);
16555 
16556   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16557   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16558   verifyFormat("void foo4(void) {\n"
16559                "  BYTE p[1]    = 1;\n"
16560                "  A    B       = {.one_foooooooooooooooo = 2,\n"
16561                "                  .two_fooooooooooooo    = 3,\n"
16562                "                  .three_fooooooooooooo  = 4};\n"
16563                "  BYTE payload = 2;\n"
16564                "}",
16565                Style);
16566 }
16567 
TEST_F(FormatTest,LinuxBraceBreaking)16568 TEST_F(FormatTest, LinuxBraceBreaking) {
16569   FormatStyle LinuxBraceStyle = getLLVMStyle();
16570   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
16571   verifyFormat("namespace a\n"
16572                "{\n"
16573                "class A\n"
16574                "{\n"
16575                "  void f()\n"
16576                "  {\n"
16577                "    if (true) {\n"
16578                "      a();\n"
16579                "      b();\n"
16580                "    } else {\n"
16581                "      a();\n"
16582                "    }\n"
16583                "  }\n"
16584                "  void g() { return; }\n"
16585                "};\n"
16586                "struct B {\n"
16587                "  int x;\n"
16588                "};\n"
16589                "} // namespace a\n",
16590                LinuxBraceStyle);
16591   verifyFormat("enum X {\n"
16592                "  Y = 0,\n"
16593                "}\n",
16594                LinuxBraceStyle);
16595   verifyFormat("struct S {\n"
16596                "  int Type;\n"
16597                "  union {\n"
16598                "    int x;\n"
16599                "    double y;\n"
16600                "  } Value;\n"
16601                "  class C\n"
16602                "  {\n"
16603                "    MyFavoriteType Value;\n"
16604                "  } Class;\n"
16605                "}\n",
16606                LinuxBraceStyle);
16607 }
16608 
TEST_F(FormatTest,MozillaBraceBreaking)16609 TEST_F(FormatTest, MozillaBraceBreaking) {
16610   FormatStyle MozillaBraceStyle = getLLVMStyle();
16611   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
16612   MozillaBraceStyle.FixNamespaceComments = false;
16613   verifyFormat("namespace a {\n"
16614                "class A\n"
16615                "{\n"
16616                "  void f()\n"
16617                "  {\n"
16618                "    if (true) {\n"
16619                "      a();\n"
16620                "      b();\n"
16621                "    }\n"
16622                "  }\n"
16623                "  void g() { return; }\n"
16624                "};\n"
16625                "enum E\n"
16626                "{\n"
16627                "  A,\n"
16628                "  // foo\n"
16629                "  B,\n"
16630                "  C\n"
16631                "};\n"
16632                "struct B\n"
16633                "{\n"
16634                "  int x;\n"
16635                "};\n"
16636                "}\n",
16637                MozillaBraceStyle);
16638   verifyFormat("struct S\n"
16639                "{\n"
16640                "  int Type;\n"
16641                "  union\n"
16642                "  {\n"
16643                "    int x;\n"
16644                "    double y;\n"
16645                "  } Value;\n"
16646                "  class C\n"
16647                "  {\n"
16648                "    MyFavoriteType Value;\n"
16649                "  } Class;\n"
16650                "}\n",
16651                MozillaBraceStyle);
16652 }
16653 
TEST_F(FormatTest,StroustrupBraceBreaking)16654 TEST_F(FormatTest, StroustrupBraceBreaking) {
16655   FormatStyle StroustrupBraceStyle = getLLVMStyle();
16656   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
16657   verifyFormat("namespace a {\n"
16658                "class A {\n"
16659                "  void f()\n"
16660                "  {\n"
16661                "    if (true) {\n"
16662                "      a();\n"
16663                "      b();\n"
16664                "    }\n"
16665                "  }\n"
16666                "  void g() { return; }\n"
16667                "};\n"
16668                "struct B {\n"
16669                "  int x;\n"
16670                "};\n"
16671                "} // namespace a\n",
16672                StroustrupBraceStyle);
16673 
16674   verifyFormat("void foo()\n"
16675                "{\n"
16676                "  if (a) {\n"
16677                "    a();\n"
16678                "  }\n"
16679                "  else {\n"
16680                "    b();\n"
16681                "  }\n"
16682                "}\n",
16683                StroustrupBraceStyle);
16684 
16685   verifyFormat("#ifdef _DEBUG\n"
16686                "int foo(int i = 0)\n"
16687                "#else\n"
16688                "int foo(int i = 5)\n"
16689                "#endif\n"
16690                "{\n"
16691                "  return i;\n"
16692                "}",
16693                StroustrupBraceStyle);
16694 
16695   verifyFormat("void foo() {}\n"
16696                "void bar()\n"
16697                "#ifdef _DEBUG\n"
16698                "{\n"
16699                "  foo();\n"
16700                "}\n"
16701                "#else\n"
16702                "{\n"
16703                "}\n"
16704                "#endif",
16705                StroustrupBraceStyle);
16706 
16707   verifyFormat("void foobar() { int i = 5; }\n"
16708                "#ifdef _DEBUG\n"
16709                "void bar() {}\n"
16710                "#else\n"
16711                "void bar() { foobar(); }\n"
16712                "#endif",
16713                StroustrupBraceStyle);
16714 }
16715 
TEST_F(FormatTest,AllmanBraceBreaking)16716 TEST_F(FormatTest, AllmanBraceBreaking) {
16717   FormatStyle AllmanBraceStyle = getLLVMStyle();
16718   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
16719 
16720   EXPECT_EQ("namespace a\n"
16721             "{\n"
16722             "void f();\n"
16723             "void g();\n"
16724             "} // namespace a\n",
16725             format("namespace a\n"
16726                    "{\n"
16727                    "void f();\n"
16728                    "void g();\n"
16729                    "}\n",
16730                    AllmanBraceStyle));
16731 
16732   verifyFormat("namespace a\n"
16733                "{\n"
16734                "class A\n"
16735                "{\n"
16736                "  void f()\n"
16737                "  {\n"
16738                "    if (true)\n"
16739                "    {\n"
16740                "      a();\n"
16741                "      b();\n"
16742                "    }\n"
16743                "  }\n"
16744                "  void g() { return; }\n"
16745                "};\n"
16746                "struct B\n"
16747                "{\n"
16748                "  int x;\n"
16749                "};\n"
16750                "union C\n"
16751                "{\n"
16752                "};\n"
16753                "} // namespace a",
16754                AllmanBraceStyle);
16755 
16756   verifyFormat("void f()\n"
16757                "{\n"
16758                "  if (true)\n"
16759                "  {\n"
16760                "    a();\n"
16761                "  }\n"
16762                "  else if (false)\n"
16763                "  {\n"
16764                "    b();\n"
16765                "  }\n"
16766                "  else\n"
16767                "  {\n"
16768                "    c();\n"
16769                "  }\n"
16770                "}\n",
16771                AllmanBraceStyle);
16772 
16773   verifyFormat("void f()\n"
16774                "{\n"
16775                "  for (int i = 0; i < 10; ++i)\n"
16776                "  {\n"
16777                "    a();\n"
16778                "  }\n"
16779                "  while (false)\n"
16780                "  {\n"
16781                "    b();\n"
16782                "  }\n"
16783                "  do\n"
16784                "  {\n"
16785                "    c();\n"
16786                "  } while (false)\n"
16787                "}\n",
16788                AllmanBraceStyle);
16789 
16790   verifyFormat("void f(int a)\n"
16791                "{\n"
16792                "  switch (a)\n"
16793                "  {\n"
16794                "  case 0:\n"
16795                "    break;\n"
16796                "  case 1:\n"
16797                "  {\n"
16798                "    break;\n"
16799                "  }\n"
16800                "  case 2:\n"
16801                "  {\n"
16802                "  }\n"
16803                "  break;\n"
16804                "  default:\n"
16805                "    break;\n"
16806                "  }\n"
16807                "}\n",
16808                AllmanBraceStyle);
16809 
16810   verifyFormat("enum X\n"
16811                "{\n"
16812                "  Y = 0,\n"
16813                "}\n",
16814                AllmanBraceStyle);
16815   verifyFormat("enum X\n"
16816                "{\n"
16817                "  Y = 0\n"
16818                "}\n",
16819                AllmanBraceStyle);
16820 
16821   verifyFormat("@interface BSApplicationController ()\n"
16822                "{\n"
16823                "@private\n"
16824                "  id _extraIvar;\n"
16825                "}\n"
16826                "@end\n",
16827                AllmanBraceStyle);
16828 
16829   verifyFormat("#ifdef _DEBUG\n"
16830                "int foo(int i = 0)\n"
16831                "#else\n"
16832                "int foo(int i = 5)\n"
16833                "#endif\n"
16834                "{\n"
16835                "  return i;\n"
16836                "}",
16837                AllmanBraceStyle);
16838 
16839   verifyFormat("void foo() {}\n"
16840                "void bar()\n"
16841                "#ifdef _DEBUG\n"
16842                "{\n"
16843                "  foo();\n"
16844                "}\n"
16845                "#else\n"
16846                "{\n"
16847                "}\n"
16848                "#endif",
16849                AllmanBraceStyle);
16850 
16851   verifyFormat("void foobar() { int i = 5; }\n"
16852                "#ifdef _DEBUG\n"
16853                "void bar() {}\n"
16854                "#else\n"
16855                "void bar() { foobar(); }\n"
16856                "#endif",
16857                AllmanBraceStyle);
16858 
16859   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
16860             FormatStyle::SLS_All);
16861 
16862   verifyFormat("[](int i) { return i + 2; };\n"
16863                "[](int i, int j)\n"
16864                "{\n"
16865                "  auto x = i + j;\n"
16866                "  auto y = i * j;\n"
16867                "  return x ^ y;\n"
16868                "};\n"
16869                "void foo()\n"
16870                "{\n"
16871                "  auto shortLambda = [](int i) { return i + 2; };\n"
16872                "  auto longLambda = [](int i, int j)\n"
16873                "  {\n"
16874                "    auto x = i + j;\n"
16875                "    auto y = i * j;\n"
16876                "    return x ^ y;\n"
16877                "  };\n"
16878                "}",
16879                AllmanBraceStyle);
16880 
16881   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
16882 
16883   verifyFormat("[](int i)\n"
16884                "{\n"
16885                "  return i + 2;\n"
16886                "};\n"
16887                "[](int i, int j)\n"
16888                "{\n"
16889                "  auto x = i + j;\n"
16890                "  auto y = i * j;\n"
16891                "  return x ^ y;\n"
16892                "};\n"
16893                "void foo()\n"
16894                "{\n"
16895                "  auto shortLambda = [](int i)\n"
16896                "  {\n"
16897                "    return i + 2;\n"
16898                "  };\n"
16899                "  auto longLambda = [](int i, int j)\n"
16900                "  {\n"
16901                "    auto x = i + j;\n"
16902                "    auto y = i * j;\n"
16903                "    return x ^ y;\n"
16904                "  };\n"
16905                "}",
16906                AllmanBraceStyle);
16907 
16908   // Reset
16909   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
16910 
16911   // This shouldn't affect ObjC blocks..
16912   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
16913                "  // ...\n"
16914                "  int i;\n"
16915                "}];",
16916                AllmanBraceStyle);
16917   verifyFormat("void (^block)(void) = ^{\n"
16918                "  // ...\n"
16919                "  int i;\n"
16920                "};",
16921                AllmanBraceStyle);
16922   // .. or dict literals.
16923   verifyFormat("void f()\n"
16924                "{\n"
16925                "  // ...\n"
16926                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
16927                "}",
16928                AllmanBraceStyle);
16929   verifyFormat("void f()\n"
16930                "{\n"
16931                "  // ...\n"
16932                "  [object someMethod:@{a : @\"b\"}];\n"
16933                "}",
16934                AllmanBraceStyle);
16935   verifyFormat("int f()\n"
16936                "{ // comment\n"
16937                "  return 42;\n"
16938                "}",
16939                AllmanBraceStyle);
16940 
16941   AllmanBraceStyle.ColumnLimit = 19;
16942   verifyFormat("void f() { int i; }", AllmanBraceStyle);
16943   AllmanBraceStyle.ColumnLimit = 18;
16944   verifyFormat("void f()\n"
16945                "{\n"
16946                "  int i;\n"
16947                "}",
16948                AllmanBraceStyle);
16949   AllmanBraceStyle.ColumnLimit = 80;
16950 
16951   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
16952   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
16953       FormatStyle::SIS_WithoutElse;
16954   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
16955   verifyFormat("void f(bool b)\n"
16956                "{\n"
16957                "  if (b)\n"
16958                "  {\n"
16959                "    return;\n"
16960                "  }\n"
16961                "}\n",
16962                BreakBeforeBraceShortIfs);
16963   verifyFormat("void f(bool b)\n"
16964                "{\n"
16965                "  if constexpr (b)\n"
16966                "  {\n"
16967                "    return;\n"
16968                "  }\n"
16969                "}\n",
16970                BreakBeforeBraceShortIfs);
16971   verifyFormat("void f(bool b)\n"
16972                "{\n"
16973                "  if CONSTEXPR (b)\n"
16974                "  {\n"
16975                "    return;\n"
16976                "  }\n"
16977                "}\n",
16978                BreakBeforeBraceShortIfs);
16979   verifyFormat("void f(bool b)\n"
16980                "{\n"
16981                "  if (b) return;\n"
16982                "}\n",
16983                BreakBeforeBraceShortIfs);
16984   verifyFormat("void f(bool b)\n"
16985                "{\n"
16986                "  if constexpr (b) return;\n"
16987                "}\n",
16988                BreakBeforeBraceShortIfs);
16989   verifyFormat("void f(bool b)\n"
16990                "{\n"
16991                "  if CONSTEXPR (b) return;\n"
16992                "}\n",
16993                BreakBeforeBraceShortIfs);
16994   verifyFormat("void f(bool b)\n"
16995                "{\n"
16996                "  while (b)\n"
16997                "  {\n"
16998                "    return;\n"
16999                "  }\n"
17000                "}\n",
17001                BreakBeforeBraceShortIfs);
17002 }
17003 
TEST_F(FormatTest,WhitesmithsBraceBreaking)17004 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
17005   FormatStyle WhitesmithsBraceStyle = getLLVMStyle();
17006   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
17007 
17008   // Make a few changes to the style for testing purposes
17009   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
17010       FormatStyle::SFS_Empty;
17011   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17012   WhitesmithsBraceStyle.ColumnLimit = 0;
17013 
17014   // FIXME: this test case can't decide whether there should be a blank line
17015   // after the ~D() line or not. It adds one if one doesn't exist in the test
17016   // and it removes the line if one exists.
17017   /*
17018   verifyFormat("class A;\n"
17019                "namespace B\n"
17020                "  {\n"
17021                "class C;\n"
17022                "// Comment\n"
17023                "class D\n"
17024                "  {\n"
17025                "public:\n"
17026                "  D();\n"
17027                "  ~D() {}\n"
17028                "private:\n"
17029                "  enum E\n"
17030                "    {\n"
17031                "    F\n"
17032                "    }\n"
17033                "  };\n"
17034                "  } // namespace B\n",
17035                WhitesmithsBraceStyle);
17036   */
17037 
17038   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
17039   verifyFormat("namespace a\n"
17040                "  {\n"
17041                "class A\n"
17042                "  {\n"
17043                "  void f()\n"
17044                "    {\n"
17045                "    if (true)\n"
17046                "      {\n"
17047                "      a();\n"
17048                "      b();\n"
17049                "      }\n"
17050                "    }\n"
17051                "  void g()\n"
17052                "    {\n"
17053                "    return;\n"
17054                "    }\n"
17055                "  };\n"
17056                "struct B\n"
17057                "  {\n"
17058                "  int x;\n"
17059                "  };\n"
17060                "  } // namespace a",
17061                WhitesmithsBraceStyle);
17062 
17063   verifyFormat("namespace a\n"
17064                "  {\n"
17065                "namespace b\n"
17066                "  {\n"
17067                "class A\n"
17068                "  {\n"
17069                "  void f()\n"
17070                "    {\n"
17071                "    if (true)\n"
17072                "      {\n"
17073                "      a();\n"
17074                "      b();\n"
17075                "      }\n"
17076                "    }\n"
17077                "  void g()\n"
17078                "    {\n"
17079                "    return;\n"
17080                "    }\n"
17081                "  };\n"
17082                "struct B\n"
17083                "  {\n"
17084                "  int x;\n"
17085                "  };\n"
17086                "  } // namespace b\n"
17087                "  } // namespace a",
17088                WhitesmithsBraceStyle);
17089 
17090   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
17091   verifyFormat("namespace a\n"
17092                "  {\n"
17093                "namespace b\n"
17094                "  {\n"
17095                "  class A\n"
17096                "    {\n"
17097                "    void f()\n"
17098                "      {\n"
17099                "      if (true)\n"
17100                "        {\n"
17101                "        a();\n"
17102                "        b();\n"
17103                "        }\n"
17104                "      }\n"
17105                "    void g()\n"
17106                "      {\n"
17107                "      return;\n"
17108                "      }\n"
17109                "    };\n"
17110                "  struct B\n"
17111                "    {\n"
17112                "    int x;\n"
17113                "    };\n"
17114                "  } // namespace b\n"
17115                "  } // namespace a",
17116                WhitesmithsBraceStyle);
17117 
17118   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
17119   verifyFormat("namespace a\n"
17120                "  {\n"
17121                "  namespace b\n"
17122                "    {\n"
17123                "    class A\n"
17124                "      {\n"
17125                "      void f()\n"
17126                "        {\n"
17127                "        if (true)\n"
17128                "          {\n"
17129                "          a();\n"
17130                "          b();\n"
17131                "          }\n"
17132                "        }\n"
17133                "      void g()\n"
17134                "        {\n"
17135                "        return;\n"
17136                "        }\n"
17137                "      };\n"
17138                "    struct B\n"
17139                "      {\n"
17140                "      int x;\n"
17141                "      };\n"
17142                "    } // namespace b\n"
17143                "  }   // namespace a",
17144                WhitesmithsBraceStyle);
17145 
17146   verifyFormat("void f()\n"
17147                "  {\n"
17148                "  if (true)\n"
17149                "    {\n"
17150                "    a();\n"
17151                "    }\n"
17152                "  else if (false)\n"
17153                "    {\n"
17154                "    b();\n"
17155                "    }\n"
17156                "  else\n"
17157                "    {\n"
17158                "    c();\n"
17159                "    }\n"
17160                "  }\n",
17161                WhitesmithsBraceStyle);
17162 
17163   verifyFormat("void f()\n"
17164                "  {\n"
17165                "  for (int i = 0; i < 10; ++i)\n"
17166                "    {\n"
17167                "    a();\n"
17168                "    }\n"
17169                "  while (false)\n"
17170                "    {\n"
17171                "    b();\n"
17172                "    }\n"
17173                "  do\n"
17174                "    {\n"
17175                "    c();\n"
17176                "    } while (false)\n"
17177                "  }\n",
17178                WhitesmithsBraceStyle);
17179 
17180   WhitesmithsBraceStyle.IndentCaseLabels = true;
17181   verifyFormat("void switchTest1(int a)\n"
17182                "  {\n"
17183                "  switch (a)\n"
17184                "    {\n"
17185                "    case 2:\n"
17186                "      {\n"
17187                "      }\n"
17188                "      break;\n"
17189                "    }\n"
17190                "  }\n",
17191                WhitesmithsBraceStyle);
17192 
17193   verifyFormat("void switchTest2(int a)\n"
17194                "  {\n"
17195                "  switch (a)\n"
17196                "    {\n"
17197                "    case 0:\n"
17198                "      break;\n"
17199                "    case 1:\n"
17200                "      {\n"
17201                "      break;\n"
17202                "      }\n"
17203                "    case 2:\n"
17204                "      {\n"
17205                "      }\n"
17206                "      break;\n"
17207                "    default:\n"
17208                "      break;\n"
17209                "    }\n"
17210                "  }\n",
17211                WhitesmithsBraceStyle);
17212 
17213   verifyFormat("void switchTest3(int a)\n"
17214                "  {\n"
17215                "  switch (a)\n"
17216                "    {\n"
17217                "    case 0:\n"
17218                "      {\n"
17219                "      foo(x);\n"
17220                "      }\n"
17221                "      break;\n"
17222                "    default:\n"
17223                "      {\n"
17224                "      foo(1);\n"
17225                "      }\n"
17226                "      break;\n"
17227                "    }\n"
17228                "  }\n",
17229                WhitesmithsBraceStyle);
17230 
17231   WhitesmithsBraceStyle.IndentCaseLabels = false;
17232 
17233   verifyFormat("void switchTest4(int a)\n"
17234                "  {\n"
17235                "  switch (a)\n"
17236                "    {\n"
17237                "  case 2:\n"
17238                "    {\n"
17239                "    }\n"
17240                "    break;\n"
17241                "    }\n"
17242                "  }\n",
17243                WhitesmithsBraceStyle);
17244 
17245   verifyFormat("void switchTest5(int a)\n"
17246                "  {\n"
17247                "  switch (a)\n"
17248                "    {\n"
17249                "  case 0:\n"
17250                "    break;\n"
17251                "  case 1:\n"
17252                "    {\n"
17253                "    foo();\n"
17254                "    break;\n"
17255                "    }\n"
17256                "  case 2:\n"
17257                "    {\n"
17258                "    }\n"
17259                "    break;\n"
17260                "  default:\n"
17261                "    break;\n"
17262                "    }\n"
17263                "  }\n",
17264                WhitesmithsBraceStyle);
17265 
17266   verifyFormat("void switchTest6(int a)\n"
17267                "  {\n"
17268                "  switch (a)\n"
17269                "    {\n"
17270                "  case 0:\n"
17271                "    {\n"
17272                "    foo(x);\n"
17273                "    }\n"
17274                "    break;\n"
17275                "  default:\n"
17276                "    {\n"
17277                "    foo(1);\n"
17278                "    }\n"
17279                "    break;\n"
17280                "    }\n"
17281                "  }\n",
17282                WhitesmithsBraceStyle);
17283 
17284   verifyFormat("enum X\n"
17285                "  {\n"
17286                "  Y = 0, // testing\n"
17287                "  }\n",
17288                WhitesmithsBraceStyle);
17289 
17290   verifyFormat("enum X\n"
17291                "  {\n"
17292                "  Y = 0\n"
17293                "  }\n",
17294                WhitesmithsBraceStyle);
17295   verifyFormat("enum X\n"
17296                "  {\n"
17297                "  Y = 0,\n"
17298                "  Z = 1\n"
17299                "  };\n",
17300                WhitesmithsBraceStyle);
17301 
17302   verifyFormat("@interface BSApplicationController ()\n"
17303                "  {\n"
17304                "@private\n"
17305                "  id _extraIvar;\n"
17306                "  }\n"
17307                "@end\n",
17308                WhitesmithsBraceStyle);
17309 
17310   verifyFormat("#ifdef _DEBUG\n"
17311                "int foo(int i = 0)\n"
17312                "#else\n"
17313                "int foo(int i = 5)\n"
17314                "#endif\n"
17315                "  {\n"
17316                "  return i;\n"
17317                "  }",
17318                WhitesmithsBraceStyle);
17319 
17320   verifyFormat("void foo() {}\n"
17321                "void bar()\n"
17322                "#ifdef _DEBUG\n"
17323                "  {\n"
17324                "  foo();\n"
17325                "  }\n"
17326                "#else\n"
17327                "  {\n"
17328                "  }\n"
17329                "#endif",
17330                WhitesmithsBraceStyle);
17331 
17332   verifyFormat("void foobar()\n"
17333                "  {\n"
17334                "  int i = 5;\n"
17335                "  }\n"
17336                "#ifdef _DEBUG\n"
17337                "void bar()\n"
17338                "  {\n"
17339                "  }\n"
17340                "#else\n"
17341                "void bar()\n"
17342                "  {\n"
17343                "  foobar();\n"
17344                "  }\n"
17345                "#endif",
17346                WhitesmithsBraceStyle);
17347 
17348   // This shouldn't affect ObjC blocks..
17349   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
17350                "  // ...\n"
17351                "  int i;\n"
17352                "}];",
17353                WhitesmithsBraceStyle);
17354   verifyFormat("void (^block)(void) = ^{\n"
17355                "  // ...\n"
17356                "  int i;\n"
17357                "};",
17358                WhitesmithsBraceStyle);
17359   // .. or dict literals.
17360   verifyFormat("void f()\n"
17361                "  {\n"
17362                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
17363                "  }",
17364                WhitesmithsBraceStyle);
17365 
17366   verifyFormat("int f()\n"
17367                "  { // comment\n"
17368                "  return 42;\n"
17369                "  }",
17370                WhitesmithsBraceStyle);
17371 
17372   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
17373   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
17374       FormatStyle::SIS_OnlyFirstIf;
17375   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
17376   verifyFormat("void f(bool b)\n"
17377                "  {\n"
17378                "  if (b)\n"
17379                "    {\n"
17380                "    return;\n"
17381                "    }\n"
17382                "  }\n",
17383                BreakBeforeBraceShortIfs);
17384   verifyFormat("void f(bool b)\n"
17385                "  {\n"
17386                "  if (b) return;\n"
17387                "  }\n",
17388                BreakBeforeBraceShortIfs);
17389   verifyFormat("void f(bool b)\n"
17390                "  {\n"
17391                "  while (b)\n"
17392                "    {\n"
17393                "    return;\n"
17394                "    }\n"
17395                "  }\n",
17396                BreakBeforeBraceShortIfs);
17397 }
17398 
TEST_F(FormatTest,GNUBraceBreaking)17399 TEST_F(FormatTest, GNUBraceBreaking) {
17400   FormatStyle GNUBraceStyle = getLLVMStyle();
17401   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
17402   verifyFormat("namespace a\n"
17403                "{\n"
17404                "class A\n"
17405                "{\n"
17406                "  void f()\n"
17407                "  {\n"
17408                "    int a;\n"
17409                "    {\n"
17410                "      int b;\n"
17411                "    }\n"
17412                "    if (true)\n"
17413                "      {\n"
17414                "        a();\n"
17415                "        b();\n"
17416                "      }\n"
17417                "  }\n"
17418                "  void g() { return; }\n"
17419                "}\n"
17420                "} // namespace a",
17421                GNUBraceStyle);
17422 
17423   verifyFormat("void f()\n"
17424                "{\n"
17425                "  if (true)\n"
17426                "    {\n"
17427                "      a();\n"
17428                "    }\n"
17429                "  else if (false)\n"
17430                "    {\n"
17431                "      b();\n"
17432                "    }\n"
17433                "  else\n"
17434                "    {\n"
17435                "      c();\n"
17436                "    }\n"
17437                "}\n",
17438                GNUBraceStyle);
17439 
17440   verifyFormat("void f()\n"
17441                "{\n"
17442                "  for (int i = 0; i < 10; ++i)\n"
17443                "    {\n"
17444                "      a();\n"
17445                "    }\n"
17446                "  while (false)\n"
17447                "    {\n"
17448                "      b();\n"
17449                "    }\n"
17450                "  do\n"
17451                "    {\n"
17452                "      c();\n"
17453                "    }\n"
17454                "  while (false);\n"
17455                "}\n",
17456                GNUBraceStyle);
17457 
17458   verifyFormat("void f(int a)\n"
17459                "{\n"
17460                "  switch (a)\n"
17461                "    {\n"
17462                "    case 0:\n"
17463                "      break;\n"
17464                "    case 1:\n"
17465                "      {\n"
17466                "        break;\n"
17467                "      }\n"
17468                "    case 2:\n"
17469                "      {\n"
17470                "      }\n"
17471                "      break;\n"
17472                "    default:\n"
17473                "      break;\n"
17474                "    }\n"
17475                "}\n",
17476                GNUBraceStyle);
17477 
17478   verifyFormat("enum X\n"
17479                "{\n"
17480                "  Y = 0,\n"
17481                "}\n",
17482                GNUBraceStyle);
17483 
17484   verifyFormat("@interface BSApplicationController ()\n"
17485                "{\n"
17486                "@private\n"
17487                "  id _extraIvar;\n"
17488                "}\n"
17489                "@end\n",
17490                GNUBraceStyle);
17491 
17492   verifyFormat("#ifdef _DEBUG\n"
17493                "int foo(int i = 0)\n"
17494                "#else\n"
17495                "int foo(int i = 5)\n"
17496                "#endif\n"
17497                "{\n"
17498                "  return i;\n"
17499                "}",
17500                GNUBraceStyle);
17501 
17502   verifyFormat("void foo() {}\n"
17503                "void bar()\n"
17504                "#ifdef _DEBUG\n"
17505                "{\n"
17506                "  foo();\n"
17507                "}\n"
17508                "#else\n"
17509                "{\n"
17510                "}\n"
17511                "#endif",
17512                GNUBraceStyle);
17513 
17514   verifyFormat("void foobar() { int i = 5; }\n"
17515                "#ifdef _DEBUG\n"
17516                "void bar() {}\n"
17517                "#else\n"
17518                "void bar() { foobar(); }\n"
17519                "#endif",
17520                GNUBraceStyle);
17521 }
17522 
TEST_F(FormatTest,WebKitBraceBreaking)17523 TEST_F(FormatTest, WebKitBraceBreaking) {
17524   FormatStyle WebKitBraceStyle = getLLVMStyle();
17525   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
17526   WebKitBraceStyle.FixNamespaceComments = false;
17527   verifyFormat("namespace a {\n"
17528                "class A {\n"
17529                "  void f()\n"
17530                "  {\n"
17531                "    if (true) {\n"
17532                "      a();\n"
17533                "      b();\n"
17534                "    }\n"
17535                "  }\n"
17536                "  void g() { return; }\n"
17537                "};\n"
17538                "enum E {\n"
17539                "  A,\n"
17540                "  // foo\n"
17541                "  B,\n"
17542                "  C\n"
17543                "};\n"
17544                "struct B {\n"
17545                "  int x;\n"
17546                "};\n"
17547                "}\n",
17548                WebKitBraceStyle);
17549   verifyFormat("struct S {\n"
17550                "  int Type;\n"
17551                "  union {\n"
17552                "    int x;\n"
17553                "    double y;\n"
17554                "  } Value;\n"
17555                "  class C {\n"
17556                "    MyFavoriteType Value;\n"
17557                "  } Class;\n"
17558                "};\n",
17559                WebKitBraceStyle);
17560 }
17561 
TEST_F(FormatTest,CatchExceptionReferenceBinding)17562 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
17563   verifyFormat("void f() {\n"
17564                "  try {\n"
17565                "  } catch (const Exception &e) {\n"
17566                "  }\n"
17567                "}\n",
17568                getLLVMStyle());
17569 }
17570 
TEST_F(FormatTest,CatchAlignArrayOfStructuresRightAlignment)17571 TEST_F(FormatTest, CatchAlignArrayOfStructuresRightAlignment) {
17572   auto Style = getLLVMStyle();
17573   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
17574   Style.AlignConsecutiveAssignments =
17575       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17576   Style.AlignConsecutiveDeclarations =
17577       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17578   verifyFormat("struct test demo[] = {\n"
17579                "    {56,    23, \"hello\"},\n"
17580                "    {-1, 93463, \"world\"},\n"
17581                "    { 7,     5,    \"!!\"}\n"
17582                "};\n",
17583                Style);
17584 
17585   verifyFormat("struct test demo[] = {\n"
17586                "    {56,    23, \"hello\"}, // first line\n"
17587                "    {-1, 93463, \"world\"}, // second line\n"
17588                "    { 7,     5,    \"!!\"}  // third line\n"
17589                "};\n",
17590                Style);
17591 
17592   verifyFormat("struct test demo[4] = {\n"
17593                "    { 56,    23, 21,       \"oh\"}, // first line\n"
17594                "    { -1, 93463, 22,       \"my\"}, // second line\n"
17595                "    {  7,     5,  1, \"goodness\"}  // third line\n"
17596                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
17597                "};\n",
17598                Style);
17599 
17600   verifyFormat("struct test demo[3] = {\n"
17601                "    {56,    23, \"hello\"},\n"
17602                "    {-1, 93463, \"world\"},\n"
17603                "    { 7,     5,    \"!!\"}\n"
17604                "};\n",
17605                Style);
17606 
17607   verifyFormat("struct test demo[3] = {\n"
17608                "    {int{56},    23, \"hello\"},\n"
17609                "    {int{-1}, 93463, \"world\"},\n"
17610                "    { int{7},     5,    \"!!\"}\n"
17611                "};\n",
17612                Style);
17613 
17614   verifyFormat("struct test demo[] = {\n"
17615                "    {56,    23, \"hello\"},\n"
17616                "    {-1, 93463, \"world\"},\n"
17617                "    { 7,     5,    \"!!\"},\n"
17618                "};\n",
17619                Style);
17620 
17621   verifyFormat("test demo[] = {\n"
17622                "    {56,    23, \"hello\"},\n"
17623                "    {-1, 93463, \"world\"},\n"
17624                "    { 7,     5,    \"!!\"},\n"
17625                "};\n",
17626                Style);
17627 
17628   verifyFormat("demo = std::array<struct test, 3>{\n"
17629                "    test{56,    23, \"hello\"},\n"
17630                "    test{-1, 93463, \"world\"},\n"
17631                "    test{ 7,     5,    \"!!\"},\n"
17632                "};\n",
17633                Style);
17634 
17635   verifyFormat("test demo[] = {\n"
17636                "    {56,    23, \"hello\"},\n"
17637                "#if X\n"
17638                "    {-1, 93463, \"world\"},\n"
17639                "#endif\n"
17640                "    { 7,     5,    \"!!\"}\n"
17641                "};\n",
17642                Style);
17643 
17644   verifyFormat(
17645       "test demo[] = {\n"
17646       "    { 7,    23,\n"
17647       "     \"hello world i am a very long line that really, in any\"\n"
17648       "     \"just world, ought to be split over multiple lines\"},\n"
17649       "    {-1, 93463,                                  \"world\"},\n"
17650       "    {56,     5,                                     \"!!\"}\n"
17651       "};\n",
17652       Style);
17653 
17654   verifyFormat("return GradForUnaryCwise(g, {\n"
17655                "                                {{\"sign\"}, \"Sign\",  "
17656                "  {\"x\", \"dy\"}},\n"
17657                "                                {  {\"dx\"},  \"Mul\", {\"dy\""
17658                ", \"sign\"}},\n"
17659                "});\n",
17660                Style);
17661 
17662   Style.ColumnLimit = 0;
17663   EXPECT_EQ(
17664       "test demo[] = {\n"
17665       "    {56,    23, \"hello world i am a very long line that really, "
17666       "in any just world, ought to be split over multiple lines\"},\n"
17667       "    {-1, 93463,                                                  "
17668       "                                                 \"world\"},\n"
17669       "    { 7,     5,                                                  "
17670       "                                                    \"!!\"},\n"
17671       "};",
17672       format("test demo[] = {{56, 23, \"hello world i am a very long line "
17673              "that really, in any just world, ought to be split over multiple "
17674              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17675              Style));
17676 
17677   Style.ColumnLimit = 80;
17678   verifyFormat("test demo[] = {\n"
17679                "    {56,    23, /* a comment */ \"hello\"},\n"
17680                "    {-1, 93463,                 \"world\"},\n"
17681                "    { 7,     5,                    \"!!\"}\n"
17682                "};\n",
17683                Style);
17684 
17685   verifyFormat("test demo[] = {\n"
17686                "    {56,    23,                    \"hello\"},\n"
17687                "    {-1, 93463, \"world\" /* comment here */},\n"
17688                "    { 7,     5,                       \"!!\"}\n"
17689                "};\n",
17690                Style);
17691 
17692   verifyFormat("test demo[] = {\n"
17693                "    {56, /* a comment */ 23, \"hello\"},\n"
17694                "    {-1,              93463, \"world\"},\n"
17695                "    { 7,                  5,    \"!!\"}\n"
17696                "};\n",
17697                Style);
17698 
17699   Style.ColumnLimit = 20;
17700   EXPECT_EQ(
17701       "demo = std::array<\n"
17702       "    struct test, 3>{\n"
17703       "    test{\n"
17704       "         56,    23,\n"
17705       "         \"hello \"\n"
17706       "         \"world i \"\n"
17707       "         \"am a very \"\n"
17708       "         \"long line \"\n"
17709       "         \"that \"\n"
17710       "         \"really, \"\n"
17711       "         \"in any \"\n"
17712       "         \"just \"\n"
17713       "         \"world, \"\n"
17714       "         \"ought to \"\n"
17715       "         \"be split \"\n"
17716       "         \"over \"\n"
17717       "         \"multiple \"\n"
17718       "         \"lines\"},\n"
17719       "    test{-1, 93463,\n"
17720       "         \"world\"},\n"
17721       "    test{ 7,     5,\n"
17722       "         \"!!\"   },\n"
17723       "};",
17724       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
17725              "i am a very long line that really, in any just world, ought "
17726              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
17727              "test{7, 5, \"!!\"},};",
17728              Style));
17729   // This caused a core dump by enabling Alignment in the LLVMStyle globally
17730   Style = getLLVMStyleWithColumns(50);
17731   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
17732   verifyFormat("static A x = {\n"
17733                "    {{init1, init2, init3, init4},\n"
17734                "     {init1, init2, init3, init4}}\n"
17735                "};",
17736                Style);
17737   Style.ColumnLimit = 100;
17738   EXPECT_EQ(
17739       "test demo[] = {\n"
17740       "    {56,    23,\n"
17741       "     \"hello world i am a very long line that really, in any just world"
17742       ", ought to be split over \"\n"
17743       "     \"multiple lines\"  },\n"
17744       "    {-1, 93463, \"world\"},\n"
17745       "    { 7,     5,    \"!!\"},\n"
17746       "};",
17747       format("test demo[] = {{56, 23, \"hello world i am a very long line "
17748              "that really, in any just world, ought to be split over multiple "
17749              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17750              Style));
17751 
17752   Style = getLLVMStyleWithColumns(50);
17753   Style.AlignArrayOfStructures = FormatStyle::AIAS_Right;
17754   Style.AlignConsecutiveAssignments =
17755       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17756   Style.AlignConsecutiveDeclarations =
17757       FormatStyle::AlignConsecutiveStyle::ACS_Consecutive;
17758   verifyFormat("struct test demo[] = {\n"
17759                "    {56,    23, \"hello\"},\n"
17760                "    {-1, 93463, \"world\"},\n"
17761                "    { 7,     5,    \"!!\"}\n"
17762                "};\n"
17763                "static A x = {\n"
17764                "    {{init1, init2, init3, init4},\n"
17765                "     {init1, init2, init3, init4}}\n"
17766                "};",
17767                Style);
17768   Style.ColumnLimit = 100;
17769   Style.AlignConsecutiveAssignments =
17770       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
17771   Style.AlignConsecutiveDeclarations =
17772       FormatStyle::AlignConsecutiveStyle::ACS_AcrossComments;
17773   verifyFormat("struct test demo[] = {\n"
17774                "    {56,    23, \"hello\"},\n"
17775                "    {-1, 93463, \"world\"},\n"
17776                "    { 7,     5,    \"!!\"}\n"
17777                "};\n"
17778                "struct test demo[4] = {\n"
17779                "    { 56,    23, 21,       \"oh\"}, // first line\n"
17780                "    { -1, 93463, 22,       \"my\"}, // second line\n"
17781                "    {  7,     5,  1, \"goodness\"}  // third line\n"
17782                "    {234,     5,  1, \"gracious\"}  // fourth line\n"
17783                "};\n",
17784                Style);
17785   EXPECT_EQ(
17786       "test demo[] = {\n"
17787       "    {56,\n"
17788       "     \"hello world i am a very long line that really, in any just world"
17789       ", ought to be split over \"\n"
17790       "     \"multiple lines\",    23},\n"
17791       "    {-1,      \"world\", 93463},\n"
17792       "    { 7,         \"!!\",     5},\n"
17793       "};",
17794       format("test demo[] = {{56, \"hello world i am a very long line "
17795              "that really, in any just world, ought to be split over multiple "
17796              "lines\", 23},{-1, \"world\", 93463},{7, \"!!\", 5},};",
17797              Style));
17798 }
17799 
TEST_F(FormatTest,CatchAlignArrayOfStructuresLeftAlignment)17800 TEST_F(FormatTest, CatchAlignArrayOfStructuresLeftAlignment) {
17801   auto Style = getLLVMStyle();
17802   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
17803   /* FIXME: This case gets misformatted.
17804   verifyFormat("auto foo = Items{\n"
17805                "    Section{0, bar(), },\n"
17806                "    Section{1, boo()  }\n"
17807                "};\n",
17808                Style);
17809   */
17810   verifyFormat("auto foo = Items{\n"
17811                "    Section{\n"
17812                "            0, bar(),\n"
17813                "            }\n"
17814                "};\n",
17815                Style);
17816   verifyFormat("struct test demo[] = {\n"
17817                "    {56, 23,    \"hello\"},\n"
17818                "    {-1, 93463, \"world\"},\n"
17819                "    {7,  5,     \"!!\"   }\n"
17820                "};\n",
17821                Style);
17822   verifyFormat("struct test demo[] = {\n"
17823                "    {56, 23,    \"hello\"}, // first line\n"
17824                "    {-1, 93463, \"world\"}, // second line\n"
17825                "    {7,  5,     \"!!\"   }  // third line\n"
17826                "};\n",
17827                Style);
17828   verifyFormat("struct test demo[4] = {\n"
17829                "    {56,  23,    21, \"oh\"      }, // first line\n"
17830                "    {-1,  93463, 22, \"my\"      }, // second line\n"
17831                "    {7,   5,     1,  \"goodness\"}  // third line\n"
17832                "    {234, 5,     1,  \"gracious\"}  // fourth line\n"
17833                "};\n",
17834                Style);
17835   verifyFormat("struct test demo[3] = {\n"
17836                "    {56, 23,    \"hello\"},\n"
17837                "    {-1, 93463, \"world\"},\n"
17838                "    {7,  5,     \"!!\"   }\n"
17839                "};\n",
17840                Style);
17841 
17842   verifyFormat("struct test demo[3] = {\n"
17843                "    {int{56}, 23,    \"hello\"},\n"
17844                "    {int{-1}, 93463, \"world\"},\n"
17845                "    {int{7},  5,     \"!!\"   }\n"
17846                "};\n",
17847                Style);
17848   verifyFormat("struct test demo[] = {\n"
17849                "    {56, 23,    \"hello\"},\n"
17850                "    {-1, 93463, \"world\"},\n"
17851                "    {7,  5,     \"!!\"   },\n"
17852                "};\n",
17853                Style);
17854   verifyFormat("test demo[] = {\n"
17855                "    {56, 23,    \"hello\"},\n"
17856                "    {-1, 93463, \"world\"},\n"
17857                "    {7,  5,     \"!!\"   },\n"
17858                "};\n",
17859                Style);
17860   verifyFormat("demo = std::array<struct test, 3>{\n"
17861                "    test{56, 23,    \"hello\"},\n"
17862                "    test{-1, 93463, \"world\"},\n"
17863                "    test{7,  5,     \"!!\"   },\n"
17864                "};\n",
17865                Style);
17866   verifyFormat("test demo[] = {\n"
17867                "    {56, 23,    \"hello\"},\n"
17868                "#if X\n"
17869                "    {-1, 93463, \"world\"},\n"
17870                "#endif\n"
17871                "    {7,  5,     \"!!\"   }\n"
17872                "};\n",
17873                Style);
17874   verifyFormat(
17875       "test demo[] = {\n"
17876       "    {7,  23,\n"
17877       "     \"hello world i am a very long line that really, in any\"\n"
17878       "     \"just world, ought to be split over multiple lines\"},\n"
17879       "    {-1, 93463, \"world\"                                 },\n"
17880       "    {56, 5,     \"!!\"                                    }\n"
17881       "};\n",
17882       Style);
17883 
17884   verifyFormat("return GradForUnaryCwise(g, {\n"
17885                "                                {{\"sign\"}, \"Sign\", {\"x\", "
17886                "\"dy\"}   },\n"
17887                "                                {{\"dx\"},   \"Mul\",  "
17888                "{\"dy\", \"sign\"}},\n"
17889                "});\n",
17890                Style);
17891 
17892   Style.ColumnLimit = 0;
17893   EXPECT_EQ(
17894       "test demo[] = {\n"
17895       "    {56, 23,    \"hello world i am a very long line that really, in any "
17896       "just world, ought to be split over multiple lines\"},\n"
17897       "    {-1, 93463, \"world\"                                               "
17898       "                                                   },\n"
17899       "    {7,  5,     \"!!\"                                                  "
17900       "                                                   },\n"
17901       "};",
17902       format("test demo[] = {{56, 23, \"hello world i am a very long line "
17903              "that really, in any just world, ought to be split over multiple "
17904              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17905              Style));
17906 
17907   Style.ColumnLimit = 80;
17908   verifyFormat("test demo[] = {\n"
17909                "    {56, 23,    /* a comment */ \"hello\"},\n"
17910                "    {-1, 93463, \"world\"                },\n"
17911                "    {7,  5,     \"!!\"                   }\n"
17912                "};\n",
17913                Style);
17914 
17915   verifyFormat("test demo[] = {\n"
17916                "    {56, 23,    \"hello\"                   },\n"
17917                "    {-1, 93463, \"world\" /* comment here */},\n"
17918                "    {7,  5,     \"!!\"                      }\n"
17919                "};\n",
17920                Style);
17921 
17922   verifyFormat("test demo[] = {\n"
17923                "    {56, /* a comment */ 23, \"hello\"},\n"
17924                "    {-1, 93463,              \"world\"},\n"
17925                "    {7,  5,                  \"!!\"   }\n"
17926                "};\n",
17927                Style);
17928 
17929   Style.ColumnLimit = 20;
17930   EXPECT_EQ(
17931       "demo = std::array<\n"
17932       "    struct test, 3>{\n"
17933       "    test{\n"
17934       "         56, 23,\n"
17935       "         \"hello \"\n"
17936       "         \"world i \"\n"
17937       "         \"am a very \"\n"
17938       "         \"long line \"\n"
17939       "         \"that \"\n"
17940       "         \"really, \"\n"
17941       "         \"in any \"\n"
17942       "         \"just \"\n"
17943       "         \"world, \"\n"
17944       "         \"ought to \"\n"
17945       "         \"be split \"\n"
17946       "         \"over \"\n"
17947       "         \"multiple \"\n"
17948       "         \"lines\"},\n"
17949       "    test{-1, 93463,\n"
17950       "         \"world\"},\n"
17951       "    test{7,  5,\n"
17952       "         \"!!\"   },\n"
17953       "};",
17954       format("demo = std::array<struct test, 3>{test{56, 23, \"hello world "
17955              "i am a very long line that really, in any just world, ought "
17956              "to be split over multiple lines\"},test{-1, 93463, \"world\"},"
17957              "test{7, 5, \"!!\"},};",
17958              Style));
17959 
17960   // This caused a core dump by enabling Alignment in the LLVMStyle globally
17961   Style = getLLVMStyleWithColumns(50);
17962   Style.AlignArrayOfStructures = FormatStyle::AIAS_Left;
17963   verifyFormat("static A x = {\n"
17964                "    {{init1, init2, init3, init4},\n"
17965                "     {init1, init2, init3, init4}}\n"
17966                "};",
17967                Style);
17968   Style.ColumnLimit = 100;
17969   EXPECT_EQ(
17970       "test demo[] = {\n"
17971       "    {56, 23,\n"
17972       "     \"hello world i am a very long line that really, in any just world"
17973       ", ought to be split over \"\n"
17974       "     \"multiple lines\"  },\n"
17975       "    {-1, 93463, \"world\"},\n"
17976       "    {7,  5,     \"!!\"   },\n"
17977       "};",
17978       format("test demo[] = {{56, 23, \"hello world i am a very long line "
17979              "that really, in any just world, ought to be split over multiple "
17980              "lines\"},{-1, 93463, \"world\"},{7, 5, \"!!\"},};",
17981              Style));
17982 }
17983 
TEST_F(FormatTest,UnderstandsPragmas)17984 TEST_F(FormatTest, UnderstandsPragmas) {
17985   verifyFormat("#pragma omp reduction(| : var)");
17986   verifyFormat("#pragma omp reduction(+ : var)");
17987 
17988   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
17989             "(including parentheses).",
17990             format("#pragma    mark   Any non-hyphenated or hyphenated string "
17991                    "(including parentheses)."));
17992 }
17993 
TEST_F(FormatTest,UnderstandPragmaOption)17994 TEST_F(FormatTest, UnderstandPragmaOption) {
17995   verifyFormat("#pragma option -C -A");
17996 
17997   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
17998 }
17999 
TEST_F(FormatTest,OptimizeBreakPenaltyVsExcess)18000 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
18001   FormatStyle Style = getLLVMStyle();
18002   Style.ColumnLimit = 20;
18003 
18004   // See PR41213
18005   EXPECT_EQ("/*\n"
18006             " *\t9012345\n"
18007             " * /8901\n"
18008             " */",
18009             format("/*\n"
18010                    " *\t9012345 /8901\n"
18011                    " */",
18012                    Style));
18013   EXPECT_EQ("/*\n"
18014             " *345678\n"
18015             " *\t/8901\n"
18016             " */",
18017             format("/*\n"
18018                    " *345678\t/8901\n"
18019                    " */",
18020                    Style));
18021 
18022   verifyFormat("int a; // the\n"
18023                "       // comment",
18024                Style);
18025   EXPECT_EQ("int a; /* first line\n"
18026             "        * second\n"
18027             "        * line third\n"
18028             "        * line\n"
18029             "        */",
18030             format("int a; /* first line\n"
18031                    "        * second\n"
18032                    "        * line third\n"
18033                    "        * line\n"
18034                    "        */",
18035                    Style));
18036   EXPECT_EQ("int a; // first line\n"
18037             "       // second\n"
18038             "       // line third\n"
18039             "       // line",
18040             format("int a; // first line\n"
18041                    "       // second line\n"
18042                    "       // third line",
18043                    Style));
18044 
18045   Style.PenaltyExcessCharacter = 90;
18046   verifyFormat("int a; // the comment", Style);
18047   EXPECT_EQ("int a; // the comment\n"
18048             "       // aaa",
18049             format("int a; // the comment aaa", Style));
18050   EXPECT_EQ("int a; /* first line\n"
18051             "        * second line\n"
18052             "        * third line\n"
18053             "        */",
18054             format("int a; /* first line\n"
18055                    "        * second line\n"
18056                    "        * third line\n"
18057                    "        */",
18058                    Style));
18059   EXPECT_EQ("int a; // first line\n"
18060             "       // second line\n"
18061             "       // third line",
18062             format("int a; // first line\n"
18063                    "       // second line\n"
18064                    "       // third line",
18065                    Style));
18066   // FIXME: Investigate why this is not getting the same layout as the test
18067   // above.
18068   EXPECT_EQ("int a; /* first line\n"
18069             "        * second line\n"
18070             "        * third line\n"
18071             "        */",
18072             format("int a; /* first line second line third line"
18073                    "\n*/",
18074                    Style));
18075 
18076   EXPECT_EQ("// foo bar baz bazfoo\n"
18077             "// foo bar foo bar\n",
18078             format("// foo bar baz bazfoo\n"
18079                    "// foo bar foo           bar\n",
18080                    Style));
18081   EXPECT_EQ("// foo bar baz bazfoo\n"
18082             "// foo bar foo bar\n",
18083             format("// foo bar baz      bazfoo\n"
18084                    "// foo            bar foo bar\n",
18085                    Style));
18086 
18087   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
18088   // next one.
18089   EXPECT_EQ("// foo bar baz bazfoo\n"
18090             "// bar foo bar\n",
18091             format("// foo bar baz      bazfoo bar\n"
18092                    "// foo            bar\n",
18093                    Style));
18094 
18095   EXPECT_EQ("// foo bar baz bazfoo\n"
18096             "// foo bar baz bazfoo\n"
18097             "// bar foo bar\n",
18098             format("// foo bar baz      bazfoo\n"
18099                    "// foo bar baz      bazfoo bar\n"
18100                    "// foo bar\n",
18101                    Style));
18102 
18103   EXPECT_EQ("// foo bar baz bazfoo\n"
18104             "// foo bar baz bazfoo\n"
18105             "// bar foo bar\n",
18106             format("// foo bar baz      bazfoo\n"
18107                    "// foo bar baz      bazfoo bar\n"
18108                    "// foo           bar\n",
18109                    Style));
18110 
18111   // Make sure we do not keep protruding characters if strict mode reflow is
18112   // cheaper than keeping protruding characters.
18113   Style.ColumnLimit = 21;
18114   EXPECT_EQ(
18115       "// foo foo foo foo\n"
18116       "// foo foo foo foo\n"
18117       "// foo foo foo foo\n",
18118       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
18119 
18120   EXPECT_EQ("int a = /* long block\n"
18121             "           comment */\n"
18122             "    42;",
18123             format("int a = /* long block comment */ 42;", Style));
18124 }
18125 
18126 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
18127   for (size_t i = 1; i < Styles.size(); ++i)                                   \
18128   EXPECT_EQ(Styles[0], Styles[i])                                              \
18129       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
18130 
TEST_F(FormatTest,GetsPredefinedStyleByName)18131 TEST_F(FormatTest, GetsPredefinedStyleByName) {
18132   SmallVector<FormatStyle, 3> Styles;
18133   Styles.resize(3);
18134 
18135   Styles[0] = getLLVMStyle();
18136   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
18137   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
18138   EXPECT_ALL_STYLES_EQUAL(Styles);
18139 
18140   Styles[0] = getGoogleStyle();
18141   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
18142   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
18143   EXPECT_ALL_STYLES_EQUAL(Styles);
18144 
18145   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18146   EXPECT_TRUE(
18147       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
18148   EXPECT_TRUE(
18149       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
18150   EXPECT_ALL_STYLES_EQUAL(Styles);
18151 
18152   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
18153   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
18154   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
18155   EXPECT_ALL_STYLES_EQUAL(Styles);
18156 
18157   Styles[0] = getMozillaStyle();
18158   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
18159   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
18160   EXPECT_ALL_STYLES_EQUAL(Styles);
18161 
18162   Styles[0] = getWebKitStyle();
18163   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
18164   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
18165   EXPECT_ALL_STYLES_EQUAL(Styles);
18166 
18167   Styles[0] = getGNUStyle();
18168   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
18169   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
18170   EXPECT_ALL_STYLES_EQUAL(Styles);
18171 
18172   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
18173 }
18174 
TEST_F(FormatTest,GetsCorrectBasedOnStyle)18175 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
18176   SmallVector<FormatStyle, 8> Styles;
18177   Styles.resize(2);
18178 
18179   Styles[0] = getGoogleStyle();
18180   Styles[1] = getLLVMStyle();
18181   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18182   EXPECT_ALL_STYLES_EQUAL(Styles);
18183 
18184   Styles.resize(5);
18185   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
18186   Styles[1] = getLLVMStyle();
18187   Styles[1].Language = FormatStyle::LK_JavaScript;
18188   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
18189 
18190   Styles[2] = getLLVMStyle();
18191   Styles[2].Language = FormatStyle::LK_JavaScript;
18192   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
18193                                   "BasedOnStyle: Google",
18194                                   &Styles[2])
18195                    .value());
18196 
18197   Styles[3] = getLLVMStyle();
18198   Styles[3].Language = FormatStyle::LK_JavaScript;
18199   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
18200                                   "Language: JavaScript",
18201                                   &Styles[3])
18202                    .value());
18203 
18204   Styles[4] = getLLVMStyle();
18205   Styles[4].Language = FormatStyle::LK_JavaScript;
18206   EXPECT_EQ(0, parseConfiguration("---\n"
18207                                   "BasedOnStyle: LLVM\n"
18208                                   "IndentWidth: 123\n"
18209                                   "---\n"
18210                                   "BasedOnStyle: Google\n"
18211                                   "Language: JavaScript",
18212                                   &Styles[4])
18213                    .value());
18214   EXPECT_ALL_STYLES_EQUAL(Styles);
18215 }
18216 
18217 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
18218   Style.FIELD = false;                                                         \
18219   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
18220   EXPECT_TRUE(Style.FIELD);                                                    \
18221   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
18222   EXPECT_FALSE(Style.FIELD);
18223 
18224 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
18225 
18226 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
18227   Style.STRUCT.FIELD = false;                                                  \
18228   EXPECT_EQ(0,                                                                 \
18229             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
18230                 .value());                                                     \
18231   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
18232   EXPECT_EQ(0,                                                                 \
18233             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
18234                 .value());                                                     \
18235   EXPECT_FALSE(Style.STRUCT.FIELD);
18236 
18237 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
18238   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
18239 
18240 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
18241   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
18242   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
18243   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
18244 
TEST_F(FormatTest,ParsesConfigurationBools)18245 TEST_F(FormatTest, ParsesConfigurationBools) {
18246   FormatStyle Style = {};
18247   Style.Language = FormatStyle::LK_Cpp;
18248   CHECK_PARSE_BOOL(AlignTrailingComments);
18249   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
18250   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
18251   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
18252   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
18253   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
18254   CHECK_PARSE_BOOL(BinPackArguments);
18255   CHECK_PARSE_BOOL(BinPackParameters);
18256   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
18257   CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
18258   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
18259   CHECK_PARSE_BOOL(BreakStringLiterals);
18260   CHECK_PARSE_BOOL(CompactNamespaces);
18261   CHECK_PARSE_BOOL(DeriveLineEnding);
18262   CHECK_PARSE_BOOL(DerivePointerAlignment);
18263   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
18264   CHECK_PARSE_BOOL(DisableFormat);
18265   CHECK_PARSE_BOOL(IndentAccessModifiers);
18266   CHECK_PARSE_BOOL(IndentCaseLabels);
18267   CHECK_PARSE_BOOL(IndentCaseBlocks);
18268   CHECK_PARSE_BOOL(IndentGotoLabels);
18269   CHECK_PARSE_BOOL(IndentRequires);
18270   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
18271   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
18272   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
18273   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
18274   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
18275   CHECK_PARSE_BOOL(ReflowComments);
18276   CHECK_PARSE_BOOL(SortUsingDeclarations);
18277   CHECK_PARSE_BOOL(SpacesInParentheses);
18278   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
18279   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
18280   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
18281   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
18282   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
18283   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
18284   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
18285   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
18286   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
18287   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
18288   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
18289   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
18290   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
18291   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
18292   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
18293   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
18294   CHECK_PARSE_BOOL(UseCRLF);
18295 
18296   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
18297   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
18298   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
18299   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
18300   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
18301   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
18302   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
18303   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
18304   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
18305   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
18306   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
18307   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
18308   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
18309   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
18310   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
18311   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
18312   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
18313 }
18314 
18315 #undef CHECK_PARSE_BOOL
18316 
TEST_F(FormatTest,ParsesConfiguration)18317 TEST_F(FormatTest, ParsesConfiguration) {
18318   FormatStyle Style = {};
18319   Style.Language = FormatStyle::LK_Cpp;
18320   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
18321   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
18322               ConstructorInitializerIndentWidth, 1234u);
18323   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
18324   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
18325   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
18326   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
18327   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
18328               PenaltyBreakBeforeFirstCallParameter, 1234u);
18329   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
18330               PenaltyBreakTemplateDeclaration, 1234u);
18331   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
18332   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
18333               PenaltyReturnTypeOnItsOwnLine, 1234u);
18334   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
18335               SpacesBeforeTrailingComments, 1234u);
18336   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
18337   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
18338   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
18339 
18340   Style.QualifierAlignment = FormatStyle::QAS_Right;
18341   CHECK_PARSE("QualifierAlignment: Leave", QualifierAlignment,
18342               FormatStyle::QAS_Leave);
18343   CHECK_PARSE("QualifierAlignment: Right", QualifierAlignment,
18344               FormatStyle::QAS_Right);
18345   CHECK_PARSE("QualifierAlignment: Left", QualifierAlignment,
18346               FormatStyle::QAS_Left);
18347   CHECK_PARSE("QualifierAlignment: Custom", QualifierAlignment,
18348               FormatStyle::QAS_Custom);
18349 
18350   Style.QualifierOrder.clear();
18351   CHECK_PARSE("QualifierOrder: [ const, volatile, type ]", QualifierOrder,
18352               std::vector<std::string>({"const", "volatile", "type"}));
18353   Style.QualifierOrder.clear();
18354   CHECK_PARSE("QualifierOrder: [const, type]", QualifierOrder,
18355               std::vector<std::string>({"const", "type"}));
18356   Style.QualifierOrder.clear();
18357   CHECK_PARSE("QualifierOrder: [volatile, type]", QualifierOrder,
18358               std::vector<std::string>({"volatile", "type"}));
18359 
18360   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
18361   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
18362               FormatStyle::ACS_None);
18363   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
18364               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
18365   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
18366               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
18367   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
18368               AlignConsecutiveAssignments,
18369               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18370   // For backwards compability, false / true should still parse
18371   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
18372               FormatStyle::ACS_None);
18373   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
18374               FormatStyle::ACS_Consecutive);
18375 
18376   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
18377   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
18378               FormatStyle::ACS_None);
18379   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
18380               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
18381   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
18382               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
18383   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
18384               AlignConsecutiveBitFields,
18385               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18386   // For backwards compability, false / true should still parse
18387   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
18388               FormatStyle::ACS_None);
18389   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
18390               FormatStyle::ACS_Consecutive);
18391 
18392   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
18393   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
18394               FormatStyle::ACS_None);
18395   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
18396               FormatStyle::ACS_Consecutive);
18397   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
18398               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
18399   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
18400               AlignConsecutiveMacros,
18401               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18402   // For backwards compability, false / true should still parse
18403   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
18404               FormatStyle::ACS_None);
18405   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
18406               FormatStyle::ACS_Consecutive);
18407 
18408   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
18409   CHECK_PARSE("AlignConsecutiveDeclarations: None",
18410               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
18411   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
18412               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
18413   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
18414               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
18415   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
18416               AlignConsecutiveDeclarations,
18417               FormatStyle::ACS_AcrossEmptyLinesAndComments);
18418   // For backwards compability, false / true should still parse
18419   CHECK_PARSE("AlignConsecutiveDeclarations: false",
18420               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
18421   CHECK_PARSE("AlignConsecutiveDeclarations: true",
18422               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
18423 
18424   Style.PointerAlignment = FormatStyle::PAS_Middle;
18425   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
18426               FormatStyle::PAS_Left);
18427   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
18428               FormatStyle::PAS_Right);
18429   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
18430               FormatStyle::PAS_Middle);
18431   Style.ReferenceAlignment = FormatStyle::RAS_Middle;
18432   CHECK_PARSE("ReferenceAlignment: Pointer", ReferenceAlignment,
18433               FormatStyle::RAS_Pointer);
18434   CHECK_PARSE("ReferenceAlignment: Left", ReferenceAlignment,
18435               FormatStyle::RAS_Left);
18436   CHECK_PARSE("ReferenceAlignment: Right", ReferenceAlignment,
18437               FormatStyle::RAS_Right);
18438   CHECK_PARSE("ReferenceAlignment: Middle", ReferenceAlignment,
18439               FormatStyle::RAS_Middle);
18440   // For backward compatibility:
18441   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
18442               FormatStyle::PAS_Left);
18443   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
18444               FormatStyle::PAS_Right);
18445   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
18446               FormatStyle::PAS_Middle);
18447 
18448   Style.Standard = FormatStyle::LS_Auto;
18449   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
18450   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
18451   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
18452   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
18453   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
18454   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
18455   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
18456   // Legacy aliases:
18457   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
18458   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
18459   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
18460   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
18461 
18462   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
18463   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
18464               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
18465   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
18466               FormatStyle::BOS_None);
18467   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
18468               FormatStyle::BOS_All);
18469   // For backward compatibility:
18470   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
18471               FormatStyle::BOS_None);
18472   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
18473               FormatStyle::BOS_All);
18474 
18475   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
18476   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
18477               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
18478   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
18479               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
18480   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
18481               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
18482   // For backward compatibility:
18483   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
18484               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
18485 
18486   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
18487   CHECK_PARSE("BreakInheritanceList: AfterComma", BreakInheritanceList,
18488               FormatStyle::BILS_AfterComma);
18489   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
18490               FormatStyle::BILS_BeforeComma);
18491   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
18492               FormatStyle::BILS_AfterColon);
18493   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
18494               FormatStyle::BILS_BeforeColon);
18495   // For backward compatibility:
18496   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
18497               FormatStyle::BILS_BeforeComma);
18498 
18499   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
18500   CHECK_PARSE("PackConstructorInitializers: Never", PackConstructorInitializers,
18501               FormatStyle::PCIS_Never);
18502   CHECK_PARSE("PackConstructorInitializers: BinPack",
18503               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
18504   CHECK_PARSE("PackConstructorInitializers: CurrentLine",
18505               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
18506   CHECK_PARSE("PackConstructorInitializers: NextLine",
18507               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
18508   // For backward compatibility:
18509   CHECK_PARSE("BasedOnStyle: Google\n"
18510               "ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
18511               "AllowAllConstructorInitializersOnNextLine: false",
18512               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
18513   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
18514   CHECK_PARSE("BasedOnStyle: Google\n"
18515               "ConstructorInitializerAllOnOneLineOrOnePerLine: false",
18516               PackConstructorInitializers, FormatStyle::PCIS_BinPack);
18517   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
18518               "AllowAllConstructorInitializersOnNextLine: true",
18519               PackConstructorInitializers, FormatStyle::PCIS_NextLine);
18520   Style.PackConstructorInitializers = FormatStyle::PCIS_BinPack;
18521   CHECK_PARSE("ConstructorInitializerAllOnOneLineOrOnePerLine: true\n"
18522               "AllowAllConstructorInitializersOnNextLine: false",
18523               PackConstructorInitializers, FormatStyle::PCIS_CurrentLine);
18524 
18525   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
18526   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
18527               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
18528   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
18529               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
18530   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
18531               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
18532   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
18533               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
18534 
18535   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
18536   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
18537               FormatStyle::BAS_Align);
18538   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
18539               FormatStyle::BAS_DontAlign);
18540   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
18541               FormatStyle::BAS_AlwaysBreak);
18542   // For backward compatibility:
18543   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
18544               FormatStyle::BAS_DontAlign);
18545   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
18546               FormatStyle::BAS_Align);
18547 
18548   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
18549   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
18550               FormatStyle::ENAS_DontAlign);
18551   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
18552               FormatStyle::ENAS_Left);
18553   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
18554               FormatStyle::ENAS_Right);
18555   // For backward compatibility:
18556   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
18557               FormatStyle::ENAS_Left);
18558   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
18559               FormatStyle::ENAS_Right);
18560 
18561   Style.AlignOperands = FormatStyle::OAS_Align;
18562   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
18563               FormatStyle::OAS_DontAlign);
18564   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
18565   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
18566               FormatStyle::OAS_AlignAfterOperator);
18567   // For backward compatibility:
18568   CHECK_PARSE("AlignOperands: false", AlignOperands,
18569               FormatStyle::OAS_DontAlign);
18570   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
18571 
18572   Style.UseTab = FormatStyle::UT_ForIndentation;
18573   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
18574   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
18575   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
18576   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
18577               FormatStyle::UT_ForContinuationAndIndentation);
18578   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
18579               FormatStyle::UT_AlignWithSpaces);
18580   // For backward compatibility:
18581   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
18582   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
18583 
18584   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
18585   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
18586               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
18587   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
18588               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
18589   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
18590               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
18591   // For backward compatibility:
18592   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
18593               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
18594   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
18595               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
18596 
18597   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
18598   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
18599               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
18600   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
18601               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
18602   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
18603               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
18604   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
18605               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
18606   // For backward compatibility:
18607   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
18608               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
18609   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
18610               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
18611 
18612   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
18613   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
18614               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
18615   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
18616               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
18617   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
18618               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
18619   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
18620               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
18621 
18622   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
18623   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
18624               FormatStyle::SBPO_Never);
18625   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
18626               FormatStyle::SBPO_Always);
18627   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
18628               FormatStyle::SBPO_ControlStatements);
18629   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptControlMacros",
18630               SpaceBeforeParens,
18631               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
18632   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
18633               FormatStyle::SBPO_NonEmptyParentheses);
18634   // For backward compatibility:
18635   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
18636               FormatStyle::SBPO_Never);
18637   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
18638               FormatStyle::SBPO_ControlStatements);
18639   CHECK_PARSE("SpaceBeforeParens: ControlStatementsExceptForEachMacros",
18640               SpaceBeforeParens,
18641               FormatStyle::SBPO_ControlStatementsExceptControlMacros);
18642 
18643   Style.ColumnLimit = 123;
18644   FormatStyle BaseStyle = getLLVMStyle();
18645   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
18646   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
18647 
18648   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
18649   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
18650               FormatStyle::BS_Attach);
18651   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
18652               FormatStyle::BS_Linux);
18653   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
18654               FormatStyle::BS_Mozilla);
18655   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
18656               FormatStyle::BS_Stroustrup);
18657   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
18658               FormatStyle::BS_Allman);
18659   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
18660               FormatStyle::BS_Whitesmiths);
18661   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
18662   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
18663               FormatStyle::BS_WebKit);
18664   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
18665               FormatStyle::BS_Custom);
18666 
18667   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
18668   CHECK_PARSE("BraceWrapping:\n"
18669               "  AfterControlStatement: MultiLine",
18670               BraceWrapping.AfterControlStatement,
18671               FormatStyle::BWACS_MultiLine);
18672   CHECK_PARSE("BraceWrapping:\n"
18673               "  AfterControlStatement: Always",
18674               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
18675   CHECK_PARSE("BraceWrapping:\n"
18676               "  AfterControlStatement: Never",
18677               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
18678   // For backward compatibility:
18679   CHECK_PARSE("BraceWrapping:\n"
18680               "  AfterControlStatement: true",
18681               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
18682   CHECK_PARSE("BraceWrapping:\n"
18683               "  AfterControlStatement: false",
18684               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
18685 
18686   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
18687   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
18688               FormatStyle::RTBS_None);
18689   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
18690               FormatStyle::RTBS_All);
18691   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
18692               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
18693   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
18694               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
18695   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
18696               AlwaysBreakAfterReturnType,
18697               FormatStyle::RTBS_TopLevelDefinitions);
18698 
18699   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
18700   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
18701               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
18702   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
18703               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
18704   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
18705               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
18706   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
18707               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
18708   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
18709               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
18710 
18711   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
18712   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
18713               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
18714   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
18715               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
18716   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
18717               AlwaysBreakAfterDefinitionReturnType,
18718               FormatStyle::DRTBS_TopLevel);
18719 
18720   Style.NamespaceIndentation = FormatStyle::NI_All;
18721   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
18722               FormatStyle::NI_None);
18723   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
18724               FormatStyle::NI_Inner);
18725   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
18726               FormatStyle::NI_All);
18727 
18728   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_OnlyFirstIf;
18729   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
18730               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
18731   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
18732               AllowShortIfStatementsOnASingleLine,
18733               FormatStyle::SIS_WithoutElse);
18734   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: OnlyFirstIf",
18735               AllowShortIfStatementsOnASingleLine,
18736               FormatStyle::SIS_OnlyFirstIf);
18737   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: AllIfsAndElse",
18738               AllowShortIfStatementsOnASingleLine,
18739               FormatStyle::SIS_AllIfsAndElse);
18740   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
18741               AllowShortIfStatementsOnASingleLine,
18742               FormatStyle::SIS_OnlyFirstIf);
18743   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
18744               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
18745   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
18746               AllowShortIfStatementsOnASingleLine,
18747               FormatStyle::SIS_WithoutElse);
18748 
18749   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
18750   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
18751               FormatStyle::IEBS_AfterExternBlock);
18752   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
18753               FormatStyle::IEBS_Indent);
18754   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
18755               FormatStyle::IEBS_NoIndent);
18756   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
18757               FormatStyle::IEBS_Indent);
18758   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
18759               FormatStyle::IEBS_NoIndent);
18760 
18761   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
18762   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
18763               FormatStyle::BFCS_Both);
18764   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
18765               FormatStyle::BFCS_None);
18766   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
18767               FormatStyle::BFCS_Before);
18768   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
18769               FormatStyle::BFCS_After);
18770 
18771   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
18772   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
18773               FormatStyle::SJSIO_After);
18774   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
18775               FormatStyle::SJSIO_Before);
18776 
18777   // FIXME: This is required because parsing a configuration simply overwrites
18778   // the first N elements of the list instead of resetting it.
18779   Style.ForEachMacros.clear();
18780   std::vector<std::string> BoostForeach;
18781   BoostForeach.push_back("BOOST_FOREACH");
18782   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
18783   std::vector<std::string> BoostAndQForeach;
18784   BoostAndQForeach.push_back("BOOST_FOREACH");
18785   BoostAndQForeach.push_back("Q_FOREACH");
18786   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
18787               BoostAndQForeach);
18788 
18789   Style.IfMacros.clear();
18790   std::vector<std::string> CustomIfs;
18791   CustomIfs.push_back("MYIF");
18792   CHECK_PARSE("IfMacros: [MYIF]", IfMacros, CustomIfs);
18793 
18794   Style.AttributeMacros.clear();
18795   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
18796               std::vector<std::string>{"__capability"});
18797   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
18798               std::vector<std::string>({"attr1", "attr2"}));
18799 
18800   Style.StatementAttributeLikeMacros.clear();
18801   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
18802               StatementAttributeLikeMacros,
18803               std::vector<std::string>({"emit", "Q_EMIT"}));
18804 
18805   Style.StatementMacros.clear();
18806   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
18807               std::vector<std::string>{"QUNUSED"});
18808   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
18809               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
18810 
18811   Style.NamespaceMacros.clear();
18812   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
18813               std::vector<std::string>{"TESTSUITE"});
18814   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
18815               std::vector<std::string>({"TESTSUITE", "SUITE"}));
18816 
18817   Style.WhitespaceSensitiveMacros.clear();
18818   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
18819               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
18820   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
18821               WhitespaceSensitiveMacros,
18822               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
18823   Style.WhitespaceSensitiveMacros.clear();
18824   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
18825               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
18826   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
18827               WhitespaceSensitiveMacros,
18828               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
18829 
18830   Style.IncludeStyle.IncludeCategories.clear();
18831   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
18832       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
18833   CHECK_PARSE("IncludeCategories:\n"
18834               "  - Regex: abc/.*\n"
18835               "    Priority: 2\n"
18836               "  - Regex: .*\n"
18837               "    Priority: 1\n"
18838               "    CaseSensitive: true\n",
18839               IncludeStyle.IncludeCategories, ExpectedCategories);
18840   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
18841               "abc$");
18842   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
18843               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
18844 
18845   Style.SortIncludes = FormatStyle::SI_Never;
18846   CHECK_PARSE("SortIncludes: true", SortIncludes,
18847               FormatStyle::SI_CaseSensitive);
18848   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
18849   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
18850               FormatStyle::SI_CaseInsensitive);
18851   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
18852               FormatStyle::SI_CaseSensitive);
18853   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
18854 
18855   Style.RawStringFormats.clear();
18856   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
18857       {
18858           FormatStyle::LK_TextProto,
18859           {"pb", "proto"},
18860           {"PARSE_TEXT_PROTO"},
18861           /*CanonicalDelimiter=*/"",
18862           "llvm",
18863       },
18864       {
18865           FormatStyle::LK_Cpp,
18866           {"cc", "cpp"},
18867           {"C_CODEBLOCK", "CPPEVAL"},
18868           /*CanonicalDelimiter=*/"cc",
18869           /*BasedOnStyle=*/"",
18870       },
18871   };
18872 
18873   CHECK_PARSE("RawStringFormats:\n"
18874               "  - Language: TextProto\n"
18875               "    Delimiters:\n"
18876               "      - 'pb'\n"
18877               "      - 'proto'\n"
18878               "    EnclosingFunctions:\n"
18879               "      - 'PARSE_TEXT_PROTO'\n"
18880               "    BasedOnStyle: llvm\n"
18881               "  - Language: Cpp\n"
18882               "    Delimiters:\n"
18883               "      - 'cc'\n"
18884               "      - 'cpp'\n"
18885               "    EnclosingFunctions:\n"
18886               "      - 'C_CODEBLOCK'\n"
18887               "      - 'CPPEVAL'\n"
18888               "    CanonicalDelimiter: 'cc'",
18889               RawStringFormats, ExpectedRawStringFormats);
18890 
18891   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18892               "  Minimum: 0\n"
18893               "  Maximum: 0",
18894               SpacesInLineCommentPrefix.Minimum, 0u);
18895   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
18896   Style.SpacesInLineCommentPrefix.Minimum = 1;
18897   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18898               "  Minimum: 2",
18899               SpacesInLineCommentPrefix.Minimum, 0u);
18900   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18901               "  Maximum: -1",
18902               SpacesInLineCommentPrefix.Maximum, -1u);
18903   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18904               "  Minimum: 2",
18905               SpacesInLineCommentPrefix.Minimum, 2u);
18906   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
18907               "  Maximum: 1",
18908               SpacesInLineCommentPrefix.Maximum, 1u);
18909   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
18910 
18911   Style.SpacesInAngles = FormatStyle::SIAS_Always;
18912   CHECK_PARSE("SpacesInAngles: Never", SpacesInAngles, FormatStyle::SIAS_Never);
18913   CHECK_PARSE("SpacesInAngles: Always", SpacesInAngles,
18914               FormatStyle::SIAS_Always);
18915   CHECK_PARSE("SpacesInAngles: Leave", SpacesInAngles, FormatStyle::SIAS_Leave);
18916   // For backward compatibility:
18917   CHECK_PARSE("SpacesInAngles: false", SpacesInAngles, FormatStyle::SIAS_Never);
18918   CHECK_PARSE("SpacesInAngles: true", SpacesInAngles, FormatStyle::SIAS_Always);
18919 }
18920 
TEST_F(FormatTest,ParsesConfigurationWithLanguages)18921 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
18922   FormatStyle Style = {};
18923   Style.Language = FormatStyle::LK_Cpp;
18924   CHECK_PARSE("Language: Cpp\n"
18925               "IndentWidth: 12",
18926               IndentWidth, 12u);
18927   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
18928                                "IndentWidth: 34",
18929                                &Style),
18930             ParseError::Unsuitable);
18931   FormatStyle BinPackedTCS = {};
18932   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
18933   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
18934                                "InsertTrailingCommas: Wrapped",
18935                                &BinPackedTCS),
18936             ParseError::BinPackTrailingCommaConflict);
18937   EXPECT_EQ(12u, Style.IndentWidth);
18938   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
18939   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
18940 
18941   Style.Language = FormatStyle::LK_JavaScript;
18942   CHECK_PARSE("Language: JavaScript\n"
18943               "IndentWidth: 12",
18944               IndentWidth, 12u);
18945   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
18946   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
18947                                "IndentWidth: 34",
18948                                &Style),
18949             ParseError::Unsuitable);
18950   EXPECT_EQ(23u, Style.IndentWidth);
18951   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
18952   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
18953 
18954   CHECK_PARSE("BasedOnStyle: LLVM\n"
18955               "IndentWidth: 67",
18956               IndentWidth, 67u);
18957 
18958   CHECK_PARSE("---\n"
18959               "Language: JavaScript\n"
18960               "IndentWidth: 12\n"
18961               "---\n"
18962               "Language: Cpp\n"
18963               "IndentWidth: 34\n"
18964               "...\n",
18965               IndentWidth, 12u);
18966 
18967   Style.Language = FormatStyle::LK_Cpp;
18968   CHECK_PARSE("---\n"
18969               "Language: JavaScript\n"
18970               "IndentWidth: 12\n"
18971               "---\n"
18972               "Language: Cpp\n"
18973               "IndentWidth: 34\n"
18974               "...\n",
18975               IndentWidth, 34u);
18976   CHECK_PARSE("---\n"
18977               "IndentWidth: 78\n"
18978               "---\n"
18979               "Language: JavaScript\n"
18980               "IndentWidth: 56\n"
18981               "...\n",
18982               IndentWidth, 78u);
18983 
18984   Style.ColumnLimit = 123;
18985   Style.IndentWidth = 234;
18986   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
18987   Style.TabWidth = 345;
18988   EXPECT_FALSE(parseConfiguration("---\n"
18989                                   "IndentWidth: 456\n"
18990                                   "BreakBeforeBraces: Allman\n"
18991                                   "---\n"
18992                                   "Language: JavaScript\n"
18993                                   "IndentWidth: 111\n"
18994                                   "TabWidth: 111\n"
18995                                   "---\n"
18996                                   "Language: Cpp\n"
18997                                   "BreakBeforeBraces: Stroustrup\n"
18998                                   "TabWidth: 789\n"
18999                                   "...\n",
19000                                   &Style));
19001   EXPECT_EQ(123u, Style.ColumnLimit);
19002   EXPECT_EQ(456u, Style.IndentWidth);
19003   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
19004   EXPECT_EQ(789u, Style.TabWidth);
19005 
19006   EXPECT_EQ(parseConfiguration("---\n"
19007                                "Language: JavaScript\n"
19008                                "IndentWidth: 56\n"
19009                                "---\n"
19010                                "IndentWidth: 78\n"
19011                                "...\n",
19012                                &Style),
19013             ParseError::Error);
19014   EXPECT_EQ(parseConfiguration("---\n"
19015                                "Language: JavaScript\n"
19016                                "IndentWidth: 56\n"
19017                                "---\n"
19018                                "Language: JavaScript\n"
19019                                "IndentWidth: 78\n"
19020                                "...\n",
19021                                &Style),
19022             ParseError::Error);
19023 
19024   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
19025 }
19026 
TEST_F(FormatTest,UsesLanguageForBasedOnStyle)19027 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
19028   FormatStyle Style = {};
19029   Style.Language = FormatStyle::LK_JavaScript;
19030   Style.BreakBeforeTernaryOperators = true;
19031   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
19032   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19033 
19034   Style.BreakBeforeTernaryOperators = true;
19035   EXPECT_EQ(0, parseConfiguration("---\n"
19036                                   "BasedOnStyle: Google\n"
19037                                   "---\n"
19038                                   "Language: JavaScript\n"
19039                                   "IndentWidth: 76\n"
19040                                   "...\n",
19041                                   &Style)
19042                    .value());
19043   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
19044   EXPECT_EQ(76u, Style.IndentWidth);
19045   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
19046 }
19047 
TEST_F(FormatTest,ConfigurationRoundTripTest)19048 TEST_F(FormatTest, ConfigurationRoundTripTest) {
19049   FormatStyle Style = getLLVMStyle();
19050   std::string YAML = configurationAsText(Style);
19051   FormatStyle ParsedStyle = {};
19052   ParsedStyle.Language = FormatStyle::LK_Cpp;
19053   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
19054   EXPECT_EQ(Style, ParsedStyle);
19055 }
19056 
TEST_F(FormatTest,WorksFor8bitEncodings)19057 TEST_F(FormatTest, WorksFor8bitEncodings) {
19058   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
19059             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
19060             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
19061             "\"\xef\xee\xf0\xf3...\"",
19062             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
19063                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
19064                    "\xef\xee\xf0\xf3...\"",
19065                    getLLVMStyleWithColumns(12)));
19066 }
19067 
TEST_F(FormatTest,HandlesUTF8BOM)19068 TEST_F(FormatTest, HandlesUTF8BOM) {
19069   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
19070   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
19071             format("\xef\xbb\xbf#include <iostream>"));
19072   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
19073             format("\xef\xbb\xbf\n#include <iostream>"));
19074 }
19075 
19076 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
19077 #if !defined(_MSC_VER)
19078 
TEST_F(FormatTest,CountsUTF8CharactersProperly)19079 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
19080   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
19081                getLLVMStyleWithColumns(35));
19082   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
19083                getLLVMStyleWithColumns(31));
19084   verifyFormat("// Однажды в студёную зимнюю пору...",
19085                getLLVMStyleWithColumns(36));
19086   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
19087   verifyFormat("/* Однажды в студёную зимнюю пору... */",
19088                getLLVMStyleWithColumns(39));
19089   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
19090                getLLVMStyleWithColumns(35));
19091 }
19092 
TEST_F(FormatTest,SplitsUTF8Strings)19093 TEST_F(FormatTest, SplitsUTF8Strings) {
19094   // Non-printable characters' width is currently considered to be the length in
19095   // bytes in UTF8. The characters can be displayed in very different manner
19096   // (zero-width, single width with a substitution glyph, expanded to their code
19097   // (e.g. "<8d>"), so there's no single correct way to handle them.
19098   EXPECT_EQ("\"aaaaÄ\"\n"
19099             "\"\xc2\x8d\";",
19100             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19101   EXPECT_EQ("\"aaaaaaaÄ\"\n"
19102             "\"\xc2\x8d\";",
19103             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
19104   EXPECT_EQ("\"Однажды, в \"\n"
19105             "\"студёную \"\n"
19106             "\"зимнюю \"\n"
19107             "\"пору,\"",
19108             format("\"Однажды, в студёную зимнюю пору,\"",
19109                    getLLVMStyleWithColumns(13)));
19110   EXPECT_EQ(
19111       "\"一 二 三 \"\n"
19112       "\"四 五六 \"\n"
19113       "\"七 八 九 \"\n"
19114       "\"十\"",
19115       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
19116   EXPECT_EQ("\"一\t\"\n"
19117             "\"二 \t\"\n"
19118             "\"三 四 \"\n"
19119             "\"五\t\"\n"
19120             "\"六 \t\"\n"
19121             "\"七 \"\n"
19122             "\"八九十\tqq\"",
19123             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
19124                    getLLVMStyleWithColumns(11)));
19125 
19126   // UTF8 character in an escape sequence.
19127   EXPECT_EQ("\"aaaaaa\"\n"
19128             "\"\\\xC2\x8D\"",
19129             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
19130 }
19131 
TEST_F(FormatTest,HandlesDoubleWidthCharsInMultiLineStrings)19132 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
19133   EXPECT_EQ("const char *sssss =\n"
19134             "    \"一二三四五六七八\\\n"
19135             " 九 十\";",
19136             format("const char *sssss = \"一二三四五六七八\\\n"
19137                    " 九 十\";",
19138                    getLLVMStyleWithColumns(30)));
19139 }
19140 
TEST_F(FormatTest,SplitsUTF8LineComments)19141 TEST_F(FormatTest, SplitsUTF8LineComments) {
19142   EXPECT_EQ("// aaaaÄ\xc2\x8d",
19143             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
19144   EXPECT_EQ("// Я из лесу\n"
19145             "// вышел; был\n"
19146             "// сильный\n"
19147             "// мороз.",
19148             format("// Я из лесу вышел; был сильный мороз.",
19149                    getLLVMStyleWithColumns(13)));
19150   EXPECT_EQ("// 一二三\n"
19151             "// 四五六七\n"
19152             "// 八  九\n"
19153             "// 十",
19154             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
19155 }
19156 
TEST_F(FormatTest,SplitsUTF8BlockComments)19157 TEST_F(FormatTest, SplitsUTF8BlockComments) {
19158   EXPECT_EQ("/* Гляжу,\n"
19159             " * поднимается\n"
19160             " * медленно в\n"
19161             " * гору\n"
19162             " * Лошадка,\n"
19163             " * везущая\n"
19164             " * хворосту\n"
19165             " * воз. */",
19166             format("/* Гляжу, поднимается медленно в гору\n"
19167                    " * Лошадка, везущая хворосту воз. */",
19168                    getLLVMStyleWithColumns(13)));
19169   EXPECT_EQ(
19170       "/* 一二三\n"
19171       " * 四五六七\n"
19172       " * 八  九\n"
19173       " * 十  */",
19174       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
19175   EXPECT_EQ("/* �������� ��������\n"
19176             " * ��������\n"
19177             " * ������-�� */",
19178             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
19179 }
19180 
19181 #endif // _MSC_VER
19182 
TEST_F(FormatTest,ConstructorInitializerIndentWidth)19183 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
19184   FormatStyle Style = getLLVMStyle();
19185 
19186   Style.ConstructorInitializerIndentWidth = 4;
19187   verifyFormat(
19188       "SomeClass::Constructor()\n"
19189       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19190       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19191       Style);
19192 
19193   Style.ConstructorInitializerIndentWidth = 2;
19194   verifyFormat(
19195       "SomeClass::Constructor()\n"
19196       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19197       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19198       Style);
19199 
19200   Style.ConstructorInitializerIndentWidth = 0;
19201   verifyFormat(
19202       "SomeClass::Constructor()\n"
19203       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
19204       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
19205       Style);
19206   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
19207   verifyFormat(
19208       "SomeLongTemplateVariableName<\n"
19209       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
19210       Style);
19211   verifyFormat("bool smaller = 1 < "
19212                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
19213                "                       "
19214                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
19215                Style);
19216 
19217   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
19218   verifyFormat("SomeClass::Constructor() :\n"
19219                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
19220                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
19221                Style);
19222 }
19223 
TEST_F(FormatTest,BreakConstructorInitializersBeforeComma)19224 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
19225   FormatStyle Style = getLLVMStyle();
19226   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
19227   Style.ConstructorInitializerIndentWidth = 4;
19228   verifyFormat("SomeClass::Constructor()\n"
19229                "    : a(a)\n"
19230                "    , b(b)\n"
19231                "    , c(c) {}",
19232                Style);
19233   verifyFormat("SomeClass::Constructor()\n"
19234                "    : a(a) {}",
19235                Style);
19236 
19237   Style.ColumnLimit = 0;
19238   verifyFormat("SomeClass::Constructor()\n"
19239                "    : a(a) {}",
19240                Style);
19241   verifyFormat("SomeClass::Constructor() noexcept\n"
19242                "    : a(a) {}",
19243                Style);
19244   verifyFormat("SomeClass::Constructor()\n"
19245                "    : a(a)\n"
19246                "    , b(b)\n"
19247                "    , c(c) {}",
19248                Style);
19249   verifyFormat("SomeClass::Constructor()\n"
19250                "    : a(a) {\n"
19251                "  foo();\n"
19252                "  bar();\n"
19253                "}",
19254                Style);
19255 
19256   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
19257   verifyFormat("SomeClass::Constructor()\n"
19258                "    : a(a)\n"
19259                "    , b(b)\n"
19260                "    , c(c) {\n}",
19261                Style);
19262   verifyFormat("SomeClass::Constructor()\n"
19263                "    : a(a) {\n}",
19264                Style);
19265 
19266   Style.ColumnLimit = 80;
19267   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
19268   Style.ConstructorInitializerIndentWidth = 2;
19269   verifyFormat("SomeClass::Constructor()\n"
19270                "  : a(a)\n"
19271                "  , b(b)\n"
19272                "  , c(c) {}",
19273                Style);
19274 
19275   Style.ConstructorInitializerIndentWidth = 0;
19276   verifyFormat("SomeClass::Constructor()\n"
19277                ": a(a)\n"
19278                ", b(b)\n"
19279                ", c(c) {}",
19280                Style);
19281 
19282   Style.PackConstructorInitializers = FormatStyle::PCIS_NextLine;
19283   Style.ConstructorInitializerIndentWidth = 4;
19284   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
19285   verifyFormat(
19286       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
19287       Style);
19288   verifyFormat(
19289       "SomeClass::Constructor()\n"
19290       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
19291       Style);
19292   Style.ConstructorInitializerIndentWidth = 4;
19293   Style.ColumnLimit = 60;
19294   verifyFormat("SomeClass::Constructor()\n"
19295                "    : aaaaaaaa(aaaaaaaa)\n"
19296                "    , aaaaaaaa(aaaaaaaa)\n"
19297                "    , aaaaaaaa(aaaaaaaa) {}",
19298                Style);
19299 }
19300 
TEST_F(FormatTest,ConstructorInitializersWithPreprocessorDirective)19301 TEST_F(FormatTest, ConstructorInitializersWithPreprocessorDirective) {
19302   FormatStyle Style = getLLVMStyle();
19303   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
19304   Style.ConstructorInitializerIndentWidth = 4;
19305   verifyFormat("SomeClass::Constructor()\n"
19306                "    : a{a}\n"
19307                "    , b{b} {}",
19308                Style);
19309   verifyFormat("SomeClass::Constructor()\n"
19310                "    : a{a}\n"
19311                "#if CONDITION\n"
19312                "    , b{b}\n"
19313                "#endif\n"
19314                "{\n}",
19315                Style);
19316   Style.ConstructorInitializerIndentWidth = 2;
19317   verifyFormat("SomeClass::Constructor()\n"
19318                "#if CONDITION\n"
19319                "  : a{a}\n"
19320                "#endif\n"
19321                "  , b{b}\n"
19322                "  , c{c} {\n}",
19323                Style);
19324   Style.ConstructorInitializerIndentWidth = 0;
19325   verifyFormat("SomeClass::Constructor()\n"
19326                ": a{a}\n"
19327                "#ifdef CONDITION\n"
19328                ", b{b}\n"
19329                "#else\n"
19330                ", c{c}\n"
19331                "#endif\n"
19332                ", d{d} {\n}",
19333                Style);
19334   Style.ConstructorInitializerIndentWidth = 4;
19335   verifyFormat("SomeClass::Constructor()\n"
19336                "    : a{a}\n"
19337                "#if WINDOWS\n"
19338                "#if DEBUG\n"
19339                "    , b{0}\n"
19340                "#else\n"
19341                "    , b{1}\n"
19342                "#endif\n"
19343                "#else\n"
19344                "#if DEBUG\n"
19345                "    , b{2}\n"
19346                "#else\n"
19347                "    , b{3}\n"
19348                "#endif\n"
19349                "#endif\n"
19350                "{\n}",
19351                Style);
19352   verifyFormat("SomeClass::Constructor()\n"
19353                "    : a{a}\n"
19354                "#if WINDOWS\n"
19355                "    , b{0}\n"
19356                "#if DEBUG\n"
19357                "    , c{0}\n"
19358                "#else\n"
19359                "    , c{1}\n"
19360                "#endif\n"
19361                "#else\n"
19362                "#if DEBUG\n"
19363                "    , c{2}\n"
19364                "#else\n"
19365                "    , c{3}\n"
19366                "#endif\n"
19367                "    , b{1}\n"
19368                "#endif\n"
19369                "{\n}",
19370                Style);
19371 }
19372 
TEST_F(FormatTest,Destructors)19373 TEST_F(FormatTest, Destructors) {
19374   verifyFormat("void F(int &i) { i.~int(); }");
19375   verifyFormat("void F(int &i) { i->~int(); }");
19376 }
19377 
TEST_F(FormatTest,FormatsWithWebKitStyle)19378 TEST_F(FormatTest, FormatsWithWebKitStyle) {
19379   FormatStyle Style = getWebKitStyle();
19380 
19381   // Don't indent in outer namespaces.
19382   verifyFormat("namespace outer {\n"
19383                "int i;\n"
19384                "namespace inner {\n"
19385                "    int i;\n"
19386                "} // namespace inner\n"
19387                "} // namespace outer\n"
19388                "namespace other_outer {\n"
19389                "int i;\n"
19390                "}",
19391                Style);
19392 
19393   // Don't indent case labels.
19394   verifyFormat("switch (variable) {\n"
19395                "case 1:\n"
19396                "case 2:\n"
19397                "    doSomething();\n"
19398                "    break;\n"
19399                "default:\n"
19400                "    ++variable;\n"
19401                "}",
19402                Style);
19403 
19404   // Wrap before binary operators.
19405   EXPECT_EQ("void f()\n"
19406             "{\n"
19407             "    if (aaaaaaaaaaaaaaaa\n"
19408             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
19409             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
19410             "        return;\n"
19411             "}",
19412             format("void f() {\n"
19413                    "if (aaaaaaaaaaaaaaaa\n"
19414                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
19415                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
19416                    "return;\n"
19417                    "}",
19418                    Style));
19419 
19420   // Allow functions on a single line.
19421   verifyFormat("void f() { return; }", Style);
19422 
19423   // Allow empty blocks on a single line and insert a space in empty blocks.
19424   EXPECT_EQ("void f() { }", format("void f() {}", Style));
19425   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
19426   // However, don't merge non-empty short loops.
19427   EXPECT_EQ("while (true) {\n"
19428             "    continue;\n"
19429             "}",
19430             format("while (true) { continue; }", Style));
19431 
19432   // Constructor initializers are formatted one per line with the "," on the
19433   // new line.
19434   verifyFormat("Constructor()\n"
19435                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
19436                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
19437                "          aaaaaaaaaaaaaa)\n"
19438                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
19439                "{\n"
19440                "}",
19441                Style);
19442   verifyFormat("SomeClass::Constructor()\n"
19443                "    : a(a)\n"
19444                "{\n"
19445                "}",
19446                Style);
19447   EXPECT_EQ("SomeClass::Constructor()\n"
19448             "    : a(a)\n"
19449             "{\n"
19450             "}",
19451             format("SomeClass::Constructor():a(a){}", Style));
19452   verifyFormat("SomeClass::Constructor()\n"
19453                "    : a(a)\n"
19454                "    , b(b)\n"
19455                "    , c(c)\n"
19456                "{\n"
19457                "}",
19458                Style);
19459   verifyFormat("SomeClass::Constructor()\n"
19460                "    : a(a)\n"
19461                "{\n"
19462                "    foo();\n"
19463                "    bar();\n"
19464                "}",
19465                Style);
19466 
19467   // Access specifiers should be aligned left.
19468   verifyFormat("class C {\n"
19469                "public:\n"
19470                "    int i;\n"
19471                "};",
19472                Style);
19473 
19474   // Do not align comments.
19475   verifyFormat("int a; // Do not\n"
19476                "double b; // align comments.",
19477                Style);
19478 
19479   // Do not align operands.
19480   EXPECT_EQ("ASSERT(aaaa\n"
19481             "    || bbbb);",
19482             format("ASSERT ( aaaa\n||bbbb);", Style));
19483 
19484   // Accept input's line breaks.
19485   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
19486             "    || bbbbbbbbbbbbbbb) {\n"
19487             "    i++;\n"
19488             "}",
19489             format("if (aaaaaaaaaaaaaaa\n"
19490                    "|| bbbbbbbbbbbbbbb) { i++; }",
19491                    Style));
19492   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
19493             "    i++;\n"
19494             "}",
19495             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
19496 
19497   // Don't automatically break all macro definitions (llvm.org/PR17842).
19498   verifyFormat("#define aNumber 10", Style);
19499   // However, generally keep the line breaks that the user authored.
19500   EXPECT_EQ("#define aNumber \\\n"
19501             "    10",
19502             format("#define aNumber \\\n"
19503                    " 10",
19504                    Style));
19505 
19506   // Keep empty and one-element array literals on a single line.
19507   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
19508             "                                  copyItems:YES];",
19509             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
19510                    "copyItems:YES];",
19511                    Style));
19512   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
19513             "                                  copyItems:YES];",
19514             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
19515                    "             copyItems:YES];",
19516                    Style));
19517   // FIXME: This does not seem right, there should be more indentation before
19518   // the array literal's entries. Nested blocks have the same problem.
19519   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
19520             "    @\"a\",\n"
19521             "    @\"a\"\n"
19522             "]\n"
19523             "                                  copyItems:YES];",
19524             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
19525                    "     @\"a\",\n"
19526                    "     @\"a\"\n"
19527                    "     ]\n"
19528                    "       copyItems:YES];",
19529                    Style));
19530   EXPECT_EQ(
19531       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
19532       "                                  copyItems:YES];",
19533       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
19534              "   copyItems:YES];",
19535              Style));
19536 
19537   verifyFormat("[self.a b:c c:d];", Style);
19538   EXPECT_EQ("[self.a b:c\n"
19539             "        c:d];",
19540             format("[self.a b:c\n"
19541                    "c:d];",
19542                    Style));
19543 }
19544 
TEST_F(FormatTest,FormatsLambdas)19545 TEST_F(FormatTest, FormatsLambdas) {
19546   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
19547   verifyFormat(
19548       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
19549   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
19550   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
19551   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
19552   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
19553   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
19554   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
19555   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
19556   verifyFormat("int x = f(*+[] {});");
19557   verifyFormat("void f() {\n"
19558                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
19559                "}\n");
19560   verifyFormat("void f() {\n"
19561                "  other(x.begin(), //\n"
19562                "        x.end(),   //\n"
19563                "        [&](int, int) { return 1; });\n"
19564                "}\n");
19565   verifyFormat("void f() {\n"
19566                "  other.other.other.other.other(\n"
19567                "      x.begin(), x.end(),\n"
19568                "      [something, rather](int, int, int, int, int, int, int) { "
19569                "return 1; });\n"
19570                "}\n");
19571   verifyFormat(
19572       "void f() {\n"
19573       "  other.other.other.other.other(\n"
19574       "      x.begin(), x.end(),\n"
19575       "      [something, rather](int, int, int, int, int, int, int) {\n"
19576       "        //\n"
19577       "      });\n"
19578       "}\n");
19579   verifyFormat("SomeFunction([]() { // A cool function...\n"
19580                "  return 43;\n"
19581                "});");
19582   EXPECT_EQ("SomeFunction([]() {\n"
19583             "#define A a\n"
19584             "  return 43;\n"
19585             "});",
19586             format("SomeFunction([](){\n"
19587                    "#define A a\n"
19588                    "return 43;\n"
19589                    "});"));
19590   verifyFormat("void f() {\n"
19591                "  SomeFunction([](decltype(x), A *a) {});\n"
19592                "  SomeFunction([](typeof(x), A *a) {});\n"
19593                "  SomeFunction([](_Atomic(x), A *a) {});\n"
19594                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
19595                "}");
19596   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19597                "    [](const aaaaaaaaaa &a) { return a; });");
19598   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
19599                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
19600                "});");
19601   verifyFormat("Constructor()\n"
19602                "    : Field([] { // comment\n"
19603                "        int i;\n"
19604                "      }) {}");
19605   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
19606                "  return some_parameter.size();\n"
19607                "};");
19608   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
19609                "    [](const string &s) { return s; };");
19610   verifyFormat("int i = aaaaaa ? 1 //\n"
19611                "               : [] {\n"
19612                "                   return 2; //\n"
19613                "                 }();");
19614   verifyFormat("llvm::errs() << \"number of twos is \"\n"
19615                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
19616                "                  return x == 2; // force break\n"
19617                "                });");
19618   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19619                "    [=](int iiiiiiiiiiii) {\n"
19620                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
19621                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
19622                "    });",
19623                getLLVMStyleWithColumns(60));
19624 
19625   verifyFormat("SomeFunction({[&] {\n"
19626                "                // comment\n"
19627                "              },\n"
19628                "              [&] {\n"
19629                "                // comment\n"
19630                "              }});");
19631   verifyFormat("SomeFunction({[&] {\n"
19632                "  // comment\n"
19633                "}});");
19634   verifyFormat(
19635       "virtual aaaaaaaaaaaaaaaa(\n"
19636       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
19637       "    aaaaa aaaaaaaaa);");
19638 
19639   // Lambdas with return types.
19640   verifyFormat("int c = []() -> int { return 2; }();\n");
19641   verifyFormat("int c = []() -> int * { return 2; }();\n");
19642   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
19643   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
19644   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
19645   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
19646   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
19647   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
19648   verifyFormat("[a, a]() -> a<1> {};");
19649   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
19650   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
19651   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
19652   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
19653   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
19654   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
19655   verifyFormat("[]() -> foo<!5> { return {}; };");
19656   verifyFormat("[]() -> foo<~5> { return {}; };");
19657   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
19658   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
19659   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
19660   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
19661   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
19662   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
19663   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
19664   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
19665   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
19666   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
19667   verifyFormat("namespace bar {\n"
19668                "// broken:\n"
19669                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
19670                "} // namespace bar");
19671   verifyFormat("namespace bar {\n"
19672                "// broken:\n"
19673                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
19674                "} // namespace bar");
19675   verifyFormat("namespace bar {\n"
19676                "// broken:\n"
19677                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
19678                "} // namespace bar");
19679   verifyFormat("namespace bar {\n"
19680                "// broken:\n"
19681                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
19682                "} // namespace bar");
19683   verifyFormat("namespace bar {\n"
19684                "// broken:\n"
19685                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
19686                "} // namespace bar");
19687   verifyFormat("namespace bar {\n"
19688                "// broken:\n"
19689                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
19690                "} // namespace bar");
19691   verifyFormat("namespace bar {\n"
19692                "// broken:\n"
19693                "auto foo{[]() -> foo<!5> { return {}; }};\n"
19694                "} // namespace bar");
19695   verifyFormat("namespace bar {\n"
19696                "// broken:\n"
19697                "auto foo{[]() -> foo<~5> { return {}; }};\n"
19698                "} // namespace bar");
19699   verifyFormat("namespace bar {\n"
19700                "// broken:\n"
19701                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
19702                "} // namespace bar");
19703   verifyFormat("namespace bar {\n"
19704                "// broken:\n"
19705                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
19706                "} // namespace bar");
19707   verifyFormat("namespace bar {\n"
19708                "// broken:\n"
19709                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
19710                "} // namespace bar");
19711   verifyFormat("namespace bar {\n"
19712                "// broken:\n"
19713                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
19714                "} // namespace bar");
19715   verifyFormat("namespace bar {\n"
19716                "// broken:\n"
19717                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
19718                "} // namespace bar");
19719   verifyFormat("namespace bar {\n"
19720                "// broken:\n"
19721                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
19722                "} // namespace bar");
19723   verifyFormat("namespace bar {\n"
19724                "// broken:\n"
19725                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
19726                "} // namespace bar");
19727   verifyFormat("namespace bar {\n"
19728                "// broken:\n"
19729                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
19730                "} // namespace bar");
19731   verifyFormat("namespace bar {\n"
19732                "// broken:\n"
19733                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
19734                "} // namespace bar");
19735   verifyFormat("namespace bar {\n"
19736                "// broken:\n"
19737                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
19738                "} // namespace bar");
19739   verifyFormat("[]() -> a<1> {};");
19740   verifyFormat("[]() -> a<1> { ; };");
19741   verifyFormat("[]() -> a<1> { ; }();");
19742   verifyFormat("[a, a]() -> a<true> {};");
19743   verifyFormat("[]() -> a<true> {};");
19744   verifyFormat("[]() -> a<true> { ; };");
19745   verifyFormat("[]() -> a<true> { ; }();");
19746   verifyFormat("[a, a]() -> a<false> {};");
19747   verifyFormat("[]() -> a<false> {};");
19748   verifyFormat("[]() -> a<false> { ; };");
19749   verifyFormat("[]() -> a<false> { ; }();");
19750   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
19751   verifyFormat("namespace bar {\n"
19752                "auto foo{[]() -> foo<false> { ; }};\n"
19753                "} // namespace bar");
19754   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
19755                "                   int j) -> int {\n"
19756                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
19757                "};");
19758   verifyFormat(
19759       "aaaaaaaaaaaaaaaaaaaaaa(\n"
19760       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
19761       "      return aaaaaaaaaaaaaaaaa;\n"
19762       "    });",
19763       getLLVMStyleWithColumns(70));
19764   verifyFormat("[]() //\n"
19765                "    -> int {\n"
19766                "  return 1; //\n"
19767                "};");
19768   verifyFormat("[]() -> Void<T...> {};");
19769   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
19770 
19771   // Lambdas with explicit template argument lists.
19772   verifyFormat(
19773       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
19774 
19775   // Multiple lambdas in the same parentheses change indentation rules. These
19776   // lambdas are forced to start on new lines.
19777   verifyFormat("SomeFunction(\n"
19778                "    []() {\n"
19779                "      //\n"
19780                "    },\n"
19781                "    []() {\n"
19782                "      //\n"
19783                "    });");
19784 
19785   // A lambda passed as arg0 is always pushed to the next line.
19786   verifyFormat("SomeFunction(\n"
19787                "    [this] {\n"
19788                "      //\n"
19789                "    },\n"
19790                "    1);\n");
19791 
19792   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
19793   // the arg0 case above.
19794   auto Style = getGoogleStyle();
19795   Style.BinPackArguments = false;
19796   verifyFormat("SomeFunction(\n"
19797                "    a,\n"
19798                "    [this] {\n"
19799                "      //\n"
19800                "    },\n"
19801                "    b);\n",
19802                Style);
19803   verifyFormat("SomeFunction(\n"
19804                "    a,\n"
19805                "    [this] {\n"
19806                "      //\n"
19807                "    },\n"
19808                "    b);\n");
19809 
19810   // A lambda with a very long line forces arg0 to be pushed out irrespective of
19811   // the BinPackArguments value (as long as the code is wide enough).
19812   verifyFormat(
19813       "something->SomeFunction(\n"
19814       "    a,\n"
19815       "    [this] {\n"
19816       "      "
19817       "D0000000000000000000000000000000000000000000000000000000000001();\n"
19818       "    },\n"
19819       "    b);\n");
19820 
19821   // A multi-line lambda is pulled up as long as the introducer fits on the
19822   // previous line and there are no further args.
19823   verifyFormat("function(1, [this, that] {\n"
19824                "  //\n"
19825                "});\n");
19826   verifyFormat("function([this, that] {\n"
19827                "  //\n"
19828                "});\n");
19829   // FIXME: this format is not ideal and we should consider forcing the first
19830   // arg onto its own line.
19831   verifyFormat("function(a, b, c, //\n"
19832                "         d, [this, that] {\n"
19833                "           //\n"
19834                "         });\n");
19835 
19836   // Multiple lambdas are treated correctly even when there is a short arg0.
19837   verifyFormat("SomeFunction(\n"
19838                "    1,\n"
19839                "    [this] {\n"
19840                "      //\n"
19841                "    },\n"
19842                "    [this] {\n"
19843                "      //\n"
19844                "    },\n"
19845                "    1);\n");
19846 
19847   // More complex introducers.
19848   verifyFormat("return [i, args...] {};");
19849 
19850   // Not lambdas.
19851   verifyFormat("constexpr char hello[]{\"hello\"};");
19852   verifyFormat("double &operator[](int i) { return 0; }\n"
19853                "int i;");
19854   verifyFormat("std::unique_ptr<int[]> foo() {}");
19855   verifyFormat("int i = a[a][a]->f();");
19856   verifyFormat("int i = (*b)[a]->f();");
19857 
19858   // Other corner cases.
19859   verifyFormat("void f() {\n"
19860                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
19861                "  );\n"
19862                "}");
19863 
19864   // Lambdas created through weird macros.
19865   verifyFormat("void f() {\n"
19866                "  MACRO((const AA &a) { return 1; });\n"
19867                "  MACRO((AA &a) { return 1; });\n"
19868                "}");
19869 
19870   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
19871                "      doo_dah();\n"
19872                "      doo_dah();\n"
19873                "    })) {\n"
19874                "}");
19875   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
19876                "                doo_dah();\n"
19877                "                doo_dah();\n"
19878                "              })) {\n"
19879                "}");
19880   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
19881                "                doo_dah();\n"
19882                "                doo_dah();\n"
19883                "              })) {\n"
19884                "}");
19885   verifyFormat("auto lambda = []() {\n"
19886                "  int a = 2\n"
19887                "#if A\n"
19888                "          + 2\n"
19889                "#endif\n"
19890                "      ;\n"
19891                "};");
19892 
19893   // Lambdas with complex multiline introducers.
19894   verifyFormat(
19895       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19896       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
19897       "        -> ::std::unordered_set<\n"
19898       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
19899       "      //\n"
19900       "    });");
19901 
19902   FormatStyle DoNotMerge = getLLVMStyle();
19903   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
19904   verifyFormat("auto c = []() {\n"
19905                "  return b;\n"
19906                "};",
19907                "auto c = []() { return b; };", DoNotMerge);
19908   verifyFormat("auto c = []() {\n"
19909                "};",
19910                " auto c = []() {};", DoNotMerge);
19911 
19912   FormatStyle MergeEmptyOnly = getLLVMStyle();
19913   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
19914   verifyFormat("auto c = []() {\n"
19915                "  return b;\n"
19916                "};",
19917                "auto c = []() {\n"
19918                "  return b;\n"
19919                " };",
19920                MergeEmptyOnly);
19921   verifyFormat("auto c = []() {};",
19922                "auto c = []() {\n"
19923                "};",
19924                MergeEmptyOnly);
19925 
19926   FormatStyle MergeInline = getLLVMStyle();
19927   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
19928   verifyFormat("auto c = []() {\n"
19929                "  return b;\n"
19930                "};",
19931                "auto c = []() { return b; };", MergeInline);
19932   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
19933                MergeInline);
19934   verifyFormat("function([]() { return b; }, a)",
19935                "function([]() { return b; }, a)", MergeInline);
19936   verifyFormat("function(a, []() { return b; })",
19937                "function(a, []() { return b; })", MergeInline);
19938 
19939   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
19940   // AllowShortLambdasOnASingleLine
19941   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
19942   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
19943   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
19944   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
19945       FormatStyle::ShortLambdaStyle::SLS_None;
19946   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
19947                "    []()\n"
19948                "    {\n"
19949                "      return 17;\n"
19950                "    });",
19951                LLVMWithBeforeLambdaBody);
19952   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
19953                "    []()\n"
19954                "    {\n"
19955                "    });",
19956                LLVMWithBeforeLambdaBody);
19957   verifyFormat("auto fct_SLS_None = []()\n"
19958                "{\n"
19959                "  return 17;\n"
19960                "};",
19961                LLVMWithBeforeLambdaBody);
19962   verifyFormat("TwoNestedLambdas_SLS_None(\n"
19963                "    []()\n"
19964                "    {\n"
19965                "      return Call(\n"
19966                "          []()\n"
19967                "          {\n"
19968                "            return 17;\n"
19969                "          });\n"
19970                "    });",
19971                LLVMWithBeforeLambdaBody);
19972   verifyFormat("void Fct() {\n"
19973                "  return {[]()\n"
19974                "          {\n"
19975                "            return 17;\n"
19976                "          }};\n"
19977                "}",
19978                LLVMWithBeforeLambdaBody);
19979 
19980   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
19981       FormatStyle::ShortLambdaStyle::SLS_Empty;
19982   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
19983                "    []()\n"
19984                "    {\n"
19985                "      return 17;\n"
19986                "    });",
19987                LLVMWithBeforeLambdaBody);
19988   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
19989                LLVMWithBeforeLambdaBody);
19990   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
19991                "ongFunctionName_SLS_Empty(\n"
19992                "    []() {});",
19993                LLVMWithBeforeLambdaBody);
19994   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
19995                "                                []()\n"
19996                "                                {\n"
19997                "                                  return 17;\n"
19998                "                                });",
19999                LLVMWithBeforeLambdaBody);
20000   verifyFormat("auto fct_SLS_Empty = []()\n"
20001                "{\n"
20002                "  return 17;\n"
20003                "};",
20004                LLVMWithBeforeLambdaBody);
20005   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
20006                "    []()\n"
20007                "    {\n"
20008                "      return Call([]() {});\n"
20009                "    });",
20010                LLVMWithBeforeLambdaBody);
20011   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
20012                "                           []()\n"
20013                "                           {\n"
20014                "                             return Call([]() {});\n"
20015                "                           });",
20016                LLVMWithBeforeLambdaBody);
20017   verifyFormat(
20018       "FctWithLongLineInLambda_SLS_Empty(\n"
20019       "    []()\n"
20020       "    {\n"
20021       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20022       "                               AndShouldNotBeConsiderAsInline,\n"
20023       "                               LambdaBodyMustBeBreak);\n"
20024       "    });",
20025       LLVMWithBeforeLambdaBody);
20026 
20027   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20028       FormatStyle::ShortLambdaStyle::SLS_Inline;
20029   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
20030                LLVMWithBeforeLambdaBody);
20031   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
20032                LLVMWithBeforeLambdaBody);
20033   verifyFormat("auto fct_SLS_Inline = []()\n"
20034                "{\n"
20035                "  return 17;\n"
20036                "};",
20037                LLVMWithBeforeLambdaBody);
20038   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
20039                "17; }); });",
20040                LLVMWithBeforeLambdaBody);
20041   verifyFormat(
20042       "FctWithLongLineInLambda_SLS_Inline(\n"
20043       "    []()\n"
20044       "    {\n"
20045       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20046       "                               AndShouldNotBeConsiderAsInline,\n"
20047       "                               LambdaBodyMustBeBreak);\n"
20048       "    });",
20049       LLVMWithBeforeLambdaBody);
20050   verifyFormat("FctWithMultipleParams_SLS_Inline("
20051                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
20052                "                                 []() { return 17; });",
20053                LLVMWithBeforeLambdaBody);
20054   verifyFormat(
20055       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
20056       LLVMWithBeforeLambdaBody);
20057 
20058   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20059       FormatStyle::ShortLambdaStyle::SLS_All;
20060   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
20061                LLVMWithBeforeLambdaBody);
20062   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
20063                LLVMWithBeforeLambdaBody);
20064   verifyFormat("auto fct_SLS_All = []() { return 17; };",
20065                LLVMWithBeforeLambdaBody);
20066   verifyFormat("FctWithOneParam_SLS_All(\n"
20067                "    []()\n"
20068                "    {\n"
20069                "      // A cool function...\n"
20070                "      return 43;\n"
20071                "    });",
20072                LLVMWithBeforeLambdaBody);
20073   verifyFormat("FctWithMultipleParams_SLS_All("
20074                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
20075                "                              []() { return 17; });",
20076                LLVMWithBeforeLambdaBody);
20077   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
20078                LLVMWithBeforeLambdaBody);
20079   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
20080                LLVMWithBeforeLambdaBody);
20081   verifyFormat(
20082       "FctWithLongLineInLambda_SLS_All(\n"
20083       "    []()\n"
20084       "    {\n"
20085       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20086       "                               AndShouldNotBeConsiderAsInline,\n"
20087       "                               LambdaBodyMustBeBreak);\n"
20088       "    });",
20089       LLVMWithBeforeLambdaBody);
20090   verifyFormat(
20091       "auto fct_SLS_All = []()\n"
20092       "{\n"
20093       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20094       "                           AndShouldNotBeConsiderAsInline,\n"
20095       "                           LambdaBodyMustBeBreak);\n"
20096       "};",
20097       LLVMWithBeforeLambdaBody);
20098   LLVMWithBeforeLambdaBody.BinPackParameters = false;
20099   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
20100                LLVMWithBeforeLambdaBody);
20101   verifyFormat(
20102       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
20103       "                                FirstParam,\n"
20104       "                                SecondParam,\n"
20105       "                                ThirdParam,\n"
20106       "                                FourthParam);",
20107       LLVMWithBeforeLambdaBody);
20108   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20109                "    []() { return "
20110                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
20111                "    FirstParam,\n"
20112                "    SecondParam,\n"
20113                "    ThirdParam,\n"
20114                "    FourthParam);",
20115                LLVMWithBeforeLambdaBody);
20116   verifyFormat(
20117       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
20118       "                                SecondParam,\n"
20119       "                                ThirdParam,\n"
20120       "                                FourthParam,\n"
20121       "                                []() { return SomeValueNotSoLong; });",
20122       LLVMWithBeforeLambdaBody);
20123   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
20124                "    []()\n"
20125                "    {\n"
20126                "      return "
20127                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
20128                "eConsiderAsInline;\n"
20129                "    });",
20130                LLVMWithBeforeLambdaBody);
20131   verifyFormat(
20132       "FctWithLongLineInLambda_SLS_All(\n"
20133       "    []()\n"
20134       "    {\n"
20135       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
20136       "                               AndShouldNotBeConsiderAsInline,\n"
20137       "                               LambdaBodyMustBeBreak);\n"
20138       "    });",
20139       LLVMWithBeforeLambdaBody);
20140   verifyFormat("FctWithTwoParams_SLS_All(\n"
20141                "    []()\n"
20142                "    {\n"
20143                "      // A cool function...\n"
20144                "      return 43;\n"
20145                "    },\n"
20146                "    87);",
20147                LLVMWithBeforeLambdaBody);
20148   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
20149                LLVMWithBeforeLambdaBody);
20150   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
20151                LLVMWithBeforeLambdaBody);
20152   verifyFormat(
20153       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
20154       LLVMWithBeforeLambdaBody);
20155   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
20156                "}); }, x);",
20157                LLVMWithBeforeLambdaBody);
20158   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20159                "    []()\n"
20160                "    {\n"
20161                "      // A cool function...\n"
20162                "      return Call([]() { return 17; });\n"
20163                "    });",
20164                LLVMWithBeforeLambdaBody);
20165   verifyFormat("TwoNestedLambdas_SLS_All(\n"
20166                "    []()\n"
20167                "    {\n"
20168                "      return Call(\n"
20169                "          []()\n"
20170                "          {\n"
20171                "            // A cool function...\n"
20172                "            return 17;\n"
20173                "          });\n"
20174                "    });",
20175                LLVMWithBeforeLambdaBody);
20176 
20177   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20178       FormatStyle::ShortLambdaStyle::SLS_None;
20179 
20180   verifyFormat("auto select = [this]() -> const Library::Object *\n"
20181                "{\n"
20182                "  return MyAssignment::SelectFromList(this);\n"
20183                "};\n",
20184                LLVMWithBeforeLambdaBody);
20185 
20186   verifyFormat("auto select = [this]() -> const Library::Object &\n"
20187                "{\n"
20188                "  return MyAssignment::SelectFromList(this);\n"
20189                "};\n",
20190                LLVMWithBeforeLambdaBody);
20191 
20192   verifyFormat("auto select = [this]() -> std::unique_ptr<Object>\n"
20193                "{\n"
20194                "  return MyAssignment::SelectFromList(this);\n"
20195                "};\n",
20196                LLVMWithBeforeLambdaBody);
20197 
20198   verifyFormat("namespace test {\n"
20199                "class Test {\n"
20200                "public:\n"
20201                "  Test() = default;\n"
20202                "};\n"
20203                "} // namespace test",
20204                LLVMWithBeforeLambdaBody);
20205 
20206   // Lambdas with different indentation styles.
20207   Style = getLLVMStyleWithColumns(100);
20208   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20209             "  return promise.then(\n"
20210             "      [this, &someVariable, someObject = "
20211             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20212             "        return someObject.startAsyncAction().then(\n"
20213             "            [this, &someVariable](AsyncActionResult result) "
20214             "mutable { result.processMore(); });\n"
20215             "      });\n"
20216             "}\n",
20217             format("SomeResult doSomething(SomeObject promise) {\n"
20218                    "  return promise.then([this, &someVariable, someObject = "
20219                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20220                    "    return someObject.startAsyncAction().then([this, "
20221                    "&someVariable](AsyncActionResult result) mutable {\n"
20222                    "      result.processMore();\n"
20223                    "    });\n"
20224                    "  });\n"
20225                    "}\n",
20226                    Style));
20227   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20228   verifyFormat("test() {\n"
20229                "  ([]() -> {\n"
20230                "    int b = 32;\n"
20231                "    return 3;\n"
20232                "  }).foo();\n"
20233                "}",
20234                Style);
20235   verifyFormat("test() {\n"
20236                "  []() -> {\n"
20237                "    int b = 32;\n"
20238                "    return 3;\n"
20239                "  }\n"
20240                "}",
20241                Style);
20242   verifyFormat("std::sort(v.begin(), v.end(),\n"
20243                "          [](const auto &someLongArgumentName, const auto "
20244                "&someOtherLongArgumentName) {\n"
20245                "  return someLongArgumentName.someMemberVariable < "
20246                "someOtherLongArgumentName.someMemberVariable;\n"
20247                "});",
20248                Style);
20249   verifyFormat("test() {\n"
20250                "  (\n"
20251                "      []() -> {\n"
20252                "        int b = 32;\n"
20253                "        return 3;\n"
20254                "      },\n"
20255                "      foo, bar)\n"
20256                "      .foo();\n"
20257                "}",
20258                Style);
20259   verifyFormat("test() {\n"
20260                "  ([]() -> {\n"
20261                "    int b = 32;\n"
20262                "    return 3;\n"
20263                "  })\n"
20264                "      .foo()\n"
20265                "      .bar();\n"
20266                "}",
20267                Style);
20268   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20269             "  return promise.then(\n"
20270             "      [this, &someVariable, someObject = "
20271             "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20272             "    return someObject.startAsyncAction().then(\n"
20273             "        [this, &someVariable](AsyncActionResult result) mutable { "
20274             "result.processMore(); });\n"
20275             "  });\n"
20276             "}\n",
20277             format("SomeResult doSomething(SomeObject promise) {\n"
20278                    "  return promise.then([this, &someVariable, someObject = "
20279                    "std::mv(s)](std::vector<int> evaluated) mutable {\n"
20280                    "    return someObject.startAsyncAction().then([this, "
20281                    "&someVariable](AsyncActionResult result) mutable {\n"
20282                    "      result.processMore();\n"
20283                    "    });\n"
20284                    "  });\n"
20285                    "}\n",
20286                    Style));
20287   EXPECT_EQ("SomeResult doSomething(SomeObject promise) {\n"
20288             "  return promise.then([this, &someVariable] {\n"
20289             "    return someObject.startAsyncAction().then(\n"
20290             "        [this, &someVariable](AsyncActionResult result) mutable { "
20291             "result.processMore(); });\n"
20292             "  });\n"
20293             "}\n",
20294             format("SomeResult doSomething(SomeObject promise) {\n"
20295                    "  return promise.then([this, &someVariable] {\n"
20296                    "    return someObject.startAsyncAction().then([this, "
20297                    "&someVariable](AsyncActionResult result) mutable {\n"
20298                    "      result.processMore();\n"
20299                    "    });\n"
20300                    "  });\n"
20301                    "}\n",
20302                    Style));
20303   Style = getGoogleStyle();
20304   Style.LambdaBodyIndentation = FormatStyle::LBI_OuterScope;
20305   EXPECT_EQ("#define A                                       \\\n"
20306             "  [] {                                          \\\n"
20307             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
20308             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
20309             "      }",
20310             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
20311                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
20312                    Style));
20313   // TODO: The current formatting has a minor issue that's not worth fixing
20314   // right now whereby the closing brace is indented relative to the signature
20315   // instead of being aligned. This only happens with macros.
20316 }
20317 
TEST_F(FormatTest,LambdaWithLineComments)20318 TEST_F(FormatTest, LambdaWithLineComments) {
20319   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
20320   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
20321   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
20322   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
20323       FormatStyle::ShortLambdaStyle::SLS_All;
20324 
20325   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
20326   verifyFormat("auto k = []() // comment\n"
20327                "{ return; }",
20328                LLVMWithBeforeLambdaBody);
20329   verifyFormat("auto k = []() /* comment */ { return; }",
20330                LLVMWithBeforeLambdaBody);
20331   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
20332                LLVMWithBeforeLambdaBody);
20333   verifyFormat("auto k = []() // X\n"
20334                "{ return; }",
20335                LLVMWithBeforeLambdaBody);
20336   verifyFormat(
20337       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
20338       "{ return; }",
20339       LLVMWithBeforeLambdaBody);
20340 }
20341 
TEST_F(FormatTest,EmptyLinesInLambdas)20342 TEST_F(FormatTest, EmptyLinesInLambdas) {
20343   verifyFormat("auto lambda = []() {\n"
20344                "  x(); //\n"
20345                "};",
20346                "auto lambda = []() {\n"
20347                "\n"
20348                "  x(); //\n"
20349                "\n"
20350                "};");
20351 }
20352 
TEST_F(FormatTest,FormatsBlocks)20353 TEST_F(FormatTest, FormatsBlocks) {
20354   FormatStyle ShortBlocks = getLLVMStyle();
20355   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
20356   verifyFormat("int (^Block)(int, int);", ShortBlocks);
20357   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
20358   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
20359   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
20360   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
20361   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
20362 
20363   verifyFormat("foo(^{ bar(); });", ShortBlocks);
20364   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
20365   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
20366 
20367   verifyFormat("[operation setCompletionBlock:^{\n"
20368                "  [self onOperationDone];\n"
20369                "}];");
20370   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
20371                "  [self onOperationDone];\n"
20372                "}]};");
20373   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
20374                "  f();\n"
20375                "}];");
20376   verifyFormat("int a = [operation block:^int(int *i) {\n"
20377                "  return 1;\n"
20378                "}];");
20379   verifyFormat("[myObject doSomethingWith:arg1\n"
20380                "                      aaa:^int(int *a) {\n"
20381                "                        return 1;\n"
20382                "                      }\n"
20383                "                      bbb:f(a * bbbbbbbb)];");
20384 
20385   verifyFormat("[operation setCompletionBlock:^{\n"
20386                "  [self.delegate newDataAvailable];\n"
20387                "}];",
20388                getLLVMStyleWithColumns(60));
20389   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
20390                "  NSString *path = [self sessionFilePath];\n"
20391                "  if (path) {\n"
20392                "    // ...\n"
20393                "  }\n"
20394                "});");
20395   verifyFormat("[[SessionService sharedService]\n"
20396                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20397                "      if (window) {\n"
20398                "        [self windowDidLoad:window];\n"
20399                "      } else {\n"
20400                "        [self errorLoadingWindow];\n"
20401                "      }\n"
20402                "    }];");
20403   verifyFormat("void (^largeBlock)(void) = ^{\n"
20404                "  // ...\n"
20405                "};\n",
20406                getLLVMStyleWithColumns(40));
20407   verifyFormat("[[SessionService sharedService]\n"
20408                "    loadWindowWithCompletionBlock: //\n"
20409                "        ^(SessionWindow *window) {\n"
20410                "          if (window) {\n"
20411                "            [self windowDidLoad:window];\n"
20412                "          } else {\n"
20413                "            [self errorLoadingWindow];\n"
20414                "          }\n"
20415                "        }];",
20416                getLLVMStyleWithColumns(60));
20417   verifyFormat("[myObject doSomethingWith:arg1\n"
20418                "    firstBlock:^(Foo *a) {\n"
20419                "      // ...\n"
20420                "      int i;\n"
20421                "    }\n"
20422                "    secondBlock:^(Bar *b) {\n"
20423                "      // ...\n"
20424                "      int i;\n"
20425                "    }\n"
20426                "    thirdBlock:^Foo(Bar *b) {\n"
20427                "      // ...\n"
20428                "      int i;\n"
20429                "    }];");
20430   verifyFormat("[myObject doSomethingWith:arg1\n"
20431                "               firstBlock:-1\n"
20432                "              secondBlock:^(Bar *b) {\n"
20433                "                // ...\n"
20434                "                int i;\n"
20435                "              }];");
20436 
20437   verifyFormat("f(^{\n"
20438                "  @autoreleasepool {\n"
20439                "    if (a) {\n"
20440                "      g();\n"
20441                "    }\n"
20442                "  }\n"
20443                "});");
20444   verifyFormat("Block b = ^int *(A *a, B *b) {}");
20445   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
20446                "};");
20447 
20448   FormatStyle FourIndent = getLLVMStyle();
20449   FourIndent.ObjCBlockIndentWidth = 4;
20450   verifyFormat("[operation setCompletionBlock:^{\n"
20451                "    [self onOperationDone];\n"
20452                "}];",
20453                FourIndent);
20454 }
20455 
TEST_F(FormatTest,FormatsBlocksWithZeroColumnWidth)20456 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
20457   FormatStyle ZeroColumn = getLLVMStyle();
20458   ZeroColumn.ColumnLimit = 0;
20459 
20460   verifyFormat("[[SessionService sharedService] "
20461                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20462                "  if (window) {\n"
20463                "    [self windowDidLoad:window];\n"
20464                "  } else {\n"
20465                "    [self errorLoadingWindow];\n"
20466                "  }\n"
20467                "}];",
20468                ZeroColumn);
20469   EXPECT_EQ("[[SessionService sharedService]\n"
20470             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20471             "      if (window) {\n"
20472             "        [self windowDidLoad:window];\n"
20473             "      } else {\n"
20474             "        [self errorLoadingWindow];\n"
20475             "      }\n"
20476             "    }];",
20477             format("[[SessionService sharedService]\n"
20478                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
20479                    "                if (window) {\n"
20480                    "    [self windowDidLoad:window];\n"
20481                    "  } else {\n"
20482                    "    [self errorLoadingWindow];\n"
20483                    "  }\n"
20484                    "}];",
20485                    ZeroColumn));
20486   verifyFormat("[myObject doSomethingWith:arg1\n"
20487                "    firstBlock:^(Foo *a) {\n"
20488                "      // ...\n"
20489                "      int i;\n"
20490                "    }\n"
20491                "    secondBlock:^(Bar *b) {\n"
20492                "      // ...\n"
20493                "      int i;\n"
20494                "    }\n"
20495                "    thirdBlock:^Foo(Bar *b) {\n"
20496                "      // ...\n"
20497                "      int i;\n"
20498                "    }];",
20499                ZeroColumn);
20500   verifyFormat("f(^{\n"
20501                "  @autoreleasepool {\n"
20502                "    if (a) {\n"
20503                "      g();\n"
20504                "    }\n"
20505                "  }\n"
20506                "});",
20507                ZeroColumn);
20508   verifyFormat("void (^largeBlock)(void) = ^{\n"
20509                "  // ...\n"
20510                "};",
20511                ZeroColumn);
20512 
20513   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
20514   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
20515             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
20516   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
20517   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
20518             "  int i;\n"
20519             "};",
20520             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
20521 }
20522 
TEST_F(FormatTest,SupportsCRLF)20523 TEST_F(FormatTest, SupportsCRLF) {
20524   EXPECT_EQ("int a;\r\n"
20525             "int b;\r\n"
20526             "int c;\r\n",
20527             format("int a;\r\n"
20528                    "  int b;\r\n"
20529                    "    int c;\r\n",
20530                    getLLVMStyle()));
20531   EXPECT_EQ("int a;\r\n"
20532             "int b;\r\n"
20533             "int c;\r\n",
20534             format("int a;\r\n"
20535                    "  int b;\n"
20536                    "    int c;\r\n",
20537                    getLLVMStyle()));
20538   EXPECT_EQ("int a;\n"
20539             "int b;\n"
20540             "int c;\n",
20541             format("int a;\r\n"
20542                    "  int b;\n"
20543                    "    int c;\n",
20544                    getLLVMStyle()));
20545   EXPECT_EQ("\"aaaaaaa \"\r\n"
20546             "\"bbbbbbb\";\r\n",
20547             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
20548   EXPECT_EQ("#define A \\\r\n"
20549             "  b;      \\\r\n"
20550             "  c;      \\\r\n"
20551             "  d;\r\n",
20552             format("#define A \\\r\n"
20553                    "  b; \\\r\n"
20554                    "  c; d; \r\n",
20555                    getGoogleStyle()));
20556 
20557   EXPECT_EQ("/*\r\n"
20558             "multi line block comments\r\n"
20559             "should not introduce\r\n"
20560             "an extra carriage return\r\n"
20561             "*/\r\n",
20562             format("/*\r\n"
20563                    "multi line block comments\r\n"
20564                    "should not introduce\r\n"
20565                    "an extra carriage return\r\n"
20566                    "*/\r\n"));
20567   EXPECT_EQ("/*\r\n"
20568             "\r\n"
20569             "*/",
20570             format("/*\r\n"
20571                    "    \r\r\r\n"
20572                    "*/"));
20573 
20574   FormatStyle style = getLLVMStyle();
20575 
20576   style.DeriveLineEnding = true;
20577   style.UseCRLF = false;
20578   EXPECT_EQ("union FooBarBazQux {\n"
20579             "  int foo;\n"
20580             "  int bar;\n"
20581             "  int baz;\n"
20582             "};",
20583             format("union FooBarBazQux {\r\n"
20584                    "  int foo;\n"
20585                    "  int bar;\r\n"
20586                    "  int baz;\n"
20587                    "};",
20588                    style));
20589   style.UseCRLF = true;
20590   EXPECT_EQ("union FooBarBazQux {\r\n"
20591             "  int foo;\r\n"
20592             "  int bar;\r\n"
20593             "  int baz;\r\n"
20594             "};",
20595             format("union FooBarBazQux {\r\n"
20596                    "  int foo;\n"
20597                    "  int bar;\r\n"
20598                    "  int baz;\n"
20599                    "};",
20600                    style));
20601 
20602   style.DeriveLineEnding = false;
20603   style.UseCRLF = false;
20604   EXPECT_EQ("union FooBarBazQux {\n"
20605             "  int foo;\n"
20606             "  int bar;\n"
20607             "  int baz;\n"
20608             "  int qux;\n"
20609             "};",
20610             format("union FooBarBazQux {\r\n"
20611                    "  int foo;\n"
20612                    "  int bar;\r\n"
20613                    "  int baz;\n"
20614                    "  int qux;\r\n"
20615                    "};",
20616                    style));
20617   style.UseCRLF = true;
20618   EXPECT_EQ("union FooBarBazQux {\r\n"
20619             "  int foo;\r\n"
20620             "  int bar;\r\n"
20621             "  int baz;\r\n"
20622             "  int qux;\r\n"
20623             "};",
20624             format("union FooBarBazQux {\r\n"
20625                    "  int foo;\n"
20626                    "  int bar;\r\n"
20627                    "  int baz;\n"
20628                    "  int qux;\n"
20629                    "};",
20630                    style));
20631 
20632   style.DeriveLineEnding = true;
20633   style.UseCRLF = false;
20634   EXPECT_EQ("union FooBarBazQux {\r\n"
20635             "  int foo;\r\n"
20636             "  int bar;\r\n"
20637             "  int baz;\r\n"
20638             "  int qux;\r\n"
20639             "};",
20640             format("union FooBarBazQux {\r\n"
20641                    "  int foo;\n"
20642                    "  int bar;\r\n"
20643                    "  int baz;\n"
20644                    "  int qux;\r\n"
20645                    "};",
20646                    style));
20647   style.UseCRLF = true;
20648   EXPECT_EQ("union FooBarBazQux {\n"
20649             "  int foo;\n"
20650             "  int bar;\n"
20651             "  int baz;\n"
20652             "  int qux;\n"
20653             "};",
20654             format("union FooBarBazQux {\r\n"
20655                    "  int foo;\n"
20656                    "  int bar;\r\n"
20657                    "  int baz;\n"
20658                    "  int qux;\n"
20659                    "};",
20660                    style));
20661 }
20662 
TEST_F(FormatTest,MunchSemicolonAfterBlocks)20663 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
20664   verifyFormat("MY_CLASS(C) {\n"
20665                "  int i;\n"
20666                "  int j;\n"
20667                "};");
20668 }
20669 
TEST_F(FormatTest,ConfigurableContinuationIndentWidth)20670 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
20671   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
20672   TwoIndent.ContinuationIndentWidth = 2;
20673 
20674   EXPECT_EQ("int i =\n"
20675             "  longFunction(\n"
20676             "    arg);",
20677             format("int i = longFunction(arg);", TwoIndent));
20678 
20679   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
20680   SixIndent.ContinuationIndentWidth = 6;
20681 
20682   EXPECT_EQ("int i =\n"
20683             "      longFunction(\n"
20684             "            arg);",
20685             format("int i = longFunction(arg);", SixIndent));
20686 }
20687 
TEST_F(FormatTest,WrappedClosingParenthesisIndent)20688 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
20689   FormatStyle Style = getLLVMStyle();
20690   verifyFormat("int Foo::getter(\n"
20691                "    //\n"
20692                ") const {\n"
20693                "  return foo;\n"
20694                "}",
20695                Style);
20696   verifyFormat("void Foo::setter(\n"
20697                "    //\n"
20698                ") {\n"
20699                "  foo = 1;\n"
20700                "}",
20701                Style);
20702 }
20703 
TEST_F(FormatTest,SpacesInAngles)20704 TEST_F(FormatTest, SpacesInAngles) {
20705   FormatStyle Spaces = getLLVMStyle();
20706   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
20707 
20708   verifyFormat("vector< ::std::string > x1;", Spaces);
20709   verifyFormat("Foo< int, Bar > x2;", Spaces);
20710   verifyFormat("Foo< ::int, ::Bar > x3;", Spaces);
20711 
20712   verifyFormat("static_cast< int >(arg);", Spaces);
20713   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
20714   verifyFormat("f< int, float >();", Spaces);
20715   verifyFormat("template <> g() {}", Spaces);
20716   verifyFormat("template < std::vector< int > > f() {}", Spaces);
20717   verifyFormat("std::function< void(int, int) > fct;", Spaces);
20718   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
20719                Spaces);
20720 
20721   Spaces.Standard = FormatStyle::LS_Cpp03;
20722   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
20723   verifyFormat("A< A< int > >();", Spaces);
20724 
20725   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
20726   verifyFormat("A<A<int> >();", Spaces);
20727 
20728   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
20729   verifyFormat("vector< ::std::string> x4;", "vector<::std::string> x4;",
20730                Spaces);
20731   verifyFormat("vector< ::std::string > x4;", "vector<::std::string > x4;",
20732                Spaces);
20733 
20734   verifyFormat("A<A<int> >();", Spaces);
20735   verifyFormat("A<A<int> >();", "A<A<int>>();", Spaces);
20736   verifyFormat("A< A< int > >();", Spaces);
20737 
20738   Spaces.Standard = FormatStyle::LS_Cpp11;
20739   Spaces.SpacesInAngles = FormatStyle::SIAS_Always;
20740   verifyFormat("A< A< int > >();", Spaces);
20741 
20742   Spaces.SpacesInAngles = FormatStyle::SIAS_Never;
20743   verifyFormat("vector<::std::string> x4;", Spaces);
20744   verifyFormat("vector<int> x5;", Spaces);
20745   verifyFormat("Foo<int, Bar> x6;", Spaces);
20746   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
20747 
20748   verifyFormat("A<A<int>>();", Spaces);
20749 
20750   Spaces.SpacesInAngles = FormatStyle::SIAS_Leave;
20751   verifyFormat("vector<::std::string> x4;", Spaces);
20752   verifyFormat("vector< ::std::string > x4;", Spaces);
20753   verifyFormat("vector<int> x5;", Spaces);
20754   verifyFormat("vector< int > x5;", Spaces);
20755   verifyFormat("Foo<int, Bar> x6;", Spaces);
20756   verifyFormat("Foo< int, Bar > x6;", Spaces);
20757   verifyFormat("Foo<::int, ::Bar> x7;", Spaces);
20758   verifyFormat("Foo< ::int, ::Bar > x7;", Spaces);
20759 
20760   verifyFormat("A<A<int>>();", Spaces);
20761   verifyFormat("A< A< int > >();", Spaces);
20762   verifyFormat("A<A<int > >();", Spaces);
20763   verifyFormat("A< A< int>>();", Spaces);
20764 }
20765 
TEST_F(FormatTest,SpaceAfterTemplateKeyword)20766 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
20767   FormatStyle Style = getLLVMStyle();
20768   Style.SpaceAfterTemplateKeyword = false;
20769   verifyFormat("template<int> void foo();", Style);
20770 }
20771 
TEST_F(FormatTest,TripleAngleBrackets)20772 TEST_F(FormatTest, TripleAngleBrackets) {
20773   verifyFormat("f<<<1, 1>>>();");
20774   verifyFormat("f<<<1, 1, 1, s>>>();");
20775   verifyFormat("f<<<a, b, c, d>>>();");
20776   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
20777   verifyFormat("f<param><<<1, 1>>>();");
20778   verifyFormat("f<1><<<1, 1>>>();");
20779   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
20780   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
20781                "aaaaaaaaaaa<<<\n    1, 1>>>();");
20782   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
20783                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
20784 }
20785 
TEST_F(FormatTest,MergeLessLessAtEnd)20786 TEST_F(FormatTest, MergeLessLessAtEnd) {
20787   verifyFormat("<<");
20788   EXPECT_EQ("< < <", format("\\\n<<<"));
20789   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
20790                "aaallvm::outs() <<");
20791   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
20792                "aaaallvm::outs()\n    <<");
20793 }
20794 
TEST_F(FormatTest,HandleUnbalancedImplicitBracesAcrossPPBranches)20795 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
20796   std::string code = "#if A\n"
20797                      "#if B\n"
20798                      "a.\n"
20799                      "#endif\n"
20800                      "    a = 1;\n"
20801                      "#else\n"
20802                      "#endif\n"
20803                      "#if C\n"
20804                      "#else\n"
20805                      "#endif\n";
20806   EXPECT_EQ(code, format(code));
20807 }
20808 
TEST_F(FormatTest,HandleConflictMarkers)20809 TEST_F(FormatTest, HandleConflictMarkers) {
20810   // Git/SVN conflict markers.
20811   EXPECT_EQ("int a;\n"
20812             "void f() {\n"
20813             "  callme(some(parameter1,\n"
20814             "<<<<<<< text by the vcs\n"
20815             "              parameter2),\n"
20816             "||||||| text by the vcs\n"
20817             "              parameter2),\n"
20818             "         parameter3,\n"
20819             "======= text by the vcs\n"
20820             "              parameter2, parameter3),\n"
20821             ">>>>>>> text by the vcs\n"
20822             "         otherparameter);\n",
20823             format("int a;\n"
20824                    "void f() {\n"
20825                    "  callme(some(parameter1,\n"
20826                    "<<<<<<< text by the vcs\n"
20827                    "  parameter2),\n"
20828                    "||||||| text by the vcs\n"
20829                    "  parameter2),\n"
20830                    "  parameter3,\n"
20831                    "======= text by the vcs\n"
20832                    "  parameter2,\n"
20833                    "  parameter3),\n"
20834                    ">>>>>>> text by the vcs\n"
20835                    "  otherparameter);\n"));
20836 
20837   // Perforce markers.
20838   EXPECT_EQ("void f() {\n"
20839             "  function(\n"
20840             ">>>> text by the vcs\n"
20841             "      parameter,\n"
20842             "==== text by the vcs\n"
20843             "      parameter,\n"
20844             "==== text by the vcs\n"
20845             "      parameter,\n"
20846             "<<<< text by the vcs\n"
20847             "      parameter);\n",
20848             format("void f() {\n"
20849                    "  function(\n"
20850                    ">>>> text by the vcs\n"
20851                    "  parameter,\n"
20852                    "==== text by the vcs\n"
20853                    "  parameter,\n"
20854                    "==== text by the vcs\n"
20855                    "  parameter,\n"
20856                    "<<<< text by the vcs\n"
20857                    "  parameter);\n"));
20858 
20859   EXPECT_EQ("<<<<<<<\n"
20860             "|||||||\n"
20861             "=======\n"
20862             ">>>>>>>",
20863             format("<<<<<<<\n"
20864                    "|||||||\n"
20865                    "=======\n"
20866                    ">>>>>>>"));
20867 
20868   EXPECT_EQ("<<<<<<<\n"
20869             "|||||||\n"
20870             "int i;\n"
20871             "=======\n"
20872             ">>>>>>>",
20873             format("<<<<<<<\n"
20874                    "|||||||\n"
20875                    "int i;\n"
20876                    "=======\n"
20877                    ">>>>>>>"));
20878 
20879   // FIXME: Handle parsing of macros around conflict markers correctly:
20880   EXPECT_EQ("#define Macro \\\n"
20881             "<<<<<<<\n"
20882             "Something \\\n"
20883             "|||||||\n"
20884             "Else \\\n"
20885             "=======\n"
20886             "Other \\\n"
20887             ">>>>>>>\n"
20888             "    End int i;\n",
20889             format("#define Macro \\\n"
20890                    "<<<<<<<\n"
20891                    "  Something \\\n"
20892                    "|||||||\n"
20893                    "  Else \\\n"
20894                    "=======\n"
20895                    "  Other \\\n"
20896                    ">>>>>>>\n"
20897                    "  End\n"
20898                    "int i;\n"));
20899 }
20900 
TEST_F(FormatTest,DisableRegions)20901 TEST_F(FormatTest, DisableRegions) {
20902   EXPECT_EQ("int i;\n"
20903             "// clang-format off\n"
20904             "  int j;\n"
20905             "// clang-format on\n"
20906             "int k;",
20907             format(" int  i;\n"
20908                    "   // clang-format off\n"
20909                    "  int j;\n"
20910                    " // clang-format on\n"
20911                    "   int   k;"));
20912   EXPECT_EQ("int i;\n"
20913             "/* clang-format off */\n"
20914             "  int j;\n"
20915             "/* clang-format on */\n"
20916             "int k;",
20917             format(" int  i;\n"
20918                    "   /* clang-format off */\n"
20919                    "  int j;\n"
20920                    " /* clang-format on */\n"
20921                    "   int   k;"));
20922 
20923   // Don't reflow comments within disabled regions.
20924   EXPECT_EQ("// clang-format off\n"
20925             "// long long long long long long line\n"
20926             "/* clang-format on */\n"
20927             "/* long long long\n"
20928             " * long long long\n"
20929             " * line */\n"
20930             "int i;\n"
20931             "/* clang-format off */\n"
20932             "/* long long long long long long line */\n",
20933             format("// clang-format off\n"
20934                    "// long long long long long long line\n"
20935                    "/* clang-format on */\n"
20936                    "/* long long long long long long line */\n"
20937                    "int i;\n"
20938                    "/* clang-format off */\n"
20939                    "/* long long long long long long line */\n",
20940                    getLLVMStyleWithColumns(20)));
20941 }
20942 
TEST_F(FormatTest,DoNotCrashOnInvalidInput)20943 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
20944   format("? ) =");
20945   verifyNoCrash("#define a\\\n /**/}");
20946 }
20947 
TEST_F(FormatTest,FormatsTableGenCode)20948 TEST_F(FormatTest, FormatsTableGenCode) {
20949   FormatStyle Style = getLLVMStyle();
20950   Style.Language = FormatStyle::LK_TableGen;
20951   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
20952 }
20953 
TEST_F(FormatTest,ArrayOfTemplates)20954 TEST_F(FormatTest, ArrayOfTemplates) {
20955   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
20956             format("auto a = new unique_ptr<int > [ 10];"));
20957 
20958   FormatStyle Spaces = getLLVMStyle();
20959   Spaces.SpacesInSquareBrackets = true;
20960   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
20961             format("auto a = new unique_ptr<int > [10];", Spaces));
20962 }
20963 
TEST_F(FormatTest,ArrayAsTemplateType)20964 TEST_F(FormatTest, ArrayAsTemplateType) {
20965   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
20966             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
20967 
20968   FormatStyle Spaces = getLLVMStyle();
20969   Spaces.SpacesInSquareBrackets = true;
20970   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
20971             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
20972 }
20973 
TEST_F(FormatTest,NoSpaceAfterSuper)20974 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
20975 
TEST(FormatStyle,GetStyleWithEmptyFileName)20976 TEST(FormatStyle, GetStyleWithEmptyFileName) {
20977   llvm::vfs::InMemoryFileSystem FS;
20978   auto Style1 = getStyle("file", "", "Google", "", &FS);
20979   ASSERT_TRUE((bool)Style1);
20980   ASSERT_EQ(*Style1, getGoogleStyle());
20981 }
20982 
TEST(FormatStyle,GetStyleOfFile)20983 TEST(FormatStyle, GetStyleOfFile) {
20984   llvm::vfs::InMemoryFileSystem FS;
20985   // Test 1: format file in the same directory.
20986   ASSERT_TRUE(
20987       FS.addFile("/a/.clang-format", 0,
20988                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
20989   ASSERT_TRUE(
20990       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
20991   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
20992   ASSERT_TRUE((bool)Style1);
20993   ASSERT_EQ(*Style1, getLLVMStyle());
20994 
20995   // Test 2.1: fallback to default.
20996   ASSERT_TRUE(
20997       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
20998   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
20999   ASSERT_TRUE((bool)Style2);
21000   ASSERT_EQ(*Style2, getMozillaStyle());
21001 
21002   // Test 2.2: no format on 'none' fallback style.
21003   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
21004   ASSERT_TRUE((bool)Style2);
21005   ASSERT_EQ(*Style2, getNoStyle());
21006 
21007   // Test 2.3: format if config is found with no based style while fallback is
21008   // 'none'.
21009   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
21010                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
21011   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
21012   ASSERT_TRUE((bool)Style2);
21013   ASSERT_EQ(*Style2, getLLVMStyle());
21014 
21015   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
21016   Style2 = getStyle("{}", "a.h", "none", "", &FS);
21017   ASSERT_TRUE((bool)Style2);
21018   ASSERT_EQ(*Style2, getLLVMStyle());
21019 
21020   // Test 3: format file in parent directory.
21021   ASSERT_TRUE(
21022       FS.addFile("/c/.clang-format", 0,
21023                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
21024   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
21025                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21026   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
21027   ASSERT_TRUE((bool)Style3);
21028   ASSERT_EQ(*Style3, getGoogleStyle());
21029 
21030   // Test 4: error on invalid fallback style
21031   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
21032   ASSERT_FALSE((bool)Style4);
21033   llvm::consumeError(Style4.takeError());
21034 
21035   // Test 5: error on invalid yaml on command line
21036   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
21037   ASSERT_FALSE((bool)Style5);
21038   llvm::consumeError(Style5.takeError());
21039 
21040   // Test 6: error on invalid style
21041   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
21042   ASSERT_FALSE((bool)Style6);
21043   llvm::consumeError(Style6.takeError());
21044 
21045   // Test 7: found config file, error on parsing it
21046   ASSERT_TRUE(
21047       FS.addFile("/d/.clang-format", 0,
21048                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
21049                                                   "InvalidKey: InvalidValue")));
21050   ASSERT_TRUE(
21051       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
21052   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
21053   ASSERT_FALSE((bool)Style7a);
21054   llvm::consumeError(Style7a.takeError());
21055 
21056   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
21057   ASSERT_TRUE((bool)Style7b);
21058 
21059   // Test 8: inferred per-language defaults apply.
21060   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
21061   ASSERT_TRUE((bool)StyleTd);
21062   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
21063 
21064   // Test 9.1: overwriting a file style, when parent no file exists with no
21065   // fallback style
21066   ASSERT_TRUE(FS.addFile(
21067       "/e/sub/.clang-format", 0,
21068       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
21069                                        "ColumnLimit: 20")));
21070   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
21071                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21072   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21073   ASSERT_TRUE(static_cast<bool>(Style9));
21074   ASSERT_EQ(*Style9, [] {
21075     auto Style = getNoStyle();
21076     Style.ColumnLimit = 20;
21077     return Style;
21078   }());
21079 
21080   // Test 9.2: with LLVM fallback style
21081   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
21082   ASSERT_TRUE(static_cast<bool>(Style9));
21083   ASSERT_EQ(*Style9, [] {
21084     auto Style = getLLVMStyle();
21085     Style.ColumnLimit = 20;
21086     return Style;
21087   }());
21088 
21089   // Test 9.3: with a parent file
21090   ASSERT_TRUE(
21091       FS.addFile("/e/.clang-format", 0,
21092                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
21093                                                   "UseTab: Always")));
21094   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
21095   ASSERT_TRUE(static_cast<bool>(Style9));
21096   ASSERT_EQ(*Style9, [] {
21097     auto Style = getGoogleStyle();
21098     Style.ColumnLimit = 20;
21099     Style.UseTab = FormatStyle::UT_Always;
21100     return Style;
21101   }());
21102 
21103   // Test 9.4: propagate more than one level
21104   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
21105                          llvm::MemoryBuffer::getMemBuffer("int i;")));
21106   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
21107                          llvm::MemoryBuffer::getMemBuffer(
21108                              "BasedOnStyle: InheritParentConfig\n"
21109                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
21110   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
21111 
21112   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
21113     auto Style = getGoogleStyle();
21114     Style.ColumnLimit = 20;
21115     Style.UseTab = FormatStyle::UT_Always;
21116     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
21117     return Style;
21118   }();
21119 
21120   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
21121   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
21122   ASSERT_TRUE(static_cast<bool>(Style9));
21123   ASSERT_EQ(*Style9, SubSubStyle);
21124 
21125   // Test 9.5: use InheritParentConfig as style name
21126   Style9 =
21127       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
21128   ASSERT_TRUE(static_cast<bool>(Style9));
21129   ASSERT_EQ(*Style9, SubSubStyle);
21130 
21131   // Test 9.6: use command line style with inheritance
21132   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
21133                     "none", "", &FS);
21134   ASSERT_TRUE(static_cast<bool>(Style9));
21135   ASSERT_EQ(*Style9, SubSubStyle);
21136 
21137   // Test 9.7: use command line style with inheritance and own config
21138   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
21139                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
21140                     "/e/sub/code.cpp", "none", "", &FS);
21141   ASSERT_TRUE(static_cast<bool>(Style9));
21142   ASSERT_EQ(*Style9, SubSubStyle);
21143 
21144   // Test 9.8: use inheritance from a file without BasedOnStyle
21145   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
21146                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
21147   ASSERT_TRUE(
21148       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
21149                  llvm::MemoryBuffer::getMemBuffer(
21150                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
21151   // Make sure we do not use the fallback style
21152   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
21153   ASSERT_TRUE(static_cast<bool>(Style9));
21154   ASSERT_EQ(*Style9, [] {
21155     auto Style = getLLVMStyle();
21156     Style.ColumnLimit = 123;
21157     return Style;
21158   }());
21159 
21160   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
21161   ASSERT_TRUE(static_cast<bool>(Style9));
21162   ASSERT_EQ(*Style9, [] {
21163     auto Style = getLLVMStyle();
21164     Style.ColumnLimit = 123;
21165     Style.IndentWidth = 7;
21166     return Style;
21167   }());
21168 }
21169 
TEST_F(ReplacementTest,FormatCodeAfterReplacements)21170 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
21171   // Column limit is 20.
21172   std::string Code = "Type *a =\n"
21173                      "    new Type();\n"
21174                      "g(iiiii, 0, jjjjj,\n"
21175                      "  0, kkkkk, 0, mm);\n"
21176                      "int  bad     = format   ;";
21177   std::string Expected = "auto a = new Type();\n"
21178                          "g(iiiii, nullptr,\n"
21179                          "  jjjjj, nullptr,\n"
21180                          "  kkkkk, nullptr,\n"
21181                          "  mm);\n"
21182                          "int  bad     = format   ;";
21183   FileID ID = Context.createInMemoryFile("format.cpp", Code);
21184   tooling::Replacements Replaces = toReplacements(
21185       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
21186                             "auto "),
21187        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
21188                             "nullptr"),
21189        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
21190                             "nullptr"),
21191        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
21192                             "nullptr")});
21193 
21194   format::FormatStyle Style = format::getLLVMStyle();
21195   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
21196   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
21197   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
21198       << llvm::toString(FormattedReplaces.takeError()) << "\n";
21199   auto Result = applyAllReplacements(Code, *FormattedReplaces);
21200   EXPECT_TRUE(static_cast<bool>(Result));
21201   EXPECT_EQ(Expected, *Result);
21202 }
21203 
TEST_F(ReplacementTest,SortIncludesAfterReplacement)21204 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
21205   std::string Code = "#include \"a.h\"\n"
21206                      "#include \"c.h\"\n"
21207                      "\n"
21208                      "int main() {\n"
21209                      "  return 0;\n"
21210                      "}";
21211   std::string Expected = "#include \"a.h\"\n"
21212                          "#include \"b.h\"\n"
21213                          "#include \"c.h\"\n"
21214                          "\n"
21215                          "int main() {\n"
21216                          "  return 0;\n"
21217                          "}";
21218   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
21219   tooling::Replacements Replaces = toReplacements(
21220       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
21221                             "#include \"b.h\"\n")});
21222 
21223   format::FormatStyle Style = format::getLLVMStyle();
21224   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
21225   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
21226   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
21227       << llvm::toString(FormattedReplaces.takeError()) << "\n";
21228   auto Result = applyAllReplacements(Code, *FormattedReplaces);
21229   EXPECT_TRUE(static_cast<bool>(Result));
21230   EXPECT_EQ(Expected, *Result);
21231 }
21232 
TEST_F(FormatTest,FormatSortsUsingDeclarations)21233 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
21234   EXPECT_EQ("using std::cin;\n"
21235             "using std::cout;",
21236             format("using std::cout;\n"
21237                    "using std::cin;",
21238                    getGoogleStyle()));
21239 }
21240 
TEST_F(FormatTest,UTF8CharacterLiteralCpp03)21241 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
21242   format::FormatStyle Style = format::getLLVMStyle();
21243   Style.Standard = FormatStyle::LS_Cpp03;
21244   // cpp03 recognize this string as identifier u8 and literal character 'a'
21245   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
21246 }
21247 
TEST_F(FormatTest,UTF8CharacterLiteralCpp11)21248 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
21249   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
21250   // all modes, including C++11, C++14 and C++17
21251   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
21252 }
21253 
TEST_F(FormatTest,DoNotFormatLikelyXml)21254 TEST_F(FormatTest, DoNotFormatLikelyXml) {
21255   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
21256   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
21257 }
21258 
TEST_F(FormatTest,StructuredBindings)21259 TEST_F(FormatTest, StructuredBindings) {
21260   // Structured bindings is a C++17 feature.
21261   // all modes, including C++11, C++14 and C++17
21262   verifyFormat("auto [a, b] = f();");
21263   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
21264   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
21265   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
21266   EXPECT_EQ("auto const volatile [a, b] = f();",
21267             format("auto  const   volatile[a, b] = f();"));
21268   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
21269   EXPECT_EQ("auto &[a, b, c] = f();",
21270             format("auto   &[  a  ,  b,c   ] = f();"));
21271   EXPECT_EQ("auto &&[a, b, c] = f();",
21272             format("auto   &&[  a  ,  b,c   ] = f();"));
21273   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
21274   EXPECT_EQ("auto const volatile &&[a, b] = f();",
21275             format("auto  const  volatile  &&[a, b] = f();"));
21276   EXPECT_EQ("auto const &&[a, b] = f();",
21277             format("auto  const   &&  [a, b] = f();"));
21278   EXPECT_EQ("const auto &[a, b] = f();",
21279             format("const  auto  &  [a, b] = f();"));
21280   EXPECT_EQ("const auto volatile &&[a, b] = f();",
21281             format("const  auto   volatile  &&[a, b] = f();"));
21282   EXPECT_EQ("volatile const auto &&[a, b] = f();",
21283             format("volatile  const  auto   &&[a, b] = f();"));
21284   EXPECT_EQ("const auto &&[a, b] = f();",
21285             format("const  auto  &&  [a, b] = f();"));
21286 
21287   // Make sure we don't mistake structured bindings for lambdas.
21288   FormatStyle PointerMiddle = getLLVMStyle();
21289   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
21290   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
21291   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
21292   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
21293   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
21294   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
21295   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
21296   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
21297   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
21298   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
21299   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
21300   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
21301   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
21302 
21303   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
21304             format("for (const auto   &&   [a, b] : some_range) {\n}"));
21305   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
21306             format("for (const auto   &   [a, b] : some_range) {\n}"));
21307   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
21308             format("for (const auto[a, b] : some_range) {\n}"));
21309   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
21310   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
21311   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
21312   EXPECT_EQ("auto const &[x, y](expr);",
21313             format("auto  const  &  [x,y]  (expr);"));
21314   EXPECT_EQ("auto const &&[x, y](expr);",
21315             format("auto  const  &&  [x,y]  (expr);"));
21316   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
21317   EXPECT_EQ("auto const &[x, y]{expr};",
21318             format("auto  const  &  [x,y]  {expr};"));
21319   EXPECT_EQ("auto const &&[x, y]{expr};",
21320             format("auto  const  &&  [x,y]  {expr};"));
21321 
21322   format::FormatStyle Spaces = format::getLLVMStyle();
21323   Spaces.SpacesInSquareBrackets = true;
21324   verifyFormat("auto [ a, b ] = f();", Spaces);
21325   verifyFormat("auto &&[ a, b ] = f();", Spaces);
21326   verifyFormat("auto &[ a, b ] = f();", Spaces);
21327   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
21328   verifyFormat("auto const &[ a, b ] = f();", Spaces);
21329 }
21330 
TEST_F(FormatTest,FileAndCode)21331 TEST_F(FormatTest, FileAndCode) {
21332   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
21333   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
21334   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
21335   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
21336   EXPECT_EQ(FormatStyle::LK_ObjC,
21337             guessLanguage("foo.h", "@interface Foo\n@end\n"));
21338   EXPECT_EQ(
21339       FormatStyle::LK_ObjC,
21340       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
21341   EXPECT_EQ(FormatStyle::LK_ObjC,
21342             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
21343   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
21344   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
21345   EXPECT_EQ(FormatStyle::LK_ObjC,
21346             guessLanguage("foo", "@interface Foo\n@end\n"));
21347   EXPECT_EQ(FormatStyle::LK_ObjC,
21348             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
21349   EXPECT_EQ(
21350       FormatStyle::LK_ObjC,
21351       guessLanguage("foo.h",
21352                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
21353   EXPECT_EQ(
21354       FormatStyle::LK_Cpp,
21355       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
21356 }
21357 
TEST_F(FormatTest,GuessLanguageWithCpp11AttributeSpecifiers)21358 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
21359   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
21360   EXPECT_EQ(FormatStyle::LK_ObjC,
21361             guessLanguage("foo.h", "array[[calculator getIndex]];"));
21362   EXPECT_EQ(FormatStyle::LK_Cpp,
21363             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
21364   EXPECT_EQ(
21365       FormatStyle::LK_Cpp,
21366       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
21367   EXPECT_EQ(FormatStyle::LK_ObjC,
21368             guessLanguage("foo.h", "[[noreturn foo] bar];"));
21369   EXPECT_EQ(FormatStyle::LK_Cpp,
21370             guessLanguage("foo.h", "[[clang::fallthrough]];"));
21371   EXPECT_EQ(FormatStyle::LK_ObjC,
21372             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
21373   EXPECT_EQ(FormatStyle::LK_Cpp,
21374             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
21375   EXPECT_EQ(FormatStyle::LK_Cpp,
21376             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
21377   EXPECT_EQ(FormatStyle::LK_ObjC,
21378             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
21379   EXPECT_EQ(FormatStyle::LK_Cpp,
21380             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
21381   EXPECT_EQ(
21382       FormatStyle::LK_Cpp,
21383       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
21384   EXPECT_EQ(
21385       FormatStyle::LK_Cpp,
21386       guessLanguage("foo.h",
21387                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
21388   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
21389 }
21390 
TEST_F(FormatTest,GuessLanguageWithCaret)21391 TEST_F(FormatTest, GuessLanguageWithCaret) {
21392   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
21393   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
21394   EXPECT_EQ(FormatStyle::LK_ObjC,
21395             guessLanguage("foo.h", "int(^)(char, float);"));
21396   EXPECT_EQ(FormatStyle::LK_ObjC,
21397             guessLanguage("foo.h", "int(^foo)(char, float);"));
21398   EXPECT_EQ(FormatStyle::LK_ObjC,
21399             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
21400   EXPECT_EQ(FormatStyle::LK_ObjC,
21401             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
21402   EXPECT_EQ(
21403       FormatStyle::LK_ObjC,
21404       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
21405 }
21406 
TEST_F(FormatTest,GuessLanguageWithPragmas)21407 TEST_F(FormatTest, GuessLanguageWithPragmas) {
21408   EXPECT_EQ(FormatStyle::LK_Cpp,
21409             guessLanguage("foo.h", "__pragma(warning(disable:))"));
21410   EXPECT_EQ(FormatStyle::LK_Cpp,
21411             guessLanguage("foo.h", "#pragma(warning(disable:))"));
21412   EXPECT_EQ(FormatStyle::LK_Cpp,
21413             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
21414 }
21415 
TEST_F(FormatTest,FormatsInlineAsmSymbolicNames)21416 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
21417   // ASM symbolic names are identifiers that must be surrounded by [] without
21418   // space in between:
21419   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
21420 
21421   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
21422   verifyFormat(R"(//
21423 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
21424 )");
21425 
21426   // A list of several ASM symbolic names.
21427   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
21428 
21429   // ASM symbolic names in inline ASM with inputs and outputs.
21430   verifyFormat(R"(//
21431 asm("cmoveq %1, %2, %[result]"
21432     : [result] "=r"(result)
21433     : "r"(test), "r"(new), "[result]"(old));
21434 )");
21435 
21436   // ASM symbolic names in inline ASM with no outputs.
21437   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
21438 }
21439 
TEST_F(FormatTest,GuessedLanguageWithInlineAsmClobbers)21440 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
21441   EXPECT_EQ(FormatStyle::LK_Cpp,
21442             guessLanguage("foo.h", "void f() {\n"
21443                                    "  asm (\"mov %[e], %[d]\"\n"
21444                                    "     : [d] \"=rm\" (d)\n"
21445                                    "       [e] \"rm\" (*e));\n"
21446                                    "}"));
21447   EXPECT_EQ(FormatStyle::LK_Cpp,
21448             guessLanguage("foo.h", "void f() {\n"
21449                                    "  _asm (\"mov %[e], %[d]\"\n"
21450                                    "     : [d] \"=rm\" (d)\n"
21451                                    "       [e] \"rm\" (*e));\n"
21452                                    "}"));
21453   EXPECT_EQ(FormatStyle::LK_Cpp,
21454             guessLanguage("foo.h", "void f() {\n"
21455                                    "  __asm (\"mov %[e], %[d]\"\n"
21456                                    "     : [d] \"=rm\" (d)\n"
21457                                    "       [e] \"rm\" (*e));\n"
21458                                    "}"));
21459   EXPECT_EQ(FormatStyle::LK_Cpp,
21460             guessLanguage("foo.h", "void f() {\n"
21461                                    "  __asm__ (\"mov %[e], %[d]\"\n"
21462                                    "     : [d] \"=rm\" (d)\n"
21463                                    "       [e] \"rm\" (*e));\n"
21464                                    "}"));
21465   EXPECT_EQ(FormatStyle::LK_Cpp,
21466             guessLanguage("foo.h", "void f() {\n"
21467                                    "  asm (\"mov %[e], %[d]\"\n"
21468                                    "     : [d] \"=rm\" (d),\n"
21469                                    "       [e] \"rm\" (*e));\n"
21470                                    "}"));
21471   EXPECT_EQ(FormatStyle::LK_Cpp,
21472             guessLanguage("foo.h", "void f() {\n"
21473                                    "  asm volatile (\"mov %[e], %[d]\"\n"
21474                                    "     : [d] \"=rm\" (d)\n"
21475                                    "       [e] \"rm\" (*e));\n"
21476                                    "}"));
21477 }
21478 
TEST_F(FormatTest,GuessLanguageWithChildLines)21479 TEST_F(FormatTest, GuessLanguageWithChildLines) {
21480   EXPECT_EQ(FormatStyle::LK_Cpp,
21481             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
21482   EXPECT_EQ(FormatStyle::LK_ObjC,
21483             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
21484   EXPECT_EQ(
21485       FormatStyle::LK_Cpp,
21486       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
21487   EXPECT_EQ(
21488       FormatStyle::LK_ObjC,
21489       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
21490 }
21491 
TEST_F(FormatTest,TypenameMacros)21492 TEST_F(FormatTest, TypenameMacros) {
21493   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
21494 
21495   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
21496   FormatStyle Google = getGoogleStyleWithColumns(0);
21497   Google.TypenameMacros = TypenameMacros;
21498   verifyFormat("struct foo {\n"
21499                "  int bar;\n"
21500                "  TAILQ_ENTRY(a) bleh;\n"
21501                "};",
21502                Google);
21503 
21504   FormatStyle Macros = getLLVMStyle();
21505   Macros.TypenameMacros = TypenameMacros;
21506 
21507   verifyFormat("STACK_OF(int) a;", Macros);
21508   verifyFormat("STACK_OF(int) *a;", Macros);
21509   verifyFormat("STACK_OF(int const *) *a;", Macros);
21510   verifyFormat("STACK_OF(int *const) *a;", Macros);
21511   verifyFormat("STACK_OF(int, string) a;", Macros);
21512   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
21513   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
21514   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
21515   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
21516   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
21517   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
21518 
21519   Macros.PointerAlignment = FormatStyle::PAS_Left;
21520   verifyFormat("STACK_OF(int)* a;", Macros);
21521   verifyFormat("STACK_OF(int*)* a;", Macros);
21522   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
21523   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
21524   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
21525 }
21526 
TEST_F(FormatTest,AtomicQualifier)21527 TEST_F(FormatTest, AtomicQualifier) {
21528   // Check that we treate _Atomic as a type and not a function call
21529   FormatStyle Google = getGoogleStyleWithColumns(0);
21530   verifyFormat("struct foo {\n"
21531                "  int a1;\n"
21532                "  _Atomic(a) a2;\n"
21533                "  _Atomic(_Atomic(int) *const) a3;\n"
21534                "};",
21535                Google);
21536   verifyFormat("_Atomic(uint64_t) a;");
21537   verifyFormat("_Atomic(uint64_t) *a;");
21538   verifyFormat("_Atomic(uint64_t const *) *a;");
21539   verifyFormat("_Atomic(uint64_t *const) *a;");
21540   verifyFormat("_Atomic(const uint64_t *) *a;");
21541   verifyFormat("_Atomic(uint64_t) a;");
21542   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
21543   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
21544   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
21545   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
21546 
21547   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
21548   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
21549   FormatStyle Style = getLLVMStyle();
21550   Style.PointerAlignment = FormatStyle::PAS_Left;
21551   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
21552   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
21553   verifyFormat("_Atomic(int)* a;", Style);
21554   verifyFormat("_Atomic(int*)* a;", Style);
21555   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
21556 
21557   Style.SpacesInCStyleCastParentheses = true;
21558   Style.SpacesInParentheses = false;
21559   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
21560   Style.SpacesInCStyleCastParentheses = false;
21561   Style.SpacesInParentheses = true;
21562   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
21563   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
21564 }
21565 
TEST_F(FormatTest,AmbersandInLamda)21566 TEST_F(FormatTest, AmbersandInLamda) {
21567   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
21568   FormatStyle AlignStyle = getLLVMStyle();
21569   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
21570   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
21571   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
21572   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
21573 }
21574 
TEST_F(FormatTest,SpacesInConditionalStatement)21575 TEST_F(FormatTest, SpacesInConditionalStatement) {
21576   FormatStyle Spaces = getLLVMStyle();
21577   Spaces.IfMacros.clear();
21578   Spaces.IfMacros.push_back("MYIF");
21579   Spaces.SpacesInConditionalStatement = true;
21580   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
21581   verifyFormat("if ( !a )\n  return;", Spaces);
21582   verifyFormat("if ( a )\n  return;", Spaces);
21583   verifyFormat("if constexpr ( a )\n  return;", Spaces);
21584   verifyFormat("MYIF ( a )\n  return;", Spaces);
21585   verifyFormat("MYIF ( a )\n  return;\nelse MYIF ( b )\n  return;", Spaces);
21586   verifyFormat("MYIF ( a )\n  return;\nelse\n  return;", Spaces);
21587   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
21588   verifyFormat("while ( a )\n  return;", Spaces);
21589   verifyFormat("while ( (a && b) )\n  return;", Spaces);
21590   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
21591   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
21592   // Check that space on the left of "::" is inserted as expected at beginning
21593   // of condition.
21594   verifyFormat("while ( ::func() )\n  return;", Spaces);
21595 
21596   // Check impact of ControlStatementsExceptControlMacros is honored.
21597   Spaces.SpaceBeforeParens =
21598       FormatStyle::SBPO_ControlStatementsExceptControlMacros;
21599   verifyFormat("MYIF( a )\n  return;", Spaces);
21600   verifyFormat("MYIF( a )\n  return;\nelse MYIF( b )\n  return;", Spaces);
21601   verifyFormat("MYIF( a )\n  return;\nelse\n  return;", Spaces);
21602 }
21603 
TEST_F(FormatTest,AlternativeOperators)21604 TEST_F(FormatTest, AlternativeOperators) {
21605   // Test case for ensuring alternate operators are not
21606   // combined with their right most neighbour.
21607   verifyFormat("int a and b;");
21608   verifyFormat("int a and_eq b;");
21609   verifyFormat("int a bitand b;");
21610   verifyFormat("int a bitor b;");
21611   verifyFormat("int a compl b;");
21612   verifyFormat("int a not b;");
21613   verifyFormat("int a not_eq b;");
21614   verifyFormat("int a or b;");
21615   verifyFormat("int a xor b;");
21616   verifyFormat("int a xor_eq b;");
21617   verifyFormat("return this not_eq bitand other;");
21618   verifyFormat("bool operator not_eq(const X bitand other)");
21619 
21620   verifyFormat("int a and 5;");
21621   verifyFormat("int a and_eq 5;");
21622   verifyFormat("int a bitand 5;");
21623   verifyFormat("int a bitor 5;");
21624   verifyFormat("int a compl 5;");
21625   verifyFormat("int a not 5;");
21626   verifyFormat("int a not_eq 5;");
21627   verifyFormat("int a or 5;");
21628   verifyFormat("int a xor 5;");
21629   verifyFormat("int a xor_eq 5;");
21630 
21631   verifyFormat("int a compl(5);");
21632   verifyFormat("int a not(5);");
21633 
21634   /* FIXME handle alternate tokens
21635    * https://en.cppreference.com/w/cpp/language/operator_alternative
21636   // alternative tokens
21637   verifyFormat("compl foo();");     //  ~foo();
21638   verifyFormat("foo() <%%>;");      // foo();
21639   verifyFormat("void foo() <%%>;"); // void foo(){}
21640   verifyFormat("int a <:1:>;");     // int a[1];[
21641   verifyFormat("%:define ABC abc"); // #define ABC abc
21642   verifyFormat("%:%:");             // ##
21643   */
21644 }
21645 
TEST_F(FormatTest,STLWhileNotDefineChed)21646 TEST_F(FormatTest, STLWhileNotDefineChed) {
21647   verifyFormat("#if defined(while)\n"
21648                "#define while EMIT WARNING C4005\n"
21649                "#endif // while");
21650 }
21651 
TEST_F(FormatTest,OperatorSpacing)21652 TEST_F(FormatTest, OperatorSpacing) {
21653   FormatStyle Style = getLLVMStyle();
21654   Style.PointerAlignment = FormatStyle::PAS_Right;
21655   verifyFormat("Foo::operator*();", Style);
21656   verifyFormat("Foo::operator void *();", Style);
21657   verifyFormat("Foo::operator void **();", Style);
21658   verifyFormat("Foo::operator void *&();", Style);
21659   verifyFormat("Foo::operator void *&&();", Style);
21660   verifyFormat("Foo::operator void const *();", Style);
21661   verifyFormat("Foo::operator void const **();", Style);
21662   verifyFormat("Foo::operator void const *&();", Style);
21663   verifyFormat("Foo::operator void const *&&();", Style);
21664   verifyFormat("Foo::operator()(void *);", Style);
21665   verifyFormat("Foo::operator*(void *);", Style);
21666   verifyFormat("Foo::operator*();", Style);
21667   verifyFormat("Foo::operator**();", Style);
21668   verifyFormat("Foo::operator&();", Style);
21669   verifyFormat("Foo::operator<int> *();", Style);
21670   verifyFormat("Foo::operator<Foo> *();", Style);
21671   verifyFormat("Foo::operator<int> **();", Style);
21672   verifyFormat("Foo::operator<Foo> **();", Style);
21673   verifyFormat("Foo::operator<int> &();", Style);
21674   verifyFormat("Foo::operator<Foo> &();", Style);
21675   verifyFormat("Foo::operator<int> &&();", Style);
21676   verifyFormat("Foo::operator<Foo> &&();", Style);
21677   verifyFormat("Foo::operator<int> *&();", Style);
21678   verifyFormat("Foo::operator<Foo> *&();", Style);
21679   verifyFormat("Foo::operator<int> *&&();", Style);
21680   verifyFormat("Foo::operator<Foo> *&&();", Style);
21681   verifyFormat("operator*(int (*)(), class Foo);", Style);
21682 
21683   verifyFormat("Foo::operator&();", Style);
21684   verifyFormat("Foo::operator void &();", Style);
21685   verifyFormat("Foo::operator void const &();", Style);
21686   verifyFormat("Foo::operator()(void &);", Style);
21687   verifyFormat("Foo::operator&(void &);", Style);
21688   verifyFormat("Foo::operator&();", Style);
21689   verifyFormat("operator&(int (&)(), class Foo);", Style);
21690 
21691   verifyFormat("Foo::operator&&();", Style);
21692   verifyFormat("Foo::operator**();", Style);
21693   verifyFormat("Foo::operator void &&();", Style);
21694   verifyFormat("Foo::operator void const &&();", Style);
21695   verifyFormat("Foo::operator()(void &&);", Style);
21696   verifyFormat("Foo::operator&&(void &&);", Style);
21697   verifyFormat("Foo::operator&&();", Style);
21698   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
21699   verifyFormat("operator const nsTArrayRight<E> &()", Style);
21700   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
21701                Style);
21702   verifyFormat("operator void **()", Style);
21703   verifyFormat("operator const FooRight<Object> &()", Style);
21704   verifyFormat("operator const FooRight<Object> *()", Style);
21705   verifyFormat("operator const FooRight<Object> **()", Style);
21706   verifyFormat("operator const FooRight<Object> *&()", Style);
21707   verifyFormat("operator const FooRight<Object> *&&()", Style);
21708 
21709   Style.PointerAlignment = FormatStyle::PAS_Left;
21710   verifyFormat("Foo::operator*();", Style);
21711   verifyFormat("Foo::operator**();", Style);
21712   verifyFormat("Foo::operator void*();", Style);
21713   verifyFormat("Foo::operator void**();", Style);
21714   verifyFormat("Foo::operator void*&();", Style);
21715   verifyFormat("Foo::operator void*&&();", Style);
21716   verifyFormat("Foo::operator void const*();", Style);
21717   verifyFormat("Foo::operator void const**();", Style);
21718   verifyFormat("Foo::operator void const*&();", Style);
21719   verifyFormat("Foo::operator void const*&&();", Style);
21720   verifyFormat("Foo::operator/*comment*/ void*();", Style);
21721   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
21722   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
21723   verifyFormat("Foo::operator()(void*);", Style);
21724   verifyFormat("Foo::operator*(void*);", Style);
21725   verifyFormat("Foo::operator*();", Style);
21726   verifyFormat("Foo::operator<int>*();", Style);
21727   verifyFormat("Foo::operator<Foo>*();", Style);
21728   verifyFormat("Foo::operator<int>**();", Style);
21729   verifyFormat("Foo::operator<Foo>**();", Style);
21730   verifyFormat("Foo::operator<Foo>*&();", Style);
21731   verifyFormat("Foo::operator<int>&();", Style);
21732   verifyFormat("Foo::operator<Foo>&();", Style);
21733   verifyFormat("Foo::operator<int>&&();", Style);
21734   verifyFormat("Foo::operator<Foo>&&();", Style);
21735   verifyFormat("Foo::operator<int>*&();", Style);
21736   verifyFormat("Foo::operator<Foo>*&();", Style);
21737   verifyFormat("operator*(int (*)(), class Foo);", Style);
21738 
21739   verifyFormat("Foo::operator&();", Style);
21740   verifyFormat("Foo::operator void&();", Style);
21741   verifyFormat("Foo::operator void const&();", Style);
21742   verifyFormat("Foo::operator/*comment*/ void&();", Style);
21743   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
21744   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
21745   verifyFormat("Foo::operator()(void&);", Style);
21746   verifyFormat("Foo::operator&(void&);", Style);
21747   verifyFormat("Foo::operator&();", Style);
21748   verifyFormat("operator&(int (&)(), class Foo);", Style);
21749 
21750   verifyFormat("Foo::operator&&();", Style);
21751   verifyFormat("Foo::operator void&&();", Style);
21752   verifyFormat("Foo::operator void const&&();", Style);
21753   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
21754   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
21755   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
21756   verifyFormat("Foo::operator()(void&&);", Style);
21757   verifyFormat("Foo::operator&&(void&&);", Style);
21758   verifyFormat("Foo::operator&&();", Style);
21759   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
21760   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
21761   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
21762                Style);
21763   verifyFormat("operator void**()", Style);
21764   verifyFormat("operator const FooLeft<Object>&()", Style);
21765   verifyFormat("operator const FooLeft<Object>*()", Style);
21766   verifyFormat("operator const FooLeft<Object>**()", Style);
21767   verifyFormat("operator const FooLeft<Object>*&()", Style);
21768   verifyFormat("operator const FooLeft<Object>*&&()", Style);
21769 
21770   // PR45107
21771   verifyFormat("operator Vector<String>&();", Style);
21772   verifyFormat("operator const Vector<String>&();", Style);
21773   verifyFormat("operator foo::Bar*();", Style);
21774   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
21775   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
21776                Style);
21777 
21778   Style.PointerAlignment = FormatStyle::PAS_Middle;
21779   verifyFormat("Foo::operator*();", Style);
21780   verifyFormat("Foo::operator void *();", Style);
21781   verifyFormat("Foo::operator()(void *);", Style);
21782   verifyFormat("Foo::operator*(void *);", Style);
21783   verifyFormat("Foo::operator*();", Style);
21784   verifyFormat("operator*(int (*)(), class Foo);", Style);
21785 
21786   verifyFormat("Foo::operator&();", Style);
21787   verifyFormat("Foo::operator void &();", Style);
21788   verifyFormat("Foo::operator void const &();", Style);
21789   verifyFormat("Foo::operator()(void &);", Style);
21790   verifyFormat("Foo::operator&(void &);", Style);
21791   verifyFormat("Foo::operator&();", Style);
21792   verifyFormat("operator&(int (&)(), class Foo);", Style);
21793 
21794   verifyFormat("Foo::operator&&();", Style);
21795   verifyFormat("Foo::operator void &&();", Style);
21796   verifyFormat("Foo::operator void const &&();", Style);
21797   verifyFormat("Foo::operator()(void &&);", Style);
21798   verifyFormat("Foo::operator&&(void &&);", Style);
21799   verifyFormat("Foo::operator&&();", Style);
21800   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
21801 }
21802 
TEST_F(FormatTest,OperatorPassedAsAFunctionPtr)21803 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
21804   FormatStyle Style = getLLVMStyle();
21805   // PR46157
21806   verifyFormat("foo(operator+, -42);", Style);
21807   verifyFormat("foo(operator++, -42);", Style);
21808   verifyFormat("foo(operator--, -42);", Style);
21809   verifyFormat("foo(-42, operator--);", Style);
21810   verifyFormat("foo(-42, operator, );", Style);
21811   verifyFormat("foo(operator, , -42);", Style);
21812 }
21813 
TEST_F(FormatTest,WhitespaceSensitiveMacros)21814 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
21815   FormatStyle Style = getLLVMStyle();
21816   Style.WhitespaceSensitiveMacros.push_back("FOO");
21817 
21818   // Don't use the helpers here, since 'mess up' will change the whitespace
21819   // and these are all whitespace sensitive by definition
21820   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
21821             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
21822   EXPECT_EQ(
21823       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
21824       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
21825   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
21826             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
21827   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
21828             "       Still=Intentional);",
21829             format("FOO(String-ized&Messy+But,: :\n"
21830                    "       Still=Intentional);",
21831                    Style));
21832   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
21833   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
21834             "       Still=Intentional);",
21835             format("FOO(String-ized=&Messy+But,: :\n"
21836                    "       Still=Intentional);",
21837                    Style));
21838 
21839   Style.ColumnLimit = 21;
21840   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
21841             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
21842 }
21843 
TEST_F(FormatTest,VeryLongNamespaceCommentSplit)21844 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
21845   // These tests are not in NamespaceFixer because that doesn't
21846   // test its interaction with line wrapping
21847   FormatStyle Style = getLLVMStyle();
21848   Style.ColumnLimit = 80;
21849   verifyFormat("namespace {\n"
21850                "int i;\n"
21851                "int j;\n"
21852                "} // namespace",
21853                Style);
21854 
21855   verifyFormat("namespace AAA {\n"
21856                "int i;\n"
21857                "int j;\n"
21858                "} // namespace AAA",
21859                Style);
21860 
21861   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
21862             "int i;\n"
21863             "int j;\n"
21864             "} // namespace Averyveryveryverylongnamespace",
21865             format("namespace Averyveryveryverylongnamespace {\n"
21866                    "int i;\n"
21867                    "int j;\n"
21868                    "}",
21869                    Style));
21870 
21871   EXPECT_EQ(
21872       "namespace "
21873       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
21874       "    went::mad::now {\n"
21875       "int i;\n"
21876       "int j;\n"
21877       "} // namespace\n"
21878       "  // "
21879       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
21880       "went::mad::now",
21881       format("namespace "
21882              "would::it::save::you::a::lot::of::time::if_::i::"
21883              "just::gave::up::and_::went::mad::now {\n"
21884              "int i;\n"
21885              "int j;\n"
21886              "}",
21887              Style));
21888 
21889   // This used to duplicate the comment again and again on subsequent runs
21890   EXPECT_EQ(
21891       "namespace "
21892       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
21893       "    went::mad::now {\n"
21894       "int i;\n"
21895       "int j;\n"
21896       "} // namespace\n"
21897       "  // "
21898       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
21899       "went::mad::now",
21900       format("namespace "
21901              "would::it::save::you::a::lot::of::time::if_::i::"
21902              "just::gave::up::and_::went::mad::now {\n"
21903              "int i;\n"
21904              "int j;\n"
21905              "} // namespace\n"
21906              "  // "
21907              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
21908              "and_::went::mad::now",
21909              Style));
21910 }
21911 
TEST_F(FormatTest,LikelyUnlikely)21912 TEST_F(FormatTest, LikelyUnlikely) {
21913   FormatStyle Style = getLLVMStyle();
21914 
21915   verifyFormat("if (argc > 5) [[unlikely]] {\n"
21916                "  return 29;\n"
21917                "}",
21918                Style);
21919 
21920   verifyFormat("if (argc > 5) [[likely]] {\n"
21921                "  return 29;\n"
21922                "}",
21923                Style);
21924 
21925   verifyFormat("if (argc > 5) [[unlikely]] {\n"
21926                "  return 29;\n"
21927                "} else [[likely]] {\n"
21928                "  return 42;\n"
21929                "}\n",
21930                Style);
21931 
21932   verifyFormat("if (argc > 5) [[unlikely]] {\n"
21933                "  return 29;\n"
21934                "} else if (argc > 10) [[likely]] {\n"
21935                "  return 99;\n"
21936                "} else {\n"
21937                "  return 42;\n"
21938                "}\n",
21939                Style);
21940 
21941   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
21942                "  return 29;\n"
21943                "}",
21944                Style);
21945 }
21946 
TEST_F(FormatTest,PenaltyIndentedWhitespace)21947 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
21948   verifyFormat("Constructor()\n"
21949                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21950                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
21951                "aaaaaaaaaaaaaaaaaat))");
21952   verifyFormat("Constructor()\n"
21953                "    : aaaaaaaaaaaaa(aaaaaa), "
21954                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
21955 
21956   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
21957   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
21958   verifyFormat("Constructor()\n"
21959                "    : aaaaaa(aaaaaa),\n"
21960                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
21961                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
21962                StyleWithWhitespacePenalty);
21963   verifyFormat("Constructor()\n"
21964                "    : aaaaaaaaaaaaa(aaaaaa), "
21965                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
21966                StyleWithWhitespacePenalty);
21967 }
21968 
TEST_F(FormatTest,LLVMDefaultStyle)21969 TEST_F(FormatTest, LLVMDefaultStyle) {
21970   FormatStyle Style = getLLVMStyle();
21971   verifyFormat("extern \"C\" {\n"
21972                "int foo();\n"
21973                "}",
21974                Style);
21975 }
TEST_F(FormatTest,GNUDefaultStyle)21976 TEST_F(FormatTest, GNUDefaultStyle) {
21977   FormatStyle Style = getGNUStyle();
21978   verifyFormat("extern \"C\"\n"
21979                "{\n"
21980                "  int foo ();\n"
21981                "}",
21982                Style);
21983 }
TEST_F(FormatTest,MozillaDefaultStyle)21984 TEST_F(FormatTest, MozillaDefaultStyle) {
21985   FormatStyle Style = getMozillaStyle();
21986   verifyFormat("extern \"C\"\n"
21987                "{\n"
21988                "  int foo();\n"
21989                "}",
21990                Style);
21991 }
TEST_F(FormatTest,GoogleDefaultStyle)21992 TEST_F(FormatTest, GoogleDefaultStyle) {
21993   FormatStyle Style = getGoogleStyle();
21994   verifyFormat("extern \"C\" {\n"
21995                "int foo();\n"
21996                "}",
21997                Style);
21998 }
TEST_F(FormatTest,ChromiumDefaultStyle)21999 TEST_F(FormatTest, ChromiumDefaultStyle) {
22000   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
22001   verifyFormat("extern \"C\" {\n"
22002                "int foo();\n"
22003                "}",
22004                Style);
22005 }
TEST_F(FormatTest,MicrosoftDefaultStyle)22006 TEST_F(FormatTest, MicrosoftDefaultStyle) {
22007   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
22008   verifyFormat("extern \"C\"\n"
22009                "{\n"
22010                "    int foo();\n"
22011                "}",
22012                Style);
22013 }
TEST_F(FormatTest,WebKitDefaultStyle)22014 TEST_F(FormatTest, WebKitDefaultStyle) {
22015   FormatStyle Style = getWebKitStyle();
22016   verifyFormat("extern \"C\" {\n"
22017                "int foo();\n"
22018                "}",
22019                Style);
22020 }
22021 
TEST_F(FormatTest,ConceptsAndRequires)22022 TEST_F(FormatTest, ConceptsAndRequires) {
22023   FormatStyle Style = getLLVMStyle();
22024   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
22025 
22026   verifyFormat("template <typename T>\n"
22027                "concept Hashable = requires(T a) {\n"
22028                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
22029                "};",
22030                Style);
22031   verifyFormat("template <typename T>\n"
22032                "concept EqualityComparable = requires(T a, T b) {\n"
22033                "  { a == b } -> bool;\n"
22034                "};",
22035                Style);
22036   verifyFormat("template <typename T>\n"
22037                "concept EqualityComparable = requires(T a, T b) {\n"
22038                "  { a == b } -> bool;\n"
22039                "  { a != b } -> bool;\n"
22040                "};",
22041                Style);
22042   verifyFormat("template <typename T>\n"
22043                "concept EqualityComparable = requires(T a, T b) {\n"
22044                "  { a == b } -> bool;\n"
22045                "  { a != b } -> bool;\n"
22046                "};",
22047                Style);
22048 
22049   verifyFormat("template <typename It>\n"
22050                "requires Iterator<It>\n"
22051                "void sort(It begin, It end) {\n"
22052                "  //....\n"
22053                "}",
22054                Style);
22055 
22056   verifyFormat("template <typename T>\n"
22057                "concept Large = sizeof(T) > 10;",
22058                Style);
22059 
22060   verifyFormat("template <typename T, typename U>\n"
22061                "concept FooableWith = requires(T t, U u) {\n"
22062                "  typename T::foo_type;\n"
22063                "  { t.foo(u) } -> typename T::foo_type;\n"
22064                "  t++;\n"
22065                "};\n"
22066                "void doFoo(FooableWith<int> auto t) {\n"
22067                "  t.foo(3);\n"
22068                "}",
22069                Style);
22070   verifyFormat("template <typename T>\n"
22071                "concept Context = sizeof(T) == 1;",
22072                Style);
22073   verifyFormat("template <typename T>\n"
22074                "concept Context = is_specialization_of_v<context, T>;",
22075                Style);
22076   verifyFormat("template <typename T>\n"
22077                "concept Node = std::is_object_v<T>;",
22078                Style);
22079   verifyFormat("template <typename T>\n"
22080                "concept Tree = true;",
22081                Style);
22082 
22083   verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
22084                "  //...\n"
22085                "}",
22086                Style);
22087 
22088   verifyFormat(
22089       "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
22090       "  //...\n"
22091       "}",
22092       Style);
22093 
22094   verifyFormat(
22095       "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
22096       "  //...\n"
22097       "}",
22098       Style);
22099 
22100   verifyFormat("template <typename T>\n"
22101                "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
22102                "Concept2<I> {\n"
22103                "  //...\n"
22104                "}",
22105                Style);
22106 
22107   verifyFormat("template <typename T>\n"
22108                "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
22109                "Concept2<I> {\n"
22110                "  //...\n"
22111                "}",
22112                Style);
22113 
22114   verifyFormat(
22115       "template <typename T>\n"
22116       "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
22117       "  //...\n"
22118       "}",
22119       Style);
22120 
22121   verifyFormat(
22122       "template <typename T>\n"
22123       "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
22124       "  //...\n"
22125       "}",
22126       Style);
22127 
22128   verifyFormat("template <typename It>\n"
22129                "requires Foo<It>() && Bar<It> {\n"
22130                "  //....\n"
22131                "}",
22132                Style);
22133 
22134   verifyFormat("template <typename It>\n"
22135                "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
22136                "  //....\n"
22137                "}",
22138                Style);
22139 
22140   verifyFormat("template <typename It>\n"
22141                "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
22142                "  //....\n"
22143                "}",
22144                Style);
22145 
22146   verifyFormat(
22147       "template <typename It>\n"
22148       "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
22149       "  //....\n"
22150       "}",
22151       Style);
22152 
22153   Style.IndentRequires = true;
22154   verifyFormat("template <typename It>\n"
22155                "  requires Iterator<It>\n"
22156                "void sort(It begin, It end) {\n"
22157                "  //....\n"
22158                "}",
22159                Style);
22160   verifyFormat("template <std::size index_>\n"
22161                "  requires(index_ < sizeof...(Children_))\n"
22162                "Tree auto &child() {\n"
22163                "  // ...\n"
22164                "}",
22165                Style);
22166 
22167   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
22168   verifyFormat("template <typename T>\n"
22169                "concept Hashable = requires (T a) {\n"
22170                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
22171                "};",
22172                Style);
22173 
22174   verifyFormat("template <class T = void>\n"
22175                "  requires EqualityComparable<T> || Same<T, void>\n"
22176                "struct equal_to;",
22177                Style);
22178 
22179   verifyFormat("template <class T>\n"
22180                "  requires requires {\n"
22181                "    T{};\n"
22182                "    T (int);\n"
22183                "  }\n",
22184                Style);
22185 
22186   Style.ColumnLimit = 78;
22187   verifyFormat("template <typename T>\n"
22188                "concept Context = Traits<typename T::traits_type> and\n"
22189                "    Interface<typename T::interface_type> and\n"
22190                "    Request<typename T::request_type> and\n"
22191                "    Response<typename T::response_type> and\n"
22192                "    ContextExtension<typename T::extension_type> and\n"
22193                "    ::std::is_copy_constructable<T> and "
22194                "::std::is_move_constructable<T> and\n"
22195                "    requires (T c) {\n"
22196                "  { c.response; } -> Response;\n"
22197                "} and requires (T c) {\n"
22198                "  { c.request; } -> Request;\n"
22199                "}\n",
22200                Style);
22201 
22202   verifyFormat("template <typename T>\n"
22203                "concept Context = Traits<typename T::traits_type> or\n"
22204                "    Interface<typename T::interface_type> or\n"
22205                "    Request<typename T::request_type> or\n"
22206                "    Response<typename T::response_type> or\n"
22207                "    ContextExtension<typename T::extension_type> or\n"
22208                "    ::std::is_copy_constructable<T> or "
22209                "::std::is_move_constructable<T> or\n"
22210                "    requires (T c) {\n"
22211                "  { c.response; } -> Response;\n"
22212                "} or requires (T c) {\n"
22213                "  { c.request; } -> Request;\n"
22214                "}\n",
22215                Style);
22216 
22217   verifyFormat("template <typename T>\n"
22218                "concept Context = Traits<typename T::traits_type> &&\n"
22219                "    Interface<typename T::interface_type> &&\n"
22220                "    Request<typename T::request_type> &&\n"
22221                "    Response<typename T::response_type> &&\n"
22222                "    ContextExtension<typename T::extension_type> &&\n"
22223                "    ::std::is_copy_constructable<T> && "
22224                "::std::is_move_constructable<T> &&\n"
22225                "    requires (T c) {\n"
22226                "  { c.response; } -> Response;\n"
22227                "} && requires (T c) {\n"
22228                "  { c.request; } -> Request;\n"
22229                "}\n",
22230                Style);
22231 
22232   verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
22233                "Constraint2<T>;");
22234 
22235   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
22236   Style.BraceWrapping.AfterFunction = true;
22237   Style.BraceWrapping.AfterClass = true;
22238   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
22239   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
22240   verifyFormat("void Foo () requires (std::copyable<T>)\n"
22241                "{\n"
22242                "  return\n"
22243                "}\n",
22244                Style);
22245 
22246   verifyFormat("void Foo () requires std::copyable<T>\n"
22247                "{\n"
22248                "  return\n"
22249                "}\n",
22250                Style);
22251 
22252   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22253                "  requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
22254                "struct constant;",
22255                Style);
22256 
22257   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22258                "  requires std::invocable<F, std::invoke_result_t<Args>...>\n"
22259                "struct constant;",
22260                Style);
22261 
22262   verifyFormat("template <class T>\n"
22263                "class plane_with_very_very_very_long_name\n"
22264                "{\n"
22265                "  constexpr plane_with_very_very_very_long_name () requires "
22266                "std::copyable<T>\n"
22267                "      : plane_with_very_very_very_long_name (1)\n"
22268                "  {\n"
22269                "  }\n"
22270                "}\n",
22271                Style);
22272 
22273   verifyFormat("template <class T>\n"
22274                "class plane_with_long_name\n"
22275                "{\n"
22276                "  constexpr plane_with_long_name () requires std::copyable<T>\n"
22277                "      : plane_with_long_name (1)\n"
22278                "  {\n"
22279                "  }\n"
22280                "}\n",
22281                Style);
22282 
22283   Style.BreakBeforeConceptDeclarations = false;
22284   verifyFormat("template <typename T> concept Tree = true;", Style);
22285 
22286   Style.IndentRequires = false;
22287   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
22288                "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
22289                "struct constant;",
22290                Style);
22291 }
22292 
TEST_F(FormatTest,StatementAttributeLikeMacros)22293 TEST_F(FormatTest, StatementAttributeLikeMacros) {
22294   FormatStyle Style = getLLVMStyle();
22295   StringRef Source = "void Foo::slot() {\n"
22296                      "  unsigned char MyChar = 'x';\n"
22297                      "  emit signal(MyChar);\n"
22298                      "  Q_EMIT signal(MyChar);\n"
22299                      "}";
22300 
22301   EXPECT_EQ(Source, format(Source, Style));
22302 
22303   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
22304   EXPECT_EQ("void Foo::slot() {\n"
22305             "  unsigned char MyChar = 'x';\n"
22306             "  emit          signal(MyChar);\n"
22307             "  Q_EMIT signal(MyChar);\n"
22308             "}",
22309             format(Source, Style));
22310 
22311   Style.StatementAttributeLikeMacros.push_back("emit");
22312   EXPECT_EQ(Source, format(Source, Style));
22313 
22314   Style.StatementAttributeLikeMacros = {};
22315   EXPECT_EQ("void Foo::slot() {\n"
22316             "  unsigned char MyChar = 'x';\n"
22317             "  emit          signal(MyChar);\n"
22318             "  Q_EMIT        signal(MyChar);\n"
22319             "}",
22320             format(Source, Style));
22321 }
22322 
TEST_F(FormatTest,IndentAccessModifiers)22323 TEST_F(FormatTest, IndentAccessModifiers) {
22324   FormatStyle Style = getLLVMStyle();
22325   Style.IndentAccessModifiers = true;
22326   // Members are *two* levels below the record;
22327   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
22328   verifyFormat("class C {\n"
22329                "    int i;\n"
22330                "};\n",
22331                Style);
22332   verifyFormat("union C {\n"
22333                "    int i;\n"
22334                "    unsigned u;\n"
22335                "};\n",
22336                Style);
22337   // Access modifiers should be indented one level below the record.
22338   verifyFormat("class C {\n"
22339                "  public:\n"
22340                "    int i;\n"
22341                "};\n",
22342                Style);
22343   verifyFormat("struct S {\n"
22344                "  private:\n"
22345                "    class C {\n"
22346                "        int j;\n"
22347                "\n"
22348                "      public:\n"
22349                "        C();\n"
22350                "    };\n"
22351                "\n"
22352                "  public:\n"
22353                "    int i;\n"
22354                "};\n",
22355                Style);
22356   // Enumerations are not records and should be unaffected.
22357   Style.AllowShortEnumsOnASingleLine = false;
22358   verifyFormat("enum class E {\n"
22359                "  A,\n"
22360                "  B\n"
22361                "};\n",
22362                Style);
22363   // Test with a different indentation width;
22364   // also proves that the result is Style.AccessModifierOffset agnostic.
22365   Style.IndentWidth = 3;
22366   verifyFormat("class C {\n"
22367                "   public:\n"
22368                "      int i;\n"
22369                "};\n",
22370                Style);
22371 }
22372 
TEST_F(FormatTest,LimitlessStringsAndComments)22373 TEST_F(FormatTest, LimitlessStringsAndComments) {
22374   auto Style = getLLVMStyleWithColumns(0);
22375   constexpr StringRef Code =
22376       "/**\n"
22377       " * This is a multiline comment with quite some long lines, at least for "
22378       "the LLVM Style.\n"
22379       " * We will redo this with strings and line comments. Just to  check if "
22380       "everything is working.\n"
22381       " */\n"
22382       "bool foo() {\n"
22383       "  /* Single line multi line comment. */\n"
22384       "  const std::string String = \"This is a multiline string with quite "
22385       "some long lines, at least for the LLVM Style.\"\n"
22386       "                             \"We already did it with multi line "
22387       "comments, and we will do it with line comments. Just to check if "
22388       "everything is working.\";\n"
22389       "  // This is a line comment (block) with quite some long lines, at "
22390       "least for the LLVM Style.\n"
22391       "  // We already did this with multi line comments and strings. Just to "
22392       "check if everything is working.\n"
22393       "  const std::string SmallString = \"Hello World\";\n"
22394       "  // Small line comment\n"
22395       "  return String.size() > SmallString.size();\n"
22396       "}";
22397   EXPECT_EQ(Code, format(Code, Style));
22398 }
22399 
22400 } // namespace
22401 } // namespace format
22402 } // namespace clang
22403