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::internal::ScopedTrace;
23 
24 namespace clang {
25 namespace format {
26 namespace {
27 
28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
29 
30 class FormatTest : public ::testing::Test {
31 protected:
32   enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck };
33 
34   std::string format(llvm::StringRef Code,
35                      const FormatStyle &Style = getLLVMStyle(),
36                      StatusCheck CheckComplete = SC_ExpectComplete) {
37     LLVM_DEBUG(llvm::errs() << "---\n");
38     LLVM_DEBUG(llvm::errs() << Code << "\n\n");
39     std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
40     FormattingAttemptStatus Status;
41     tooling::Replacements Replaces =
42         reformat(Style, Code, Ranges, "<stdin>", &Status);
43     if (CheckComplete != SC_DoNotCheck) {
44       bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete;
45       EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete)
46           << Code << "\n\n";
47     }
48     ReplacementCount = Replaces.size();
49     auto Result = applyAllReplacements(Code, Replaces);
50     EXPECT_TRUE(static_cast<bool>(Result));
51     LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
52     return *Result;
53   }
54 
55   FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) {
56     Style.ColumnLimit = ColumnLimit;
57     return Style;
58   }
59 
60   FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
61     return getStyleWithColumns(getLLVMStyle(), ColumnLimit);
62   }
63 
64   FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
65     return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
66   }
67 
68   void _verifyFormat(const char *File, int Line, llvm::StringRef Expected,
69                      llvm::StringRef Code,
70                      const FormatStyle &Style = getLLVMStyle()) {
71     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
72     EXPECT_EQ(Expected.str(), format(Expected, Style))
73         << "Expected code is not stable";
74     EXPECT_EQ(Expected.str(), format(Code, Style));
75     if (Style.Language == FormatStyle::LK_Cpp) {
76       // Objective-C++ is a superset of C++, so everything checked for C++
77       // needs to be checked for Objective-C++ as well.
78       FormatStyle ObjCStyle = Style;
79       ObjCStyle.Language = FormatStyle::LK_ObjC;
80       EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle));
81     }
82   }
83 
84   void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
85                      const FormatStyle &Style = getLLVMStyle()) {
86     _verifyFormat(File, Line, Code, test::messUp(Code), Style);
87   }
88 
89   void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code,
90                                const FormatStyle &Style = getLLVMStyle()) {
91     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
92     EXPECT_EQ(Code.str(),
93               format(test::messUp(Code), Style, SC_ExpectIncomplete));
94   }
95 
96   void _verifyIndependentOfContext(const char *File, int Line,
97                                    llvm::StringRef Text,
98                                    const FormatStyle &Style = getLLVMStyle()) {
99     _verifyFormat(File, Line, Text, Style);
100     _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(),
101                   Style);
102   }
103 
104   /// \brief Verify that clang-format does not crash on the given input.
105   void verifyNoCrash(llvm::StringRef Code,
106                      const FormatStyle &Style = getLLVMStyle()) {
107     format(Code, Style, SC_DoNotCheck);
108   }
109 
110   int ReplacementCount;
111 };
112 
113 #define verifyIndependentOfContext(...)                                        \
114   _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__)
115 #define verifyIncompleteFormat(...)                                            \
116   _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle())
119 
120 TEST_F(FormatTest, MessUp) {
121   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
122   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
123   EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
124   EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
125   EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
126 }
127 
128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
129   EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
130 }
131 
132 TEST_F(FormatTest, LLVMStyleOverride) {
133   EXPECT_EQ(FormatStyle::LK_Proto,
134             getLLVMStyle(FormatStyle::LK_Proto).Language);
135 }
136 
137 //===----------------------------------------------------------------------===//
138 // Basic function tests.
139 //===----------------------------------------------------------------------===//
140 
141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
142   EXPECT_EQ(";", format(";"));
143 }
144 
145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
146   EXPECT_EQ("int i;", format("  int i;"));
147   EXPECT_EQ("\nint i;", format(" \n\t \v \f  int i;"));
148   EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
149   EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
150 }
151 
152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
153   EXPECT_EQ("int i;", format("int\ni;"));
154 }
155 
156 TEST_F(FormatTest, FormatsNestedBlockStatements) {
157   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
158 }
159 
160 TEST_F(FormatTest, FormatsNestedCall) {
161   verifyFormat("Method(f1, f2(f3));");
162   verifyFormat("Method(f1(f2, f3()));");
163   verifyFormat("Method(f1(f2, (f3())));");
164 }
165 
166 TEST_F(FormatTest, NestedNameSpecifiers) {
167   verifyFormat("vector<::Type> v;");
168   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
169   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
170   verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
171   verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
172   verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
173   verifyFormat("bool a = 2 < ::SomeFunction();");
174   verifyFormat("ALWAYS_INLINE ::std::string getName();");
175   verifyFormat("some::string getName();");
176 }
177 
178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
179   EXPECT_EQ("if (a) {\n"
180             "  f();\n"
181             "}",
182             format("if(a){f();}"));
183   EXPECT_EQ(4, ReplacementCount);
184   EXPECT_EQ("if (a) {\n"
185             "  f();\n"
186             "}",
187             format("if (a) {\n"
188                    "  f();\n"
189                    "}"));
190   EXPECT_EQ(0, ReplacementCount);
191   EXPECT_EQ("/*\r\n"
192             "\r\n"
193             "*/\r\n",
194             format("/*\r\n"
195                    "\r\n"
196                    "*/\r\n"));
197   EXPECT_EQ(0, ReplacementCount);
198 }
199 
200 TEST_F(FormatTest, RemovesEmptyLines) {
201   EXPECT_EQ("class C {\n"
202             "  int i;\n"
203             "};",
204             format("class C {\n"
205                    " int i;\n"
206                    "\n"
207                    "};"));
208 
209   // Don't remove empty lines at the start of namespaces or extern "C" blocks.
210   EXPECT_EQ("namespace N {\n"
211             "\n"
212             "int i;\n"
213             "}",
214             format("namespace N {\n"
215                    "\n"
216                    "int    i;\n"
217                    "}",
218                    getGoogleStyle()));
219   EXPECT_EQ("/* something */ namespace N {\n"
220             "\n"
221             "int i;\n"
222             "}",
223             format("/* something */ namespace N {\n"
224                    "\n"
225                    "int    i;\n"
226                    "}",
227                    getGoogleStyle()));
228   EXPECT_EQ("inline namespace N {\n"
229             "\n"
230             "int i;\n"
231             "}",
232             format("inline namespace N {\n"
233                    "\n"
234                    "int    i;\n"
235                    "}",
236                    getGoogleStyle()));
237   EXPECT_EQ("/* something */ inline namespace N {\n"
238             "\n"
239             "int i;\n"
240             "}",
241             format("/* something */ inline namespace N {\n"
242                    "\n"
243                    "int    i;\n"
244                    "}",
245                    getGoogleStyle()));
246   EXPECT_EQ("export namespace N {\n"
247             "\n"
248             "int i;\n"
249             "}",
250             format("export namespace N {\n"
251                    "\n"
252                    "int    i;\n"
253                    "}",
254                    getGoogleStyle()));
255   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
256             "\n"
257             "int i;\n"
258             "}",
259             format("extern /**/ \"C\" /**/ {\n"
260                    "\n"
261                    "int    i;\n"
262                    "}",
263                    getGoogleStyle()));
264 
265   // ...but do keep inlining and removing empty lines for non-block extern "C"
266   // functions.
267   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
268   EXPECT_EQ("extern \"C\" int f() {\n"
269             "  int i = 42;\n"
270             "  return i;\n"
271             "}",
272             format("extern \"C\" int f() {\n"
273                    "\n"
274                    "  int i = 42;\n"
275                    "  return i;\n"
276                    "}",
277                    getGoogleStyle()));
278 
279   // Remove empty lines at the beginning and end of blocks.
280   EXPECT_EQ("void f() {\n"
281             "\n"
282             "  if (a) {\n"
283             "\n"
284             "    f();\n"
285             "  }\n"
286             "}",
287             format("void f() {\n"
288                    "\n"
289                    "  if (a) {\n"
290                    "\n"
291                    "    f();\n"
292                    "\n"
293                    "  }\n"
294                    "\n"
295                    "}",
296                    getLLVMStyle()));
297   EXPECT_EQ("void f() {\n"
298             "  if (a) {\n"
299             "    f();\n"
300             "  }\n"
301             "}",
302             format("void f() {\n"
303                    "\n"
304                    "  if (a) {\n"
305                    "\n"
306                    "    f();\n"
307                    "\n"
308                    "  }\n"
309                    "\n"
310                    "}",
311                    getGoogleStyle()));
312 
313   // Don't remove empty lines in more complex control statements.
314   EXPECT_EQ("void f() {\n"
315             "  if (a) {\n"
316             "    f();\n"
317             "\n"
318             "  } else if (b) {\n"
319             "    f();\n"
320             "  }\n"
321             "}",
322             format("void f() {\n"
323                    "  if (a) {\n"
324                    "    f();\n"
325                    "\n"
326                    "  } else if (b) {\n"
327                    "    f();\n"
328                    "\n"
329                    "  }\n"
330                    "\n"
331                    "}"));
332 
333   // Don't remove empty lines before namespace endings.
334   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
335   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
336   EXPECT_EQ("namespace {\n"
337             "int i;\n"
338             "\n"
339             "}",
340             format("namespace {\n"
341                    "int i;\n"
342                    "\n"
343                    "}",
344                    LLVMWithNoNamespaceFix));
345   EXPECT_EQ("namespace {\n"
346             "int i;\n"
347             "}",
348             format("namespace {\n"
349                    "int i;\n"
350                    "}",
351                    LLVMWithNoNamespaceFix));
352   EXPECT_EQ("namespace {\n"
353             "int i;\n"
354             "\n"
355             "};",
356             format("namespace {\n"
357                    "int i;\n"
358                    "\n"
359                    "};",
360                    LLVMWithNoNamespaceFix));
361   EXPECT_EQ("namespace {\n"
362             "int i;\n"
363             "};",
364             format("namespace {\n"
365                    "int i;\n"
366                    "};",
367                    LLVMWithNoNamespaceFix));
368   EXPECT_EQ("namespace {\n"
369             "int i;\n"
370             "\n"
371             "}",
372             format("namespace {\n"
373                    "int i;\n"
374                    "\n"
375                    "}"));
376   EXPECT_EQ("namespace {\n"
377             "int i;\n"
378             "\n"
379             "} // namespace",
380             format("namespace {\n"
381                    "int i;\n"
382                    "\n"
383                    "}  // namespace"));
384 
385   FormatStyle Style = getLLVMStyle();
386   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
387   Style.MaxEmptyLinesToKeep = 2;
388   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
389   Style.BraceWrapping.AfterClass = true;
390   Style.BraceWrapping.AfterFunction = true;
391   Style.KeepEmptyLinesAtTheStartOfBlocks = false;
392 
393   EXPECT_EQ("class Foo\n"
394             "{\n"
395             "  Foo() {}\n"
396             "\n"
397             "  void funk() {}\n"
398             "};",
399             format("class Foo\n"
400                    "{\n"
401                    "  Foo()\n"
402                    "  {\n"
403                    "  }\n"
404                    "\n"
405                    "  void funk() {}\n"
406                    "};",
407                    Style));
408 }
409 
410 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
411   verifyFormat("x = (a) and (b);");
412   verifyFormat("x = (a) or (b);");
413   verifyFormat("x = (a) bitand (b);");
414   verifyFormat("x = (a) bitor (b);");
415   verifyFormat("x = (a) not_eq (b);");
416   verifyFormat("x = (a) and_eq (b);");
417   verifyFormat("x = (a) or_eq (b);");
418   verifyFormat("x = (a) xor (b);");
419 }
420 
421 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
422   verifyFormat("x = compl(a);");
423   verifyFormat("x = not(a);");
424   verifyFormat("x = bitand(a);");
425   // Unary operator must not be merged with the next identifier
426   verifyFormat("x = compl a;");
427   verifyFormat("x = not a;");
428   verifyFormat("x = bitand a;");
429 }
430 
431 //===----------------------------------------------------------------------===//
432 // Tests for control statements.
433 //===----------------------------------------------------------------------===//
434 
435 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
436   verifyFormat("if (true)\n  f();\ng();");
437   verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
438   verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
439   verifyFormat("if constexpr (true)\n"
440                "  f();\ng();");
441   verifyFormat("if CONSTEXPR (true)\n"
442                "  f();\ng();");
443   verifyFormat("if constexpr (a)\n"
444                "  if constexpr (b)\n"
445                "    if constexpr (c)\n"
446                "      g();\n"
447                "h();");
448   verifyFormat("if CONSTEXPR (a)\n"
449                "  if CONSTEXPR (b)\n"
450                "    if CONSTEXPR (c)\n"
451                "      g();\n"
452                "h();");
453   verifyFormat("if constexpr (a)\n"
454                "  if constexpr (b) {\n"
455                "    f();\n"
456                "  }\n"
457                "g();");
458   verifyFormat("if CONSTEXPR (a)\n"
459                "  if CONSTEXPR (b) {\n"
460                "    f();\n"
461                "  }\n"
462                "g();");
463 
464   FormatStyle AllowsMergedIf = getLLVMStyle();
465   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
466   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
467       FormatStyle::SIS_WithoutElse;
468   verifyFormat("if (a)\n"
469                "  // comment\n"
470                "  f();",
471                AllowsMergedIf);
472   verifyFormat("{\n"
473                "  if (a)\n"
474                "  label:\n"
475                "    f();\n"
476                "}",
477                AllowsMergedIf);
478   verifyFormat("#define A \\\n"
479                "  if (a)  \\\n"
480                "  label:  \\\n"
481                "    f()",
482                AllowsMergedIf);
483   verifyFormat("if (a)\n"
484                "  ;",
485                AllowsMergedIf);
486   verifyFormat("if (a)\n"
487                "  if (b) return;",
488                AllowsMergedIf);
489 
490   verifyFormat("if (a) // Can't merge this\n"
491                "  f();\n",
492                AllowsMergedIf);
493   verifyFormat("if (a) /* still don't merge */\n"
494                "  f();",
495                AllowsMergedIf);
496   verifyFormat("if (a) { // Never merge this\n"
497                "  f();\n"
498                "}",
499                AllowsMergedIf);
500   verifyFormat("if (a) { /* Never merge this */\n"
501                "  f();\n"
502                "}",
503                AllowsMergedIf);
504 
505   AllowsMergedIf.ColumnLimit = 14;
506   verifyFormat("if (a) return;", AllowsMergedIf);
507   verifyFormat("if (aaaaaaaaa)\n"
508                "  return;",
509                AllowsMergedIf);
510 
511   AllowsMergedIf.ColumnLimit = 13;
512   verifyFormat("if (a)\n  return;", AllowsMergedIf);
513 }
514 
515 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
516   FormatStyle AllowsMergedIf = getLLVMStyle();
517   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
518   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
519       FormatStyle::SIS_WithoutElse;
520   verifyFormat("if (a)\n"
521                "  f();\n"
522                "else {\n"
523                "  g();\n"
524                "}",
525                AllowsMergedIf);
526   verifyFormat("if (a)\n"
527                "  f();\n"
528                "else\n"
529                "  g();\n",
530                AllowsMergedIf);
531 
532   AllowsMergedIf.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
533 
534   verifyFormat("if (a) f();\n"
535                "else {\n"
536                "  g();\n"
537                "}",
538                AllowsMergedIf);
539   verifyFormat("if (a) f();\n"
540                "else {\n"
541                "  if (a) f();\n"
542                "  else {\n"
543                "    g();\n"
544                "  }\n"
545                "  g();\n"
546                "}",
547                AllowsMergedIf);
548 }
549 
550 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
551   FormatStyle AllowsMergedLoops = getLLVMStyle();
552   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
553   verifyFormat("while (true) continue;", AllowsMergedLoops);
554   verifyFormat("for (;;) continue;", AllowsMergedLoops);
555   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
556   verifyFormat("while (true)\n"
557                "  ;",
558                AllowsMergedLoops);
559   verifyFormat("for (;;)\n"
560                "  ;",
561                AllowsMergedLoops);
562   verifyFormat("for (;;)\n"
563                "  for (;;) continue;",
564                AllowsMergedLoops);
565   verifyFormat("for (;;) // Can't merge this\n"
566                "  continue;",
567                AllowsMergedLoops);
568   verifyFormat("for (;;) /* still don't merge */\n"
569                "  continue;",
570                AllowsMergedLoops);
571   verifyFormat("do a++;\n"
572                "while (true);",
573                AllowsMergedLoops);
574   verifyFormat("do /* Don't merge */\n"
575                "  a++;\n"
576                "while (true);",
577                AllowsMergedLoops);
578   verifyFormat("do // Don't merge\n"
579                "  a++;\n"
580                "while (true);",
581                AllowsMergedLoops);
582   verifyFormat("do\n"
583                "  // Don't merge\n"
584                "  a++;\n"
585                "while (true);",
586                AllowsMergedLoops);
587   // Without braces labels are interpreted differently.
588   verifyFormat("{\n"
589                "  do\n"
590                "  label:\n"
591                "    a++;\n"
592                "  while (true);\n"
593                "}",
594                AllowsMergedLoops);
595 }
596 
597 TEST_F(FormatTest, FormatShortBracedStatements) {
598   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
599   AllowSimpleBracedStatements.ColumnLimit = 40;
600   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
601       FormatStyle::SBS_Always;
602 
603   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
604       FormatStyle::SIS_WithoutElse;
605   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
606 
607   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
608   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
609   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
610 
611   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
612   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
613   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
614   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
615   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
616   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
617   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
618   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
619   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
620   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
621   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
622                AllowSimpleBracedStatements);
623   verifyFormat("if (true) {\n"
624                "  ffffffffffffffffffffffff();\n"
625                "}",
626                AllowSimpleBracedStatements);
627   verifyFormat("if (true) {\n"
628                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
629                "}",
630                AllowSimpleBracedStatements);
631   verifyFormat("if (true) { //\n"
632                "  f();\n"
633                "}",
634                AllowSimpleBracedStatements);
635   verifyFormat("if (true) {\n"
636                "  f();\n"
637                "  f();\n"
638                "}",
639                AllowSimpleBracedStatements);
640   verifyFormat("if (true) {\n"
641                "  f();\n"
642                "} else {\n"
643                "  f();\n"
644                "}",
645                AllowSimpleBracedStatements);
646 
647   verifyFormat("struct A2 {\n"
648                "  int X;\n"
649                "};",
650                AllowSimpleBracedStatements);
651   verifyFormat("typedef struct A2 {\n"
652                "  int X;\n"
653                "} A2_t;",
654                AllowSimpleBracedStatements);
655   verifyFormat("template <int> struct A2 {\n"
656                "  struct B {};\n"
657                "};",
658                AllowSimpleBracedStatements);
659 
660   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
661       FormatStyle::SIS_Never;
662   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
663   verifyFormat("if (true) {\n"
664                "  f();\n"
665                "}",
666                AllowSimpleBracedStatements);
667   verifyFormat("if (true) {\n"
668                "  f();\n"
669                "} else {\n"
670                "  f();\n"
671                "}",
672                AllowSimpleBracedStatements);
673 
674   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
675   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
676   verifyFormat("while (true) {\n"
677                "  f();\n"
678                "}",
679                AllowSimpleBracedStatements);
680   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
681   verifyFormat("for (;;) {\n"
682                "  f();\n"
683                "}",
684                AllowSimpleBracedStatements);
685 
686   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
687       FormatStyle::SIS_WithoutElse;
688   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
689   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
690       FormatStyle::BWACS_Always;
691 
692   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
693   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
694   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
695   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
696   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
697   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
698   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
699   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
700   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
701   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
702   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
703                AllowSimpleBracedStatements);
704   verifyFormat("if (true)\n"
705                "{\n"
706                "  ffffffffffffffffffffffff();\n"
707                "}",
708                AllowSimpleBracedStatements);
709   verifyFormat("if (true)\n"
710                "{\n"
711                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
712                "}",
713                AllowSimpleBracedStatements);
714   verifyFormat("if (true)\n"
715                "{ //\n"
716                "  f();\n"
717                "}",
718                AllowSimpleBracedStatements);
719   verifyFormat("if (true)\n"
720                "{\n"
721                "  f();\n"
722                "  f();\n"
723                "}",
724                AllowSimpleBracedStatements);
725   verifyFormat("if (true)\n"
726                "{\n"
727                "  f();\n"
728                "} else\n"
729                "{\n"
730                "  f();\n"
731                "}",
732                AllowSimpleBracedStatements);
733 
734   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
735       FormatStyle::SIS_Never;
736   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
737   verifyFormat("if (true)\n"
738                "{\n"
739                "  f();\n"
740                "}",
741                AllowSimpleBracedStatements);
742   verifyFormat("if (true)\n"
743                "{\n"
744                "  f();\n"
745                "} else\n"
746                "{\n"
747                "  f();\n"
748                "}",
749                AllowSimpleBracedStatements);
750 
751   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
752   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
753   verifyFormat("while (true)\n"
754                "{\n"
755                "  f();\n"
756                "}",
757                AllowSimpleBracedStatements);
758   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
759   verifyFormat("for (;;)\n"
760                "{\n"
761                "  f();\n"
762                "}",
763                AllowSimpleBracedStatements);
764 }
765 
766 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
767   FormatStyle Style = getLLVMStyleWithColumns(60);
768   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
769   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
770   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
771   EXPECT_EQ("#define A                                                  \\\n"
772             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
773             "  {                                                        \\\n"
774             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
775             "  }\n"
776             "X;",
777             format("#define A \\\n"
778                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
779                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
780                    "   }\n"
781                    "X;",
782                    Style));
783 }
784 
785 TEST_F(FormatTest, ParseIfElse) {
786   verifyFormat("if (true)\n"
787                "  if (true)\n"
788                "    if (true)\n"
789                "      f();\n"
790                "    else\n"
791                "      g();\n"
792                "  else\n"
793                "    h();\n"
794                "else\n"
795                "  i();");
796   verifyFormat("if (true)\n"
797                "  if (true)\n"
798                "    if (true) {\n"
799                "      if (true)\n"
800                "        f();\n"
801                "    } else {\n"
802                "      g();\n"
803                "    }\n"
804                "  else\n"
805                "    h();\n"
806                "else {\n"
807                "  i();\n"
808                "}");
809   verifyFormat("if (true)\n"
810                "  if constexpr (true)\n"
811                "    if (true) {\n"
812                "      if constexpr (true)\n"
813                "        f();\n"
814                "    } else {\n"
815                "      g();\n"
816                "    }\n"
817                "  else\n"
818                "    h();\n"
819                "else {\n"
820                "  i();\n"
821                "}");
822   verifyFormat("if (true)\n"
823                "  if CONSTEXPR (true)\n"
824                "    if (true) {\n"
825                "      if CONSTEXPR (true)\n"
826                "        f();\n"
827                "    } else {\n"
828                "      g();\n"
829                "    }\n"
830                "  else\n"
831                "    h();\n"
832                "else {\n"
833                "  i();\n"
834                "}");
835   verifyFormat("void f() {\n"
836                "  if (a) {\n"
837                "  } else {\n"
838                "  }\n"
839                "}");
840 }
841 
842 TEST_F(FormatTest, ElseIf) {
843   verifyFormat("if (a) {\n} else if (b) {\n}");
844   verifyFormat("if (a)\n"
845                "  f();\n"
846                "else if (b)\n"
847                "  g();\n"
848                "else\n"
849                "  h();");
850   verifyFormat("if constexpr (a)\n"
851                "  f();\n"
852                "else if constexpr (b)\n"
853                "  g();\n"
854                "else\n"
855                "  h();");
856   verifyFormat("if CONSTEXPR (a)\n"
857                "  f();\n"
858                "else if CONSTEXPR (b)\n"
859                "  g();\n"
860                "else\n"
861                "  h();");
862   verifyFormat("if (a) {\n"
863                "  f();\n"
864                "}\n"
865                "// or else ..\n"
866                "else {\n"
867                "  g()\n"
868                "}");
869 
870   verifyFormat("if (a) {\n"
871                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
872                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
873                "}");
874   verifyFormat("if (a) {\n"
875                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
876                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
877                "}");
878   verifyFormat("if (a) {\n"
879                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
880                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
881                "}");
882   verifyFormat("if (a) {\n"
883                "} else if (\n"
884                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
885                "}",
886                getLLVMStyleWithColumns(62));
887   verifyFormat("if (a) {\n"
888                "} else if constexpr (\n"
889                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
890                "}",
891                getLLVMStyleWithColumns(62));
892   verifyFormat("if (a) {\n"
893                "} else if CONSTEXPR (\n"
894                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
895                "}",
896                getLLVMStyleWithColumns(62));
897 }
898 
899 TEST_F(FormatTest, FormatsForLoop) {
900   verifyFormat(
901       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
902       "     ++VeryVeryLongLoopVariable)\n"
903       "  ;");
904   verifyFormat("for (;;)\n"
905                "  f();");
906   verifyFormat("for (;;) {\n}");
907   verifyFormat("for (;;) {\n"
908                "  f();\n"
909                "}");
910   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
911 
912   verifyFormat(
913       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
914       "                                          E = UnwrappedLines.end();\n"
915       "     I != E; ++I) {\n}");
916 
917   verifyFormat(
918       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
919       "     ++IIIII) {\n}");
920   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
921                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
922                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
923   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
924                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
925                "         E = FD->getDeclsInPrototypeScope().end();\n"
926                "     I != E; ++I) {\n}");
927   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
928                "         I = Container.begin(),\n"
929                "         E = Container.end();\n"
930                "     I != E; ++I) {\n}",
931                getLLVMStyleWithColumns(76));
932 
933   verifyFormat(
934       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
935       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
936       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
937       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
938       "     ++aaaaaaaaaaa) {\n}");
939   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
940                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
941                "     ++i) {\n}");
942   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
943                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
944                "}");
945   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
946                "         aaaaaaaaaa);\n"
947                "     iter; ++iter) {\n"
948                "}");
949   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
950                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
951                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
952                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
953 
954   // These should not be formatted as Objective-C for-in loops.
955   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
956   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
957   verifyFormat("Foo *x;\nfor (x in y) {\n}");
958   verifyFormat(
959       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
960 
961   FormatStyle NoBinPacking = getLLVMStyle();
962   NoBinPacking.BinPackParameters = false;
963   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
964                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
965                "                                           aaaaaaaaaaaaaaaa,\n"
966                "                                           aaaaaaaaaaaaaaaa,\n"
967                "                                           aaaaaaaaaaaaaaaa);\n"
968                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
969                "}",
970                NoBinPacking);
971   verifyFormat(
972       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
973       "                                          E = UnwrappedLines.end();\n"
974       "     I != E;\n"
975       "     ++I) {\n}",
976       NoBinPacking);
977 
978   FormatStyle AlignLeft = getLLVMStyle();
979   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
980   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
981 }
982 
983 TEST_F(FormatTest, RangeBasedForLoops) {
984   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
985                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
986   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
987                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
988   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
989                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
990   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
991                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
992 }
993 
994 TEST_F(FormatTest, ForEachLoops) {
995   verifyFormat("void f() {\n"
996                "  foreach (Item *item, itemlist) {}\n"
997                "  Q_FOREACH (Item *item, itemlist) {}\n"
998                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
999                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
1000                "}");
1001 
1002   FormatStyle Style = getLLVMStyle();
1003   Style.SpaceBeforeParens =
1004       FormatStyle::SBPO_ControlStatementsExceptForEachMacros;
1005   verifyFormat("void f() {\n"
1006                "  foreach(Item *item, itemlist) {}\n"
1007                "  Q_FOREACH(Item *item, itemlist) {}\n"
1008                "  BOOST_FOREACH(Item *item, itemlist) {}\n"
1009                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
1010                "}",
1011                Style);
1012 
1013   // As function-like macros.
1014   verifyFormat("#define foreach(x, y)\n"
1015                "#define Q_FOREACH(x, y)\n"
1016                "#define BOOST_FOREACH(x, y)\n"
1017                "#define UNKNOWN_FOREACH(x, y)\n");
1018 
1019   // Not as function-like macros.
1020   verifyFormat("#define foreach (x, y)\n"
1021                "#define Q_FOREACH (x, y)\n"
1022                "#define BOOST_FOREACH (x, y)\n"
1023                "#define UNKNOWN_FOREACH (x, y)\n");
1024 
1025   // handle microsoft non standard extension
1026   verifyFormat("for each (char c in x->MyStringProperty)");
1027 }
1028 
1029 TEST_F(FormatTest, FormatsWhileLoop) {
1030   verifyFormat("while (true) {\n}");
1031   verifyFormat("while (true)\n"
1032                "  f();");
1033   verifyFormat("while () {\n}");
1034   verifyFormat("while () {\n"
1035                "  f();\n"
1036                "}");
1037 }
1038 
1039 TEST_F(FormatTest, FormatsDoWhile) {
1040   verifyFormat("do {\n"
1041                "  do_something();\n"
1042                "} while (something());");
1043   verifyFormat("do\n"
1044                "  do_something();\n"
1045                "while (something());");
1046 }
1047 
1048 TEST_F(FormatTest, FormatsSwitchStatement) {
1049   verifyFormat("switch (x) {\n"
1050                "case 1:\n"
1051                "  f();\n"
1052                "  break;\n"
1053                "case kFoo:\n"
1054                "case ns::kBar:\n"
1055                "case kBaz:\n"
1056                "  break;\n"
1057                "default:\n"
1058                "  g();\n"
1059                "  break;\n"
1060                "}");
1061   verifyFormat("switch (x) {\n"
1062                "case 1: {\n"
1063                "  f();\n"
1064                "  break;\n"
1065                "}\n"
1066                "case 2: {\n"
1067                "  break;\n"
1068                "}\n"
1069                "}");
1070   verifyFormat("switch (x) {\n"
1071                "case 1: {\n"
1072                "  f();\n"
1073                "  {\n"
1074                "    g();\n"
1075                "    h();\n"
1076                "  }\n"
1077                "  break;\n"
1078                "}\n"
1079                "}");
1080   verifyFormat("switch (x) {\n"
1081                "case 1: {\n"
1082                "  f();\n"
1083                "  if (foo) {\n"
1084                "    g();\n"
1085                "    h();\n"
1086                "  }\n"
1087                "  break;\n"
1088                "}\n"
1089                "}");
1090   verifyFormat("switch (x) {\n"
1091                "case 1: {\n"
1092                "  f();\n"
1093                "  g();\n"
1094                "} break;\n"
1095                "}");
1096   verifyFormat("switch (test)\n"
1097                "  ;");
1098   verifyFormat("switch (x) {\n"
1099                "default: {\n"
1100                "  // Do nothing.\n"
1101                "}\n"
1102                "}");
1103   verifyFormat("switch (x) {\n"
1104                "// comment\n"
1105                "// if 1, do f()\n"
1106                "case 1:\n"
1107                "  f();\n"
1108                "}");
1109   verifyFormat("switch (x) {\n"
1110                "case 1:\n"
1111                "  // Do amazing stuff\n"
1112                "  {\n"
1113                "    f();\n"
1114                "    g();\n"
1115                "  }\n"
1116                "  break;\n"
1117                "}");
1118   verifyFormat("#define A          \\\n"
1119                "  switch (x) {     \\\n"
1120                "  case a:          \\\n"
1121                "    foo = b;       \\\n"
1122                "  }",
1123                getLLVMStyleWithColumns(20));
1124   verifyFormat("#define OPERATION_CASE(name)           \\\n"
1125                "  case OP_name:                        \\\n"
1126                "    return operations::Operation##name\n",
1127                getLLVMStyleWithColumns(40));
1128   verifyFormat("switch (x) {\n"
1129                "case 1:;\n"
1130                "default:;\n"
1131                "  int i;\n"
1132                "}");
1133 
1134   verifyGoogleFormat("switch (x) {\n"
1135                      "  case 1:\n"
1136                      "    f();\n"
1137                      "    break;\n"
1138                      "  case kFoo:\n"
1139                      "  case ns::kBar:\n"
1140                      "  case kBaz:\n"
1141                      "    break;\n"
1142                      "  default:\n"
1143                      "    g();\n"
1144                      "    break;\n"
1145                      "}");
1146   verifyGoogleFormat("switch (x) {\n"
1147                      "  case 1: {\n"
1148                      "    f();\n"
1149                      "    break;\n"
1150                      "  }\n"
1151                      "}");
1152   verifyGoogleFormat("switch (test)\n"
1153                      "  ;");
1154 
1155   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
1156                      "  case OP_name:              \\\n"
1157                      "    return operations::Operation##name\n");
1158   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
1159                      "  // Get the correction operation class.\n"
1160                      "  switch (OpCode) {\n"
1161                      "    CASE(Add);\n"
1162                      "    CASE(Subtract);\n"
1163                      "    default:\n"
1164                      "      return operations::Unknown;\n"
1165                      "  }\n"
1166                      "#undef OPERATION_CASE\n"
1167                      "}");
1168   verifyFormat("DEBUG({\n"
1169                "  switch (x) {\n"
1170                "  case A:\n"
1171                "    f();\n"
1172                "    break;\n"
1173                "    // fallthrough\n"
1174                "  case B:\n"
1175                "    g();\n"
1176                "    break;\n"
1177                "  }\n"
1178                "});");
1179   EXPECT_EQ("DEBUG({\n"
1180             "  switch (x) {\n"
1181             "  case A:\n"
1182             "    f();\n"
1183             "    break;\n"
1184             "  // On B:\n"
1185             "  case B:\n"
1186             "    g();\n"
1187             "    break;\n"
1188             "  }\n"
1189             "});",
1190             format("DEBUG({\n"
1191                    "  switch (x) {\n"
1192                    "  case A:\n"
1193                    "    f();\n"
1194                    "    break;\n"
1195                    "  // On B:\n"
1196                    "  case B:\n"
1197                    "    g();\n"
1198                    "    break;\n"
1199                    "  }\n"
1200                    "});",
1201                    getLLVMStyle()));
1202   EXPECT_EQ("switch (n) {\n"
1203             "case 0: {\n"
1204             "  return false;\n"
1205             "}\n"
1206             "default: {\n"
1207             "  return true;\n"
1208             "}\n"
1209             "}",
1210             format("switch (n)\n"
1211                    "{\n"
1212                    "case 0: {\n"
1213                    "  return false;\n"
1214                    "}\n"
1215                    "default: {\n"
1216                    "  return true;\n"
1217                    "}\n"
1218                    "}",
1219                    getLLVMStyle()));
1220   verifyFormat("switch (a) {\n"
1221                "case (b):\n"
1222                "  return;\n"
1223                "}");
1224 
1225   verifyFormat("switch (a) {\n"
1226                "case some_namespace::\n"
1227                "    some_constant:\n"
1228                "  return;\n"
1229                "}",
1230                getLLVMStyleWithColumns(34));
1231 
1232   FormatStyle Style = getLLVMStyle();
1233   Style.IndentCaseLabels = true;
1234   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1235   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1236   Style.BraceWrapping.AfterCaseLabel = true;
1237   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1238   EXPECT_EQ("switch (n)\n"
1239             "{\n"
1240             "  case 0:\n"
1241             "  {\n"
1242             "    return false;\n"
1243             "  }\n"
1244             "  default:\n"
1245             "  {\n"
1246             "    return true;\n"
1247             "  }\n"
1248             "}",
1249             format("switch (n) {\n"
1250                    "  case 0: {\n"
1251                    "    return false;\n"
1252                    "  }\n"
1253                    "  default: {\n"
1254                    "    return true;\n"
1255                    "  }\n"
1256                    "}",
1257                    Style));
1258   Style.BraceWrapping.AfterCaseLabel = false;
1259   EXPECT_EQ("switch (n)\n"
1260             "{\n"
1261             "  case 0: {\n"
1262             "    return false;\n"
1263             "  }\n"
1264             "  default: {\n"
1265             "    return true;\n"
1266             "  }\n"
1267             "}",
1268             format("switch (n) {\n"
1269                    "  case 0:\n"
1270                    "  {\n"
1271                    "    return false;\n"
1272                    "  }\n"
1273                    "  default:\n"
1274                    "  {\n"
1275                    "    return true;\n"
1276                    "  }\n"
1277                    "}",
1278                    Style));
1279   Style.IndentCaseLabels = false;
1280   Style.IndentCaseBlocks = true;
1281   EXPECT_EQ("switch (n)\n"
1282             "{\n"
1283             "case 0:\n"
1284             "  {\n"
1285             "    return false;\n"
1286             "  }\n"
1287             "case 1:\n"
1288             "  break;\n"
1289             "default:\n"
1290             "  {\n"
1291             "    return true;\n"
1292             "  }\n"
1293             "}",
1294             format("switch (n) {\n"
1295                    "case 0: {\n"
1296                    "  return false;\n"
1297                    "}\n"
1298                    "case 1:\n"
1299                    "  break;\n"
1300                    "default: {\n"
1301                    "  return true;\n"
1302                    "}\n"
1303                    "}",
1304                    Style));
1305   Style.IndentCaseLabels = true;
1306   Style.IndentCaseBlocks = true;
1307   EXPECT_EQ("switch (n)\n"
1308             "{\n"
1309             "  case 0:\n"
1310             "    {\n"
1311             "      return false;\n"
1312             "    }\n"
1313             "  case 1:\n"
1314             "    break;\n"
1315             "  default:\n"
1316             "    {\n"
1317             "      return true;\n"
1318             "    }\n"
1319             "}",
1320             format("switch (n) {\n"
1321                    "case 0: {\n"
1322                    "  return false;\n"
1323                    "}\n"
1324                    "case 1:\n"
1325                    "  break;\n"
1326                    "default: {\n"
1327                    "  return true;\n"
1328                    "}\n"
1329                    "}",
1330                    Style));
1331 }
1332 
1333 TEST_F(FormatTest, CaseRanges) {
1334   verifyFormat("switch (x) {\n"
1335                "case 'A' ... 'Z':\n"
1336                "case 1 ... 5:\n"
1337                "case a ... b:\n"
1338                "  break;\n"
1339                "}");
1340 }
1341 
1342 TEST_F(FormatTest, ShortEnums) {
1343   FormatStyle Style = getLLVMStyle();
1344   Style.AllowShortEnumsOnASingleLine = true;
1345   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
1346   Style.AllowShortEnumsOnASingleLine = false;
1347   verifyFormat("enum\n"
1348                "{\n"
1349                "  A,\n"
1350                "  B,\n"
1351                "  C\n"
1352                "} ShortEnum1, ShortEnum2;",
1353                Style);
1354 }
1355 
1356 TEST_F(FormatTest, ShortCaseLabels) {
1357   FormatStyle Style = getLLVMStyle();
1358   Style.AllowShortCaseLabelsOnASingleLine = true;
1359   verifyFormat("switch (a) {\n"
1360                "case 1: x = 1; break;\n"
1361                "case 2: return;\n"
1362                "case 3:\n"
1363                "case 4:\n"
1364                "case 5: return;\n"
1365                "case 6: // comment\n"
1366                "  return;\n"
1367                "case 7:\n"
1368                "  // comment\n"
1369                "  return;\n"
1370                "case 8:\n"
1371                "  x = 8; // comment\n"
1372                "  break;\n"
1373                "default: y = 1; break;\n"
1374                "}",
1375                Style);
1376   verifyFormat("switch (a) {\n"
1377                "case 0: return; // comment\n"
1378                "case 1: break;  // comment\n"
1379                "case 2: return;\n"
1380                "// comment\n"
1381                "case 3: return;\n"
1382                "// comment 1\n"
1383                "// comment 2\n"
1384                "// comment 3\n"
1385                "case 4: break; /* comment */\n"
1386                "case 5:\n"
1387                "  // comment\n"
1388                "  break;\n"
1389                "case 6: /* comment */ x = 1; break;\n"
1390                "case 7: x = /* comment */ 1; break;\n"
1391                "case 8:\n"
1392                "  x = 1; /* comment */\n"
1393                "  break;\n"
1394                "case 9:\n"
1395                "  break; // comment line 1\n"
1396                "         // comment line 2\n"
1397                "}",
1398                Style);
1399   EXPECT_EQ("switch (a) {\n"
1400             "case 1:\n"
1401             "  x = 8;\n"
1402             "  // fall through\n"
1403             "case 2: x = 8;\n"
1404             "// comment\n"
1405             "case 3:\n"
1406             "  return; /* comment line 1\n"
1407             "           * comment line 2 */\n"
1408             "case 4: i = 8;\n"
1409             "// something else\n"
1410             "#if FOO\n"
1411             "case 5: break;\n"
1412             "#endif\n"
1413             "}",
1414             format("switch (a) {\n"
1415                    "case 1: x = 8;\n"
1416                    "  // fall through\n"
1417                    "case 2:\n"
1418                    "  x = 8;\n"
1419                    "// comment\n"
1420                    "case 3:\n"
1421                    "  return; /* comment line 1\n"
1422                    "           * comment line 2 */\n"
1423                    "case 4:\n"
1424                    "  i = 8;\n"
1425                    "// something else\n"
1426                    "#if FOO\n"
1427                    "case 5: break;\n"
1428                    "#endif\n"
1429                    "}",
1430                    Style));
1431   EXPECT_EQ("switch (a) {\n"
1432             "case 0:\n"
1433             "  return; // long long long long long long long long long long "
1434             "long long comment\n"
1435             "          // line\n"
1436             "}",
1437             format("switch (a) {\n"
1438                    "case 0: return; // long long long long long long long long "
1439                    "long long long long comment line\n"
1440                    "}",
1441                    Style));
1442   EXPECT_EQ("switch (a) {\n"
1443             "case 0:\n"
1444             "  return; /* long long long long long long long long long long "
1445             "long long comment\n"
1446             "             line */\n"
1447             "}",
1448             format("switch (a) {\n"
1449                    "case 0: return; /* long long long long long long long long "
1450                    "long long long long comment line */\n"
1451                    "}",
1452                    Style));
1453   verifyFormat("switch (a) {\n"
1454                "#if FOO\n"
1455                "case 0: return 0;\n"
1456                "#endif\n"
1457                "}",
1458                Style);
1459   verifyFormat("switch (a) {\n"
1460                "case 1: {\n"
1461                "}\n"
1462                "case 2: {\n"
1463                "  return;\n"
1464                "}\n"
1465                "case 3: {\n"
1466                "  x = 1;\n"
1467                "  return;\n"
1468                "}\n"
1469                "case 4:\n"
1470                "  if (x)\n"
1471                "    return;\n"
1472                "}",
1473                Style);
1474   Style.ColumnLimit = 21;
1475   verifyFormat("switch (a) {\n"
1476                "case 1: x = 1; break;\n"
1477                "case 2: return;\n"
1478                "case 3:\n"
1479                "case 4:\n"
1480                "case 5: return;\n"
1481                "default:\n"
1482                "  y = 1;\n"
1483                "  break;\n"
1484                "}",
1485                Style);
1486   Style.ColumnLimit = 80;
1487   Style.AllowShortCaseLabelsOnASingleLine = false;
1488   Style.IndentCaseLabels = true;
1489   EXPECT_EQ("switch (n) {\n"
1490             "  default /*comments*/:\n"
1491             "    return true;\n"
1492             "  case 0:\n"
1493             "    return false;\n"
1494             "}",
1495             format("switch (n) {\n"
1496                    "default/*comments*/:\n"
1497                    "  return true;\n"
1498                    "case 0:\n"
1499                    "  return false;\n"
1500                    "}",
1501                    Style));
1502   Style.AllowShortCaseLabelsOnASingleLine = true;
1503   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1504   Style.BraceWrapping.AfterCaseLabel = true;
1505   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1506   EXPECT_EQ("switch (n)\n"
1507             "{\n"
1508             "  case 0:\n"
1509             "  {\n"
1510             "    return false;\n"
1511             "  }\n"
1512             "  default:\n"
1513             "  {\n"
1514             "    return true;\n"
1515             "  }\n"
1516             "}",
1517             format("switch (n) {\n"
1518                    "  case 0: {\n"
1519                    "    return false;\n"
1520                    "  }\n"
1521                    "  default:\n"
1522                    "  {\n"
1523                    "    return true;\n"
1524                    "  }\n"
1525                    "}",
1526                    Style));
1527 }
1528 
1529 TEST_F(FormatTest, FormatsLabels) {
1530   verifyFormat("void f() {\n"
1531                "  some_code();\n"
1532                "test_label:\n"
1533                "  some_other_code();\n"
1534                "  {\n"
1535                "    some_more_code();\n"
1536                "  another_label:\n"
1537                "    some_more_code();\n"
1538                "  }\n"
1539                "}");
1540   verifyFormat("{\n"
1541                "  some_code();\n"
1542                "test_label:\n"
1543                "  some_other_code();\n"
1544                "}");
1545   verifyFormat("{\n"
1546                "  some_code();\n"
1547                "test_label:;\n"
1548                "  int i = 0;\n"
1549                "}");
1550   FormatStyle Style = getLLVMStyle();
1551   Style.IndentGotoLabels = false;
1552   verifyFormat("void f() {\n"
1553                "  some_code();\n"
1554                "test_label:\n"
1555                "  some_other_code();\n"
1556                "  {\n"
1557                "    some_more_code();\n"
1558                "another_label:\n"
1559                "    some_more_code();\n"
1560                "  }\n"
1561                "}",
1562                Style);
1563   verifyFormat("{\n"
1564                "  some_code();\n"
1565                "test_label:\n"
1566                "  some_other_code();\n"
1567                "}",
1568                Style);
1569   verifyFormat("{\n"
1570                "  some_code();\n"
1571                "test_label:;\n"
1572                "  int i = 0;\n"
1573                "}");
1574 }
1575 
1576 TEST_F(FormatTest, MultiLineControlStatements) {
1577   FormatStyle Style = getLLVMStyle();
1578   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
1579   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
1580   Style.ColumnLimit = 20;
1581   // Short lines should keep opening brace on same line.
1582   EXPECT_EQ("if (foo) {\n"
1583             "  bar();\n"
1584             "}",
1585             format("if(foo){bar();}", Style));
1586   EXPECT_EQ("if (foo) {\n"
1587             "  bar();\n"
1588             "} else {\n"
1589             "  baz();\n"
1590             "}",
1591             format("if(foo){bar();}else{baz();}", Style));
1592   EXPECT_EQ("if (foo && bar) {\n"
1593             "  baz();\n"
1594             "}",
1595             format("if(foo&&bar){baz();}", Style));
1596   EXPECT_EQ("if (foo) {\n"
1597             "  bar();\n"
1598             "} else if (baz) {\n"
1599             "  quux();\n"
1600             "}",
1601             format("if(foo){bar();}else if(baz){quux();}", Style));
1602   EXPECT_EQ(
1603       "if (foo) {\n"
1604       "  bar();\n"
1605       "} else if (baz) {\n"
1606       "  quux();\n"
1607       "} else {\n"
1608       "  foobar();\n"
1609       "}",
1610       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
1611   EXPECT_EQ("for (;;) {\n"
1612             "  foo();\n"
1613             "}",
1614             format("for(;;){foo();}"));
1615   EXPECT_EQ("while (1) {\n"
1616             "  foo();\n"
1617             "}",
1618             format("while(1){foo();}", Style));
1619   EXPECT_EQ("switch (foo) {\n"
1620             "case bar:\n"
1621             "  return;\n"
1622             "}",
1623             format("switch(foo){case bar:return;}", Style));
1624   EXPECT_EQ("try {\n"
1625             "  foo();\n"
1626             "} catch (...) {\n"
1627             "  bar();\n"
1628             "}",
1629             format("try{foo();}catch(...){bar();}", Style));
1630   EXPECT_EQ("do {\n"
1631             "  foo();\n"
1632             "} while (bar &&\n"
1633             "         baz);",
1634             format("do{foo();}while(bar&&baz);", Style));
1635   // Long lines should put opening brace on new line.
1636   EXPECT_EQ("if (foo && bar &&\n"
1637             "    baz)\n"
1638             "{\n"
1639             "  quux();\n"
1640             "}",
1641             format("if(foo&&bar&&baz){quux();}", Style));
1642   EXPECT_EQ("if (foo && bar &&\n"
1643             "    baz)\n"
1644             "{\n"
1645             "  quux();\n"
1646             "}",
1647             format("if (foo && bar &&\n"
1648                    "    baz) {\n"
1649                    "  quux();\n"
1650                    "}",
1651                    Style));
1652   EXPECT_EQ("if (foo) {\n"
1653             "  bar();\n"
1654             "} else if (baz ||\n"
1655             "           quux)\n"
1656             "{\n"
1657             "  foobar();\n"
1658             "}",
1659             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
1660   EXPECT_EQ(
1661       "if (foo) {\n"
1662       "  bar();\n"
1663       "} else if (baz ||\n"
1664       "           quux)\n"
1665       "{\n"
1666       "  foobar();\n"
1667       "} else {\n"
1668       "  barbaz();\n"
1669       "}",
1670       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
1671              Style));
1672   EXPECT_EQ("for (int i = 0;\n"
1673             "     i < 10; ++i)\n"
1674             "{\n"
1675             "  foo();\n"
1676             "}",
1677             format("for(int i=0;i<10;++i){foo();}", Style));
1678   EXPECT_EQ("foreach (int i,\n"
1679             "         list)\n"
1680             "{\n"
1681             "  foo();\n"
1682             "}",
1683             format("foreach(int i, list){foo();}", Style));
1684   Style.ColumnLimit =
1685       40; // to concentrate at brace wrapping, not line wrap due to column limit
1686   EXPECT_EQ("foreach (int i, list) {\n"
1687             "  foo();\n"
1688             "}",
1689             format("foreach(int i, list){foo();}", Style));
1690   Style.ColumnLimit =
1691       20; // to concentrate at brace wrapping, not line wrap due to column limit
1692   EXPECT_EQ("while (foo || bar ||\n"
1693             "       baz)\n"
1694             "{\n"
1695             "  quux();\n"
1696             "}",
1697             format("while(foo||bar||baz){quux();}", Style));
1698   EXPECT_EQ("switch (\n"
1699             "    foo = barbaz)\n"
1700             "{\n"
1701             "case quux:\n"
1702             "  return;\n"
1703             "}",
1704             format("switch(foo=barbaz){case quux:return;}", Style));
1705   EXPECT_EQ("try {\n"
1706             "  foo();\n"
1707             "} catch (\n"
1708             "    Exception &bar)\n"
1709             "{\n"
1710             "  baz();\n"
1711             "}",
1712             format("try{foo();}catch(Exception&bar){baz();}", Style));
1713   Style.ColumnLimit =
1714       40; // to concentrate at brace wrapping, not line wrap due to column limit
1715   EXPECT_EQ("try {\n"
1716             "  foo();\n"
1717             "} catch (Exception &bar) {\n"
1718             "  baz();\n"
1719             "}",
1720             format("try{foo();}catch(Exception&bar){baz();}", Style));
1721   Style.ColumnLimit =
1722       20; // to concentrate at brace wrapping, not line wrap due to column limit
1723 
1724   Style.BraceWrapping.BeforeElse = true;
1725   EXPECT_EQ(
1726       "if (foo) {\n"
1727       "  bar();\n"
1728       "}\n"
1729       "else if (baz ||\n"
1730       "         quux)\n"
1731       "{\n"
1732       "  foobar();\n"
1733       "}\n"
1734       "else {\n"
1735       "  barbaz();\n"
1736       "}",
1737       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
1738              Style));
1739 
1740   Style.BraceWrapping.BeforeCatch = true;
1741   EXPECT_EQ("try {\n"
1742             "  foo();\n"
1743             "}\n"
1744             "catch (...) {\n"
1745             "  baz();\n"
1746             "}",
1747             format("try{foo();}catch(...){baz();}", Style));
1748 }
1749 
1750 TEST_F(FormatTest, BeforeWhile) {
1751   FormatStyle Style = getLLVMStyle();
1752   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
1753 
1754   verifyFormat("do {\n"
1755                "  foo();\n"
1756                "} while (1);",
1757                Style);
1758   Style.BraceWrapping.BeforeWhile = true;
1759   verifyFormat("do {\n"
1760                "  foo();\n"
1761                "}\n"
1762                "while (1);",
1763                Style);
1764 }
1765 
1766 //===----------------------------------------------------------------------===//
1767 // Tests for classes, namespaces, etc.
1768 //===----------------------------------------------------------------------===//
1769 
1770 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
1771   verifyFormat("class A {};");
1772 }
1773 
1774 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
1775   verifyFormat("class A {\n"
1776                "public:\n"
1777                "public: // comment\n"
1778                "protected:\n"
1779                "private:\n"
1780                "  void f() {}\n"
1781                "};");
1782   verifyFormat("export class A {\n"
1783                "public:\n"
1784                "public: // comment\n"
1785                "protected:\n"
1786                "private:\n"
1787                "  void f() {}\n"
1788                "};");
1789   verifyGoogleFormat("class A {\n"
1790                      " public:\n"
1791                      " protected:\n"
1792                      " private:\n"
1793                      "  void f() {}\n"
1794                      "};");
1795   verifyGoogleFormat("export class A {\n"
1796                      " public:\n"
1797                      " protected:\n"
1798                      " private:\n"
1799                      "  void f() {}\n"
1800                      "};");
1801   verifyFormat("class A {\n"
1802                "public slots:\n"
1803                "  void f1() {}\n"
1804                "public Q_SLOTS:\n"
1805                "  void f2() {}\n"
1806                "protected slots:\n"
1807                "  void f3() {}\n"
1808                "protected Q_SLOTS:\n"
1809                "  void f4() {}\n"
1810                "private slots:\n"
1811                "  void f5() {}\n"
1812                "private Q_SLOTS:\n"
1813                "  void f6() {}\n"
1814                "signals:\n"
1815                "  void g1();\n"
1816                "Q_SIGNALS:\n"
1817                "  void g2();\n"
1818                "};");
1819 
1820   // Don't interpret 'signals' the wrong way.
1821   verifyFormat("signals.set();");
1822   verifyFormat("for (Signals signals : f()) {\n}");
1823   verifyFormat("{\n"
1824                "  signals.set(); // This needs indentation.\n"
1825                "}");
1826   verifyFormat("void f() {\n"
1827                "label:\n"
1828                "  signals.baz();\n"
1829                "}");
1830 }
1831 
1832 TEST_F(FormatTest, SeparatesLogicalBlocks) {
1833   EXPECT_EQ("class A {\n"
1834             "public:\n"
1835             "  void f();\n"
1836             "\n"
1837             "private:\n"
1838             "  void g() {}\n"
1839             "  // test\n"
1840             "protected:\n"
1841             "  int h;\n"
1842             "};",
1843             format("class A {\n"
1844                    "public:\n"
1845                    "void f();\n"
1846                    "private:\n"
1847                    "void g() {}\n"
1848                    "// test\n"
1849                    "protected:\n"
1850                    "int h;\n"
1851                    "};"));
1852   EXPECT_EQ("class A {\n"
1853             "protected:\n"
1854             "public:\n"
1855             "  void f();\n"
1856             "};",
1857             format("class A {\n"
1858                    "protected:\n"
1859                    "\n"
1860                    "public:\n"
1861                    "\n"
1862                    "  void f();\n"
1863                    "};"));
1864 
1865   // Even ensure proper spacing inside macros.
1866   EXPECT_EQ("#define B     \\\n"
1867             "  class A {   \\\n"
1868             "   protected: \\\n"
1869             "   public:    \\\n"
1870             "    void f(); \\\n"
1871             "  };",
1872             format("#define B     \\\n"
1873                    "  class A {   \\\n"
1874                    "   protected: \\\n"
1875                    "              \\\n"
1876                    "   public:    \\\n"
1877                    "              \\\n"
1878                    "    void f(); \\\n"
1879                    "  };",
1880                    getGoogleStyle()));
1881   // But don't remove empty lines after macros ending in access specifiers.
1882   EXPECT_EQ("#define A private:\n"
1883             "\n"
1884             "int i;",
1885             format("#define A         private:\n"
1886                    "\n"
1887                    "int              i;"));
1888 }
1889 
1890 TEST_F(FormatTest, FormatsClasses) {
1891   verifyFormat("class A : public B {};");
1892   verifyFormat("class A : public ::B {};");
1893 
1894   verifyFormat(
1895       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1896       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1897   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
1898                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1899                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1900   verifyFormat(
1901       "class A : public B, public C, public D, public E, public F {};");
1902   verifyFormat("class AAAAAAAAAAAA : public B,\n"
1903                "                     public C,\n"
1904                "                     public D,\n"
1905                "                     public E,\n"
1906                "                     public F,\n"
1907                "                     public G {};");
1908 
1909   verifyFormat("class\n"
1910                "    ReallyReallyLongClassName {\n"
1911                "  int i;\n"
1912                "};",
1913                getLLVMStyleWithColumns(32));
1914   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
1915                "                           aaaaaaaaaaaaaaaa> {};");
1916   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
1917                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
1918                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
1919   verifyFormat("template <class R, class C>\n"
1920                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
1921                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
1922   verifyFormat("class ::A::B {};");
1923 }
1924 
1925 TEST_F(FormatTest, BreakInheritanceStyle) {
1926   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
1927   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
1928       FormatStyle::BILS_BeforeComma;
1929   verifyFormat("class MyClass : public X {};",
1930                StyleWithInheritanceBreakBeforeComma);
1931   verifyFormat("class MyClass\n"
1932                "    : public X\n"
1933                "    , public Y {};",
1934                StyleWithInheritanceBreakBeforeComma);
1935   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
1936                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
1937                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
1938                StyleWithInheritanceBreakBeforeComma);
1939   verifyFormat("struct aaaaaaaaaaaaa\n"
1940                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
1941                "          aaaaaaaaaaaaaaaa> {};",
1942                StyleWithInheritanceBreakBeforeComma);
1943 
1944   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
1945   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
1946       FormatStyle::BILS_AfterColon;
1947   verifyFormat("class MyClass : public X {};",
1948                StyleWithInheritanceBreakAfterColon);
1949   verifyFormat("class MyClass : public X, public Y {};",
1950                StyleWithInheritanceBreakAfterColon);
1951   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
1952                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1953                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
1954                StyleWithInheritanceBreakAfterColon);
1955   verifyFormat("struct aaaaaaaaaaaaa :\n"
1956                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
1957                "        aaaaaaaaaaaaaaaa> {};",
1958                StyleWithInheritanceBreakAfterColon);
1959 }
1960 
1961 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
1962   verifyFormat("class A {\n} a, b;");
1963   verifyFormat("struct A {\n} a, b;");
1964   verifyFormat("union A {\n} a;");
1965 }
1966 
1967 TEST_F(FormatTest, FormatsEnum) {
1968   verifyFormat("enum {\n"
1969                "  Zero,\n"
1970                "  One = 1,\n"
1971                "  Two = One + 1,\n"
1972                "  Three = (One + Two),\n"
1973                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1974                "  Five = (One, Two, Three, Four, 5)\n"
1975                "};");
1976   verifyGoogleFormat("enum {\n"
1977                      "  Zero,\n"
1978                      "  One = 1,\n"
1979                      "  Two = One + 1,\n"
1980                      "  Three = (One + Two),\n"
1981                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1982                      "  Five = (One, Two, Three, Four, 5)\n"
1983                      "};");
1984   verifyFormat("enum Enum {};");
1985   verifyFormat("enum {};");
1986   verifyFormat("enum X E {} d;");
1987   verifyFormat("enum __attribute__((...)) E {} d;");
1988   verifyFormat("enum __declspec__((...)) E {} d;");
1989   verifyFormat("enum {\n"
1990                "  Bar = Foo<int, int>::value\n"
1991                "};",
1992                getLLVMStyleWithColumns(30));
1993 
1994   verifyFormat("enum ShortEnum { A, B, C };");
1995   verifyGoogleFormat("enum ShortEnum { A, B, C };");
1996 
1997   EXPECT_EQ("enum KeepEmptyLines {\n"
1998             "  ONE,\n"
1999             "\n"
2000             "  TWO,\n"
2001             "\n"
2002             "  THREE\n"
2003             "}",
2004             format("enum KeepEmptyLines {\n"
2005                    "  ONE,\n"
2006                    "\n"
2007                    "  TWO,\n"
2008                    "\n"
2009                    "\n"
2010                    "  THREE\n"
2011                    "}"));
2012   verifyFormat("enum E { // comment\n"
2013                "  ONE,\n"
2014                "  TWO\n"
2015                "};\n"
2016                "int i;");
2017 
2018   FormatStyle EightIndent = getLLVMStyle();
2019   EightIndent.IndentWidth = 8;
2020   verifyFormat("enum {\n"
2021                "        VOID,\n"
2022                "        CHAR,\n"
2023                "        SHORT,\n"
2024                "        INT,\n"
2025                "        LONG,\n"
2026                "        SIGNED,\n"
2027                "        UNSIGNED,\n"
2028                "        BOOL,\n"
2029                "        FLOAT,\n"
2030                "        DOUBLE,\n"
2031                "        COMPLEX\n"
2032                "};",
2033                EightIndent);
2034 
2035   // Not enums.
2036   verifyFormat("enum X f() {\n"
2037                "  a();\n"
2038                "  return 42;\n"
2039                "}");
2040   verifyFormat("enum X Type::f() {\n"
2041                "  a();\n"
2042                "  return 42;\n"
2043                "}");
2044   verifyFormat("enum ::X f() {\n"
2045                "  a();\n"
2046                "  return 42;\n"
2047                "}");
2048   verifyFormat("enum ns::X f() {\n"
2049                "  a();\n"
2050                "  return 42;\n"
2051                "}");
2052 }
2053 
2054 TEST_F(FormatTest, FormatsEnumsWithErrors) {
2055   verifyFormat("enum Type {\n"
2056                "  One = 0; // These semicolons should be commas.\n"
2057                "  Two = 1;\n"
2058                "};");
2059   verifyFormat("namespace n {\n"
2060                "enum Type {\n"
2061                "  One,\n"
2062                "  Two, // missing };\n"
2063                "  int i;\n"
2064                "}\n"
2065                "void g() {}");
2066 }
2067 
2068 TEST_F(FormatTest, FormatsEnumStruct) {
2069   verifyFormat("enum struct {\n"
2070                "  Zero,\n"
2071                "  One = 1,\n"
2072                "  Two = One + 1,\n"
2073                "  Three = (One + Two),\n"
2074                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2075                "  Five = (One, Two, Three, Four, 5)\n"
2076                "};");
2077   verifyFormat("enum struct Enum {};");
2078   verifyFormat("enum struct {};");
2079   verifyFormat("enum struct X E {} d;");
2080   verifyFormat("enum struct __attribute__((...)) E {} d;");
2081   verifyFormat("enum struct __declspec__((...)) E {} d;");
2082   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
2083 }
2084 
2085 TEST_F(FormatTest, FormatsEnumClass) {
2086   verifyFormat("enum class {\n"
2087                "  Zero,\n"
2088                "  One = 1,\n"
2089                "  Two = One + 1,\n"
2090                "  Three = (One + Two),\n"
2091                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2092                "  Five = (One, Two, Three, Four, 5)\n"
2093                "};");
2094   verifyFormat("enum class Enum {};");
2095   verifyFormat("enum class {};");
2096   verifyFormat("enum class X E {} d;");
2097   verifyFormat("enum class __attribute__((...)) E {} d;");
2098   verifyFormat("enum class __declspec__((...)) E {} d;");
2099   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
2100 }
2101 
2102 TEST_F(FormatTest, FormatsEnumTypes) {
2103   verifyFormat("enum X : int {\n"
2104                "  A, // Force multiple lines.\n"
2105                "  B\n"
2106                "};");
2107   verifyFormat("enum X : int { A, B };");
2108   verifyFormat("enum X : std::uint32_t { A, B };");
2109 }
2110 
2111 TEST_F(FormatTest, FormatsTypedefEnum) {
2112   FormatStyle Style = getLLVMStyle();
2113   Style.ColumnLimit = 40;
2114   verifyFormat("typedef enum {} EmptyEnum;");
2115   verifyFormat("typedef enum { A, B, C } ShortEnum;");
2116   verifyFormat("typedef enum {\n"
2117                "  ZERO = 0,\n"
2118                "  ONE = 1,\n"
2119                "  TWO = 2,\n"
2120                "  THREE = 3\n"
2121                "} LongEnum;",
2122                Style);
2123   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2124   Style.BraceWrapping.AfterEnum = true;
2125   verifyFormat("typedef enum {} EmptyEnum;");
2126   verifyFormat("typedef enum { A, B, C } ShortEnum;");
2127   verifyFormat("typedef enum\n"
2128                "{\n"
2129                "  ZERO = 0,\n"
2130                "  ONE = 1,\n"
2131                "  TWO = 2,\n"
2132                "  THREE = 3\n"
2133                "} LongEnum;",
2134                Style);
2135 }
2136 
2137 TEST_F(FormatTest, FormatsNSEnums) {
2138   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
2139   verifyGoogleFormat(
2140       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
2141   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
2142                      "  // Information about someDecentlyLongValue.\n"
2143                      "  someDecentlyLongValue,\n"
2144                      "  // Information about anotherDecentlyLongValue.\n"
2145                      "  anotherDecentlyLongValue,\n"
2146                      "  // Information about aThirdDecentlyLongValue.\n"
2147                      "  aThirdDecentlyLongValue\n"
2148                      "};");
2149   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
2150                      "  // Information about someDecentlyLongValue.\n"
2151                      "  someDecentlyLongValue,\n"
2152                      "  // Information about anotherDecentlyLongValue.\n"
2153                      "  anotherDecentlyLongValue,\n"
2154                      "  // Information about aThirdDecentlyLongValue.\n"
2155                      "  aThirdDecentlyLongValue\n"
2156                      "};");
2157   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
2158                      "  a = 1,\n"
2159                      "  b = 2,\n"
2160                      "  c = 3,\n"
2161                      "};");
2162   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
2163                      "  a = 1,\n"
2164                      "  b = 2,\n"
2165                      "  c = 3,\n"
2166                      "};");
2167   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
2168                      "  a = 1,\n"
2169                      "  b = 2,\n"
2170                      "  c = 3,\n"
2171                      "};");
2172   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
2173                      "  a = 1,\n"
2174                      "  b = 2,\n"
2175                      "  c = 3,\n"
2176                      "};");
2177 }
2178 
2179 TEST_F(FormatTest, FormatsBitfields) {
2180   verifyFormat("struct Bitfields {\n"
2181                "  unsigned sClass : 8;\n"
2182                "  unsigned ValueKind : 2;\n"
2183                "};");
2184   verifyFormat("struct A {\n"
2185                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
2186                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
2187                "};");
2188   verifyFormat("struct MyStruct {\n"
2189                "  uchar data;\n"
2190                "  uchar : 8;\n"
2191                "  uchar : 8;\n"
2192                "  uchar other;\n"
2193                "};");
2194   FormatStyle Style = getLLVMStyle();
2195   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
2196   verifyFormat("struct Bitfields {\n"
2197                "  unsigned sClass:8;\n"
2198                "  unsigned ValueKind:2;\n"
2199                "  uchar other;\n"
2200                "};",
2201                Style);
2202   verifyFormat("struct A {\n"
2203                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
2204                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
2205                "};",
2206                Style);
2207   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
2208   verifyFormat("struct Bitfields {\n"
2209                "  unsigned sClass :8;\n"
2210                "  unsigned ValueKind :2;\n"
2211                "  uchar other;\n"
2212                "};",
2213                Style);
2214   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
2215   verifyFormat("struct Bitfields {\n"
2216                "  unsigned sClass: 8;\n"
2217                "  unsigned ValueKind: 2;\n"
2218                "  uchar other;\n"
2219                "};",
2220                Style);
2221 }
2222 
2223 TEST_F(FormatTest, FormatsNamespaces) {
2224   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
2225   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
2226 
2227   verifyFormat("namespace some_namespace {\n"
2228                "class A {};\n"
2229                "void f() { f(); }\n"
2230                "}",
2231                LLVMWithNoNamespaceFix);
2232   verifyFormat("namespace N::inline D {\n"
2233                "class A {};\n"
2234                "void f() { f(); }\n"
2235                "}",
2236                LLVMWithNoNamespaceFix);
2237   verifyFormat("namespace N::inline D::E {\n"
2238                "class A {};\n"
2239                "void f() { f(); }\n"
2240                "}",
2241                LLVMWithNoNamespaceFix);
2242   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
2243                "class A {};\n"
2244                "void f() { f(); }\n"
2245                "}",
2246                LLVMWithNoNamespaceFix);
2247   verifyFormat("/* something */ namespace some_namespace {\n"
2248                "class A {};\n"
2249                "void f() { f(); }\n"
2250                "}",
2251                LLVMWithNoNamespaceFix);
2252   verifyFormat("namespace {\n"
2253                "class A {};\n"
2254                "void f() { f(); }\n"
2255                "}",
2256                LLVMWithNoNamespaceFix);
2257   verifyFormat("/* something */ namespace {\n"
2258                "class A {};\n"
2259                "void f() { f(); }\n"
2260                "}",
2261                LLVMWithNoNamespaceFix);
2262   verifyFormat("inline namespace X {\n"
2263                "class A {};\n"
2264                "void f() { f(); }\n"
2265                "}",
2266                LLVMWithNoNamespaceFix);
2267   verifyFormat("/* something */ inline namespace X {\n"
2268                "class A {};\n"
2269                "void f() { f(); }\n"
2270                "}",
2271                LLVMWithNoNamespaceFix);
2272   verifyFormat("export namespace X {\n"
2273                "class A {};\n"
2274                "void f() { f(); }\n"
2275                "}",
2276                LLVMWithNoNamespaceFix);
2277   verifyFormat("using namespace some_namespace;\n"
2278                "class A {};\n"
2279                "void f() { f(); }",
2280                LLVMWithNoNamespaceFix);
2281 
2282   // This code is more common than we thought; if we
2283   // layout this correctly the semicolon will go into
2284   // its own line, which is undesirable.
2285   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
2286   verifyFormat("namespace {\n"
2287                "class A {};\n"
2288                "};",
2289                LLVMWithNoNamespaceFix);
2290 
2291   verifyFormat("namespace {\n"
2292                "int SomeVariable = 0; // comment\n"
2293                "} // namespace",
2294                LLVMWithNoNamespaceFix);
2295   EXPECT_EQ("#ifndef HEADER_GUARD\n"
2296             "#define HEADER_GUARD\n"
2297             "namespace my_namespace {\n"
2298             "int i;\n"
2299             "} // my_namespace\n"
2300             "#endif // HEADER_GUARD",
2301             format("#ifndef HEADER_GUARD\n"
2302                    " #define HEADER_GUARD\n"
2303                    "   namespace my_namespace {\n"
2304                    "int i;\n"
2305                    "}    // my_namespace\n"
2306                    "#endif    // HEADER_GUARD",
2307                    LLVMWithNoNamespaceFix));
2308 
2309   EXPECT_EQ("namespace A::B {\n"
2310             "class C {};\n"
2311             "}",
2312             format("namespace A::B {\n"
2313                    "class C {};\n"
2314                    "}",
2315                    LLVMWithNoNamespaceFix));
2316 
2317   FormatStyle Style = getLLVMStyle();
2318   Style.NamespaceIndentation = FormatStyle::NI_All;
2319   EXPECT_EQ("namespace out {\n"
2320             "  int i;\n"
2321             "  namespace in {\n"
2322             "    int i;\n"
2323             "  } // namespace in\n"
2324             "} // namespace out",
2325             format("namespace out {\n"
2326                    "int i;\n"
2327                    "namespace in {\n"
2328                    "int i;\n"
2329                    "} // namespace in\n"
2330                    "} // namespace out",
2331                    Style));
2332 
2333   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2334   EXPECT_EQ("namespace out {\n"
2335             "int i;\n"
2336             "namespace in {\n"
2337             "  int i;\n"
2338             "} // namespace in\n"
2339             "} // namespace out",
2340             format("namespace out {\n"
2341                    "int i;\n"
2342                    "namespace in {\n"
2343                    "int i;\n"
2344                    "} // namespace in\n"
2345                    "} // namespace out",
2346                    Style));
2347 }
2348 
2349 TEST_F(FormatTest, NamespaceMacros) {
2350   FormatStyle Style = getLLVMStyle();
2351   Style.NamespaceMacros.push_back("TESTSUITE");
2352 
2353   verifyFormat("TESTSUITE(A) {\n"
2354                "int foo();\n"
2355                "} // TESTSUITE(A)",
2356                Style);
2357 
2358   verifyFormat("TESTSUITE(A, B) {\n"
2359                "int foo();\n"
2360                "} // TESTSUITE(A)",
2361                Style);
2362 
2363   // Properly indent according to NamespaceIndentation style
2364   Style.NamespaceIndentation = FormatStyle::NI_All;
2365   verifyFormat("TESTSUITE(A) {\n"
2366                "  int foo();\n"
2367                "} // TESTSUITE(A)",
2368                Style);
2369   verifyFormat("TESTSUITE(A) {\n"
2370                "  namespace B {\n"
2371                "    int foo();\n"
2372                "  } // namespace B\n"
2373                "} // TESTSUITE(A)",
2374                Style);
2375   verifyFormat("namespace A {\n"
2376                "  TESTSUITE(B) {\n"
2377                "    int foo();\n"
2378                "  } // TESTSUITE(B)\n"
2379                "} // namespace A",
2380                Style);
2381 
2382   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2383   verifyFormat("TESTSUITE(A) {\n"
2384                "TESTSUITE(B) {\n"
2385                "  int foo();\n"
2386                "} // TESTSUITE(B)\n"
2387                "} // TESTSUITE(A)",
2388                Style);
2389   verifyFormat("TESTSUITE(A) {\n"
2390                "namespace B {\n"
2391                "  int foo();\n"
2392                "} // namespace B\n"
2393                "} // TESTSUITE(A)",
2394                Style);
2395   verifyFormat("namespace A {\n"
2396                "TESTSUITE(B) {\n"
2397                "  int foo();\n"
2398                "} // TESTSUITE(B)\n"
2399                "} // namespace A",
2400                Style);
2401 
2402   // Properly merge namespace-macros blocks in CompactNamespaces mode
2403   Style.NamespaceIndentation = FormatStyle::NI_None;
2404   Style.CompactNamespaces = true;
2405   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
2406                "}} // TESTSUITE(A::B)",
2407                Style);
2408 
2409   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2410             "}} // TESTSUITE(out::in)",
2411             format("TESTSUITE(out) {\n"
2412                    "TESTSUITE(in) {\n"
2413                    "} // TESTSUITE(in)\n"
2414                    "} // TESTSUITE(out)",
2415                    Style));
2416 
2417   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2418             "}} // TESTSUITE(out::in)",
2419             format("TESTSUITE(out) {\n"
2420                    "TESTSUITE(in) {\n"
2421                    "} // TESTSUITE(in)\n"
2422                    "} // TESTSUITE(out)",
2423                    Style));
2424 
2425   // Do not merge different namespaces/macros
2426   EXPECT_EQ("namespace out {\n"
2427             "TESTSUITE(in) {\n"
2428             "} // TESTSUITE(in)\n"
2429             "} // namespace out",
2430             format("namespace out {\n"
2431                    "TESTSUITE(in) {\n"
2432                    "} // TESTSUITE(in)\n"
2433                    "} // namespace out",
2434                    Style));
2435   EXPECT_EQ("TESTSUITE(out) {\n"
2436             "namespace in {\n"
2437             "} // namespace in\n"
2438             "} // TESTSUITE(out)",
2439             format("TESTSUITE(out) {\n"
2440                    "namespace in {\n"
2441                    "} // namespace in\n"
2442                    "} // TESTSUITE(out)",
2443                    Style));
2444   Style.NamespaceMacros.push_back("FOOBAR");
2445   EXPECT_EQ("TESTSUITE(out) {\n"
2446             "FOOBAR(in) {\n"
2447             "} // FOOBAR(in)\n"
2448             "} // TESTSUITE(out)",
2449             format("TESTSUITE(out) {\n"
2450                    "FOOBAR(in) {\n"
2451                    "} // FOOBAR(in)\n"
2452                    "} // TESTSUITE(out)",
2453                    Style));
2454 }
2455 
2456 TEST_F(FormatTest, FormatsCompactNamespaces) {
2457   FormatStyle Style = getLLVMStyle();
2458   Style.CompactNamespaces = true;
2459   Style.NamespaceMacros.push_back("TESTSUITE");
2460 
2461   verifyFormat("namespace A { namespace B {\n"
2462                "}} // namespace A::B",
2463                Style);
2464 
2465   EXPECT_EQ("namespace out { namespace in {\n"
2466             "}} // namespace out::in",
2467             format("namespace out {\n"
2468                    "namespace in {\n"
2469                    "} // namespace in\n"
2470                    "} // namespace out",
2471                    Style));
2472 
2473   // Only namespaces which have both consecutive opening and end get compacted
2474   EXPECT_EQ("namespace out {\n"
2475             "namespace in1 {\n"
2476             "} // namespace in1\n"
2477             "namespace in2 {\n"
2478             "} // namespace in2\n"
2479             "} // namespace out",
2480             format("namespace out {\n"
2481                    "namespace in1 {\n"
2482                    "} // namespace in1\n"
2483                    "namespace in2 {\n"
2484                    "} // namespace in2\n"
2485                    "} // namespace out",
2486                    Style));
2487 
2488   EXPECT_EQ("namespace out {\n"
2489             "int i;\n"
2490             "namespace in {\n"
2491             "int j;\n"
2492             "} // namespace in\n"
2493             "int k;\n"
2494             "} // namespace out",
2495             format("namespace out { int i;\n"
2496                    "namespace in { int j; } // namespace in\n"
2497                    "int k; } // namespace out",
2498                    Style));
2499 
2500   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
2501             "}}} // namespace A::B::C\n",
2502             format("namespace A { namespace B {\n"
2503                    "namespace C {\n"
2504                    "}} // namespace B::C\n"
2505                    "} // namespace A\n",
2506                    Style));
2507 
2508   Style.ColumnLimit = 40;
2509   EXPECT_EQ("namespace aaaaaaaaaa {\n"
2510             "namespace bbbbbbbbbb {\n"
2511             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
2512             format("namespace aaaaaaaaaa {\n"
2513                    "namespace bbbbbbbbbb {\n"
2514                    "} // namespace bbbbbbbbbb\n"
2515                    "} // namespace aaaaaaaaaa",
2516                    Style));
2517 
2518   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
2519             "namespace cccccc {\n"
2520             "}}} // namespace aaaaaa::bbbbbb::cccccc",
2521             format("namespace aaaaaa {\n"
2522                    "namespace bbbbbb {\n"
2523                    "namespace cccccc {\n"
2524                    "} // namespace cccccc\n"
2525                    "} // namespace bbbbbb\n"
2526                    "} // namespace aaaaaa",
2527                    Style));
2528   Style.ColumnLimit = 80;
2529 
2530   // Extra semicolon after 'inner' closing brace prevents merging
2531   EXPECT_EQ("namespace out { namespace in {\n"
2532             "}; } // namespace out::in",
2533             format("namespace out {\n"
2534                    "namespace in {\n"
2535                    "}; // namespace in\n"
2536                    "} // namespace out",
2537                    Style));
2538 
2539   // Extra semicolon after 'outer' closing brace is conserved
2540   EXPECT_EQ("namespace out { namespace in {\n"
2541             "}}; // namespace out::in",
2542             format("namespace out {\n"
2543                    "namespace in {\n"
2544                    "} // namespace in\n"
2545                    "}; // namespace out",
2546                    Style));
2547 
2548   Style.NamespaceIndentation = FormatStyle::NI_All;
2549   EXPECT_EQ("namespace out { namespace in {\n"
2550             "  int i;\n"
2551             "}} // namespace out::in",
2552             format("namespace out {\n"
2553                    "namespace in {\n"
2554                    "int i;\n"
2555                    "} // namespace in\n"
2556                    "} // namespace out",
2557                    Style));
2558   EXPECT_EQ("namespace out { namespace mid {\n"
2559             "  namespace in {\n"
2560             "    int j;\n"
2561             "  } // namespace in\n"
2562             "  int k;\n"
2563             "}} // namespace out::mid",
2564             format("namespace out { namespace mid {\n"
2565                    "namespace in { int j; } // namespace in\n"
2566                    "int k; }} // namespace out::mid",
2567                    Style));
2568 
2569   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2570   EXPECT_EQ("namespace out { namespace in {\n"
2571             "  int i;\n"
2572             "}} // namespace out::in",
2573             format("namespace out {\n"
2574                    "namespace in {\n"
2575                    "int i;\n"
2576                    "} // namespace in\n"
2577                    "} // namespace out",
2578                    Style));
2579   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
2580             "  int i;\n"
2581             "}}} // namespace out::mid::in",
2582             format("namespace out {\n"
2583                    "namespace mid {\n"
2584                    "namespace in {\n"
2585                    "int i;\n"
2586                    "} // namespace in\n"
2587                    "} // namespace mid\n"
2588                    "} // namespace out",
2589                    Style));
2590 }
2591 
2592 TEST_F(FormatTest, FormatsExternC) {
2593   verifyFormat("extern \"C\" {\nint a;");
2594   verifyFormat("extern \"C\" {}");
2595   verifyFormat("extern \"C\" {\n"
2596                "int foo();\n"
2597                "}");
2598   verifyFormat("extern \"C\" int foo() {}");
2599   verifyFormat("extern \"C\" int foo();");
2600   verifyFormat("extern \"C\" int foo() {\n"
2601                "  int i = 42;\n"
2602                "  return i;\n"
2603                "}");
2604 
2605   FormatStyle Style = getLLVMStyle();
2606   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2607   Style.BraceWrapping.AfterFunction = true;
2608   verifyFormat("extern \"C\" int foo() {}", Style);
2609   verifyFormat("extern \"C\" int foo();", Style);
2610   verifyFormat("extern \"C\" int foo()\n"
2611                "{\n"
2612                "  int i = 42;\n"
2613                "  return i;\n"
2614                "}",
2615                Style);
2616 
2617   Style.BraceWrapping.AfterExternBlock = true;
2618   Style.BraceWrapping.SplitEmptyRecord = false;
2619   verifyFormat("extern \"C\"\n"
2620                "{}",
2621                Style);
2622   verifyFormat("extern \"C\"\n"
2623                "{\n"
2624                "  int foo();\n"
2625                "}",
2626                Style);
2627 }
2628 
2629 TEST_F(FormatTest, IndentExternBlockStyle) {
2630   FormatStyle Style = getLLVMStyle();
2631   Style.IndentWidth = 2;
2632 
2633   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
2634   verifyFormat("extern \"C\" { /*9*/\n}", Style);
2635   verifyFormat("extern \"C\" {\n"
2636                "  int foo10();\n"
2637                "}",
2638                Style);
2639 
2640   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
2641   verifyFormat("extern \"C\" { /*11*/\n}", Style);
2642   verifyFormat("extern \"C\" {\n"
2643                "int foo12();\n"
2644                "}",
2645                Style);
2646 
2647   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
2648   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2649   Style.BraceWrapping.AfterExternBlock = true;
2650   verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
2651   verifyFormat("extern \"C\"\n{\n"
2652                "  int foo14();\n"
2653                "}",
2654                Style);
2655 
2656   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
2657   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2658   Style.BraceWrapping.AfterExternBlock = false;
2659   verifyFormat("extern \"C\" { /*15*/\n}", Style);
2660   verifyFormat("extern \"C\" {\n"
2661                "int foo16();\n"
2662                "}",
2663                Style);
2664 }
2665 
2666 TEST_F(FormatTest, FormatsInlineASM) {
2667   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
2668   verifyFormat("asm(\"nop\" ::: \"memory\");");
2669   verifyFormat(
2670       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
2671       "    \"cpuid\\n\\t\"\n"
2672       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
2673       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
2674       "    : \"a\"(value));");
2675   EXPECT_EQ(
2676       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
2677       "  __asm {\n"
2678       "        mov     edx,[that] // vtable in edx\n"
2679       "        mov     eax,methodIndex\n"
2680       "        call    [edx][eax*4] // stdcall\n"
2681       "  }\n"
2682       "}",
2683       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
2684              "    __asm {\n"
2685              "        mov     edx,[that] // vtable in edx\n"
2686              "        mov     eax,methodIndex\n"
2687              "        call    [edx][eax*4] // stdcall\n"
2688              "    }\n"
2689              "}"));
2690   EXPECT_EQ("_asm {\n"
2691             "  xor eax, eax;\n"
2692             "  cpuid;\n"
2693             "}",
2694             format("_asm {\n"
2695                    "  xor eax, eax;\n"
2696                    "  cpuid;\n"
2697                    "}"));
2698   verifyFormat("void function() {\n"
2699                "  // comment\n"
2700                "  asm(\"\");\n"
2701                "}");
2702   EXPECT_EQ("__asm {\n"
2703             "}\n"
2704             "int i;",
2705             format("__asm   {\n"
2706                    "}\n"
2707                    "int   i;"));
2708 }
2709 
2710 TEST_F(FormatTest, FormatTryCatch) {
2711   verifyFormat("try {\n"
2712                "  throw a * b;\n"
2713                "} catch (int a) {\n"
2714                "  // Do nothing.\n"
2715                "} catch (...) {\n"
2716                "  exit(42);\n"
2717                "}");
2718 
2719   // Function-level try statements.
2720   verifyFormat("int f() try { return 4; } catch (...) {\n"
2721                "  return 5;\n"
2722                "}");
2723   verifyFormat("class A {\n"
2724                "  int a;\n"
2725                "  A() try : a(0) {\n"
2726                "  } catch (...) {\n"
2727                "    throw;\n"
2728                "  }\n"
2729                "};\n");
2730   verifyFormat("class A {\n"
2731                "  int a;\n"
2732                "  A() try : a(0), b{1} {\n"
2733                "  } catch (...) {\n"
2734                "    throw;\n"
2735                "  }\n"
2736                "};\n");
2737   verifyFormat("class A {\n"
2738                "  int a;\n"
2739                "  A() try : a(0), b{1}, c{2} {\n"
2740                "  } catch (...) {\n"
2741                "    throw;\n"
2742                "  }\n"
2743                "};\n");
2744   verifyFormat("class A {\n"
2745                "  int a;\n"
2746                "  A() try : a(0), b{1}, c{2} {\n"
2747                "    { // New scope.\n"
2748                "    }\n"
2749                "  } catch (...) {\n"
2750                "    throw;\n"
2751                "  }\n"
2752                "};\n");
2753 
2754   // Incomplete try-catch blocks.
2755   verifyIncompleteFormat("try {} catch (");
2756 }
2757 
2758 TEST_F(FormatTest, FormatTryAsAVariable) {
2759   verifyFormat("int try;");
2760   verifyFormat("int try, size;");
2761   verifyFormat("try = foo();");
2762   verifyFormat("if (try < size) {\n  return true;\n}");
2763 
2764   verifyFormat("int catch;");
2765   verifyFormat("int catch, size;");
2766   verifyFormat("catch = foo();");
2767   verifyFormat("if (catch < size) {\n  return true;\n}");
2768 
2769   FormatStyle Style = getLLVMStyle();
2770   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2771   Style.BraceWrapping.AfterFunction = true;
2772   Style.BraceWrapping.BeforeCatch = true;
2773   verifyFormat("try {\n"
2774                "  int bar = 1;\n"
2775                "}\n"
2776                "catch (...) {\n"
2777                "  int bar = 1;\n"
2778                "}",
2779                Style);
2780   verifyFormat("#if NO_EX\n"
2781                "try\n"
2782                "#endif\n"
2783                "{\n"
2784                "}\n"
2785                "#if NO_EX\n"
2786                "catch (...) {\n"
2787                "}",
2788                Style);
2789   verifyFormat("try /* abc */ {\n"
2790                "  int bar = 1;\n"
2791                "}\n"
2792                "catch (...) {\n"
2793                "  int bar = 1;\n"
2794                "}",
2795                Style);
2796   verifyFormat("try\n"
2797                "// abc\n"
2798                "{\n"
2799                "  int bar = 1;\n"
2800                "}\n"
2801                "catch (...) {\n"
2802                "  int bar = 1;\n"
2803                "}",
2804                Style);
2805 }
2806 
2807 TEST_F(FormatTest, FormatSEHTryCatch) {
2808   verifyFormat("__try {\n"
2809                "  int a = b * c;\n"
2810                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
2811                "  // Do nothing.\n"
2812                "}");
2813 
2814   verifyFormat("__try {\n"
2815                "  int a = b * c;\n"
2816                "} __finally {\n"
2817                "  // Do nothing.\n"
2818                "}");
2819 
2820   verifyFormat("DEBUG({\n"
2821                "  __try {\n"
2822                "  } __finally {\n"
2823                "  }\n"
2824                "});\n");
2825 }
2826 
2827 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
2828   verifyFormat("try {\n"
2829                "  f();\n"
2830                "} catch {\n"
2831                "  g();\n"
2832                "}");
2833   verifyFormat("try {\n"
2834                "  f();\n"
2835                "} catch (A a) MACRO(x) {\n"
2836                "  g();\n"
2837                "} catch (B b) MACRO(x) {\n"
2838                "  g();\n"
2839                "}");
2840 }
2841 
2842 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
2843   FormatStyle Style = getLLVMStyle();
2844   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
2845                           FormatStyle::BS_WebKit}) {
2846     Style.BreakBeforeBraces = BraceStyle;
2847     verifyFormat("try {\n"
2848                  "  // something\n"
2849                  "} catch (...) {\n"
2850                  "  // something\n"
2851                  "}",
2852                  Style);
2853   }
2854   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
2855   verifyFormat("try {\n"
2856                "  // something\n"
2857                "}\n"
2858                "catch (...) {\n"
2859                "  // something\n"
2860                "}",
2861                Style);
2862   verifyFormat("__try {\n"
2863                "  // something\n"
2864                "}\n"
2865                "__finally {\n"
2866                "  // something\n"
2867                "}",
2868                Style);
2869   verifyFormat("@try {\n"
2870                "  // something\n"
2871                "}\n"
2872                "@finally {\n"
2873                "  // something\n"
2874                "}",
2875                Style);
2876   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
2877   verifyFormat("try\n"
2878                "{\n"
2879                "  // something\n"
2880                "}\n"
2881                "catch (...)\n"
2882                "{\n"
2883                "  // something\n"
2884                "}",
2885                Style);
2886   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
2887   verifyFormat("try\n"
2888                "  {\n"
2889                "  // something white\n"
2890                "  }\n"
2891                "catch (...)\n"
2892                "  {\n"
2893                "  // something white\n"
2894                "  }",
2895                Style);
2896   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2897   verifyFormat("try\n"
2898                "  {\n"
2899                "    // something\n"
2900                "  }\n"
2901                "catch (...)\n"
2902                "  {\n"
2903                "    // something\n"
2904                "  }",
2905                Style);
2906   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2907   Style.BraceWrapping.BeforeCatch = true;
2908   verifyFormat("try {\n"
2909                "  // something\n"
2910                "}\n"
2911                "catch (...) {\n"
2912                "  // something\n"
2913                "}",
2914                Style);
2915 }
2916 
2917 TEST_F(FormatTest, StaticInitializers) {
2918   verifyFormat("static SomeClass SC = {1, 'a'};");
2919 
2920   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
2921                "    100000000, "
2922                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
2923 
2924   // Here, everything other than the "}" would fit on a line.
2925   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
2926                "    10000000000000000000000000};");
2927   EXPECT_EQ("S s = {a,\n"
2928             "\n"
2929             "       b};",
2930             format("S s = {\n"
2931                    "  a,\n"
2932                    "\n"
2933                    "  b\n"
2934                    "};"));
2935 
2936   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
2937   // line. However, the formatting looks a bit off and this probably doesn't
2938   // happen often in practice.
2939   verifyFormat("static int Variable[1] = {\n"
2940                "    {1000000000000000000000000000000000000}};",
2941                getLLVMStyleWithColumns(40));
2942 }
2943 
2944 TEST_F(FormatTest, DesignatedInitializers) {
2945   verifyFormat("const struct A a = {.a = 1, .b = 2};");
2946   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
2947                "                    .bbbbbbbbbb = 2,\n"
2948                "                    .cccccccccc = 3,\n"
2949                "                    .dddddddddd = 4,\n"
2950                "                    .eeeeeeeeee = 5};");
2951   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2952                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
2953                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
2954                "    .ccccccccccccccccccccccccccc = 3,\n"
2955                "    .ddddddddddddddddddddddddddd = 4,\n"
2956                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
2957 
2958   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
2959 
2960   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
2961   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
2962                "                    [2] = bbbbbbbbbb,\n"
2963                "                    [3] = cccccccccc,\n"
2964                "                    [4] = dddddddddd,\n"
2965                "                    [5] = eeeeeeeeee};");
2966   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2967                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2968                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
2969                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
2970                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
2971                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
2972 }
2973 
2974 TEST_F(FormatTest, NestedStaticInitializers) {
2975   verifyFormat("static A x = {{{}}};\n");
2976   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
2977                "               {init1, init2, init3, init4}}};",
2978                getLLVMStyleWithColumns(50));
2979 
2980   verifyFormat("somes Status::global_reps[3] = {\n"
2981                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2982                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2983                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
2984                getLLVMStyleWithColumns(60));
2985   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
2986                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2987                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2988                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
2989   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
2990                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
2991                "rect.fTop}};");
2992 
2993   verifyFormat(
2994       "SomeArrayOfSomeType a = {\n"
2995       "    {{1, 2, 3},\n"
2996       "     {1, 2, 3},\n"
2997       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
2998       "      333333333333333333333333333333},\n"
2999       "     {1, 2, 3},\n"
3000       "     {1, 2, 3}}};");
3001   verifyFormat(
3002       "SomeArrayOfSomeType a = {\n"
3003       "    {{1, 2, 3}},\n"
3004       "    {{1, 2, 3}},\n"
3005       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
3006       "      333333333333333333333333333333}},\n"
3007       "    {{1, 2, 3}},\n"
3008       "    {{1, 2, 3}}};");
3009 
3010   verifyFormat("struct {\n"
3011                "  unsigned bit;\n"
3012                "  const char *const name;\n"
3013                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
3014                "                 {kOsWin, \"Windows\"},\n"
3015                "                 {kOsLinux, \"Linux\"},\n"
3016                "                 {kOsCrOS, \"Chrome OS\"}};");
3017   verifyFormat("struct {\n"
3018                "  unsigned bit;\n"
3019                "  const char *const name;\n"
3020                "} kBitsToOs[] = {\n"
3021                "    {kOsMac, \"Mac\"},\n"
3022                "    {kOsWin, \"Windows\"},\n"
3023                "    {kOsLinux, \"Linux\"},\n"
3024                "    {kOsCrOS, \"Chrome OS\"},\n"
3025                "};");
3026 }
3027 
3028 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
3029   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3030                "                      \\\n"
3031                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
3032 }
3033 
3034 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
3035   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
3036                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
3037 
3038   // Do break defaulted and deleted functions.
3039   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
3040                "    default;",
3041                getLLVMStyleWithColumns(40));
3042   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
3043                "    delete;",
3044                getLLVMStyleWithColumns(40));
3045 }
3046 
3047 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
3048   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
3049                getLLVMStyleWithColumns(40));
3050   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
3051                getLLVMStyleWithColumns(40));
3052   EXPECT_EQ("#define Q                              \\\n"
3053             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
3054             "  \"aaaaaaaa.cpp\"",
3055             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
3056                    getLLVMStyleWithColumns(40)));
3057 }
3058 
3059 TEST_F(FormatTest, UnderstandsLinePPDirective) {
3060   EXPECT_EQ("# 123 \"A string literal\"",
3061             format("   #     123    \"A string literal\""));
3062 }
3063 
3064 TEST_F(FormatTest, LayoutUnknownPPDirective) {
3065   EXPECT_EQ("#;", format("#;"));
3066   verifyFormat("#\n;\n;\n;");
3067 }
3068 
3069 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
3070   EXPECT_EQ("#line 42 \"test\"\n",
3071             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
3072   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
3073                                     getLLVMStyleWithColumns(12)));
3074 }
3075 
3076 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
3077   EXPECT_EQ("#line 42 \"test\"",
3078             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
3079   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
3080 }
3081 
3082 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
3083   verifyFormat("#define A \\x20");
3084   verifyFormat("#define A \\ x20");
3085   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
3086   verifyFormat("#define A ''");
3087   verifyFormat("#define A ''qqq");
3088   verifyFormat("#define A `qqq");
3089   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
3090   EXPECT_EQ("const char *c = STRINGIFY(\n"
3091             "\\na : b);",
3092             format("const char * c = STRINGIFY(\n"
3093                    "\\na : b);"));
3094 
3095   verifyFormat("a\r\\");
3096   verifyFormat("a\v\\");
3097   verifyFormat("a\f\\");
3098 }
3099 
3100 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
3101   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
3102   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
3103   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
3104   // FIXME: We never break before the macro name.
3105   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
3106 
3107   verifyFormat("#define A A\n#define A A");
3108   verifyFormat("#define A(X) A\n#define A A");
3109 
3110   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
3111   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
3112 }
3113 
3114 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
3115   EXPECT_EQ("// somecomment\n"
3116             "#include \"a.h\"\n"
3117             "#define A(  \\\n"
3118             "    A, B)\n"
3119             "#include \"b.h\"\n"
3120             "// somecomment\n",
3121             format("  // somecomment\n"
3122                    "  #include \"a.h\"\n"
3123                    "#define A(A,\\\n"
3124                    "    B)\n"
3125                    "    #include \"b.h\"\n"
3126                    " // somecomment\n",
3127                    getLLVMStyleWithColumns(13)));
3128 }
3129 
3130 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
3131 
3132 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
3133   EXPECT_EQ("#define A    \\\n"
3134             "  c;         \\\n"
3135             "  e;\n"
3136             "f;",
3137             format("#define A c; e;\n"
3138                    "f;",
3139                    getLLVMStyleWithColumns(14)));
3140 }
3141 
3142 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
3143 
3144 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
3145   EXPECT_EQ("int x,\n"
3146             "#define A\n"
3147             "    y;",
3148             format("int x,\n#define A\ny;"));
3149 }
3150 
3151 TEST_F(FormatTest, HashInMacroDefinition) {
3152   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
3153   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
3154   verifyFormat("#define A  \\\n"
3155                "  {        \\\n"
3156                "    f(#c); \\\n"
3157                "  }",
3158                getLLVMStyleWithColumns(11));
3159 
3160   verifyFormat("#define A(X)         \\\n"
3161                "  void function##X()",
3162                getLLVMStyleWithColumns(22));
3163 
3164   verifyFormat("#define A(a, b, c)   \\\n"
3165                "  void a##b##c()",
3166                getLLVMStyleWithColumns(22));
3167 
3168   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
3169 }
3170 
3171 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
3172   EXPECT_EQ("#define A (x)", format("#define A (x)"));
3173   EXPECT_EQ("#define A(x)", format("#define A(x)"));
3174 
3175   FormatStyle Style = getLLVMStyle();
3176   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
3177   verifyFormat("#define true ((foo)1)", Style);
3178   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
3179   verifyFormat("#define false((foo)0)", Style);
3180 }
3181 
3182 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
3183   EXPECT_EQ("#define A b;", format("#define A \\\n"
3184                                    "          \\\n"
3185                                    "  b;",
3186                                    getLLVMStyleWithColumns(25)));
3187   EXPECT_EQ("#define A \\\n"
3188             "          \\\n"
3189             "  a;      \\\n"
3190             "  b;",
3191             format("#define A \\\n"
3192                    "          \\\n"
3193                    "  a;      \\\n"
3194                    "  b;",
3195                    getLLVMStyleWithColumns(11)));
3196   EXPECT_EQ("#define A \\\n"
3197             "  a;      \\\n"
3198             "          \\\n"
3199             "  b;",
3200             format("#define A \\\n"
3201                    "  a;      \\\n"
3202                    "          \\\n"
3203                    "  b;",
3204                    getLLVMStyleWithColumns(11)));
3205 }
3206 
3207 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
3208   verifyIncompleteFormat("#define A :");
3209   verifyFormat("#define SOMECASES  \\\n"
3210                "  case 1:          \\\n"
3211                "  case 2\n",
3212                getLLVMStyleWithColumns(20));
3213   verifyFormat("#define MACRO(a) \\\n"
3214                "  if (a)         \\\n"
3215                "    f();         \\\n"
3216                "  else           \\\n"
3217                "    g()",
3218                getLLVMStyleWithColumns(18));
3219   verifyFormat("#define A template <typename T>");
3220   verifyIncompleteFormat("#define STR(x) #x\n"
3221                          "f(STR(this_is_a_string_literal{));");
3222   verifyFormat("#pragma omp threadprivate( \\\n"
3223                "    y)), // expected-warning",
3224                getLLVMStyleWithColumns(28));
3225   verifyFormat("#d, = };");
3226   verifyFormat("#if \"a");
3227   verifyIncompleteFormat("({\n"
3228                          "#define b     \\\n"
3229                          "  }           \\\n"
3230                          "  a\n"
3231                          "a",
3232                          getLLVMStyleWithColumns(15));
3233   verifyFormat("#define A     \\\n"
3234                "  {           \\\n"
3235                "    {\n"
3236                "#define B     \\\n"
3237                "  }           \\\n"
3238                "  }",
3239                getLLVMStyleWithColumns(15));
3240   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
3241   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
3242   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
3243   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
3244 }
3245 
3246 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
3247   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
3248   EXPECT_EQ("class A : public QObject {\n"
3249             "  Q_OBJECT\n"
3250             "\n"
3251             "  A() {}\n"
3252             "};",
3253             format("class A  :  public QObject {\n"
3254                    "     Q_OBJECT\n"
3255                    "\n"
3256                    "  A() {\n}\n"
3257                    "}  ;"));
3258   EXPECT_EQ("MACRO\n"
3259             "/*static*/ int i;",
3260             format("MACRO\n"
3261                    " /*static*/ int   i;"));
3262   EXPECT_EQ("SOME_MACRO\n"
3263             "namespace {\n"
3264             "void f();\n"
3265             "} // namespace",
3266             format("SOME_MACRO\n"
3267                    "  namespace    {\n"
3268                    "void   f(  );\n"
3269                    "} // namespace"));
3270   // Only if the identifier contains at least 5 characters.
3271   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
3272   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
3273   // Only if everything is upper case.
3274   EXPECT_EQ("class A : public QObject {\n"
3275             "  Q_Object A() {}\n"
3276             "};",
3277             format("class A  :  public QObject {\n"
3278                    "     Q_Object\n"
3279                    "  A() {\n}\n"
3280                    "}  ;"));
3281 
3282   // Only if the next line can actually start an unwrapped line.
3283   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
3284             format("SOME_WEIRD_LOG_MACRO\n"
3285                    "<< SomeThing;"));
3286 
3287   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
3288                "(n, buffers))\n",
3289                getChromiumStyle(FormatStyle::LK_Cpp));
3290 
3291   // See PR41483
3292   EXPECT_EQ("/**/ FOO(a)\n"
3293             "FOO(b)",
3294             format("/**/ FOO(a)\n"
3295                    "FOO(b)"));
3296 }
3297 
3298 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
3299   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
3300             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
3301             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
3302             "class X {};\n"
3303             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
3304             "int *createScopDetectionPass() { return 0; }",
3305             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
3306                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
3307                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
3308                    "  class X {};\n"
3309                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
3310                    "  int *createScopDetectionPass() { return 0; }"));
3311   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
3312   // braces, so that inner block is indented one level more.
3313   EXPECT_EQ("int q() {\n"
3314             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3315             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3316             "  IPC_END_MESSAGE_MAP()\n"
3317             "}",
3318             format("int q() {\n"
3319                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3320                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3321                    "  IPC_END_MESSAGE_MAP()\n"
3322                    "}"));
3323 
3324   // Same inside macros.
3325   EXPECT_EQ("#define LIST(L) \\\n"
3326             "  L(A)          \\\n"
3327             "  L(B)          \\\n"
3328             "  L(C)",
3329             format("#define LIST(L) \\\n"
3330                    "  L(A) \\\n"
3331                    "  L(B) \\\n"
3332                    "  L(C)",
3333                    getGoogleStyle()));
3334 
3335   // These must not be recognized as macros.
3336   EXPECT_EQ("int q() {\n"
3337             "  f(x);\n"
3338             "  f(x) {}\n"
3339             "  f(x)->g();\n"
3340             "  f(x)->*g();\n"
3341             "  f(x).g();\n"
3342             "  f(x) = x;\n"
3343             "  f(x) += x;\n"
3344             "  f(x) -= x;\n"
3345             "  f(x) *= x;\n"
3346             "  f(x) /= x;\n"
3347             "  f(x) %= x;\n"
3348             "  f(x) &= x;\n"
3349             "  f(x) |= x;\n"
3350             "  f(x) ^= x;\n"
3351             "  f(x) >>= x;\n"
3352             "  f(x) <<= x;\n"
3353             "  f(x)[y].z();\n"
3354             "  LOG(INFO) << x;\n"
3355             "  ifstream(x) >> x;\n"
3356             "}\n",
3357             format("int q() {\n"
3358                    "  f(x)\n;\n"
3359                    "  f(x)\n {}\n"
3360                    "  f(x)\n->g();\n"
3361                    "  f(x)\n->*g();\n"
3362                    "  f(x)\n.g();\n"
3363                    "  f(x)\n = x;\n"
3364                    "  f(x)\n += x;\n"
3365                    "  f(x)\n -= x;\n"
3366                    "  f(x)\n *= x;\n"
3367                    "  f(x)\n /= x;\n"
3368                    "  f(x)\n %= x;\n"
3369                    "  f(x)\n &= x;\n"
3370                    "  f(x)\n |= x;\n"
3371                    "  f(x)\n ^= x;\n"
3372                    "  f(x)\n >>= x;\n"
3373                    "  f(x)\n <<= x;\n"
3374                    "  f(x)\n[y].z();\n"
3375                    "  LOG(INFO)\n << x;\n"
3376                    "  ifstream(x)\n >> x;\n"
3377                    "}\n"));
3378   EXPECT_EQ("int q() {\n"
3379             "  F(x)\n"
3380             "  if (1) {\n"
3381             "  }\n"
3382             "  F(x)\n"
3383             "  while (1) {\n"
3384             "  }\n"
3385             "  F(x)\n"
3386             "  G(x);\n"
3387             "  F(x)\n"
3388             "  try {\n"
3389             "    Q();\n"
3390             "  } catch (...) {\n"
3391             "  }\n"
3392             "}\n",
3393             format("int q() {\n"
3394                    "F(x)\n"
3395                    "if (1) {}\n"
3396                    "F(x)\n"
3397                    "while (1) {}\n"
3398                    "F(x)\n"
3399                    "G(x);\n"
3400                    "F(x)\n"
3401                    "try { Q(); } catch (...) {}\n"
3402                    "}\n"));
3403   EXPECT_EQ("class A {\n"
3404             "  A() : t(0) {}\n"
3405             "  A(int i) noexcept() : {}\n"
3406             "  A(X x)\n" // FIXME: function-level try blocks are broken.
3407             "  try : t(0) {\n"
3408             "  } catch (...) {\n"
3409             "  }\n"
3410             "};",
3411             format("class A {\n"
3412                    "  A()\n : t(0) {}\n"
3413                    "  A(int i)\n noexcept() : {}\n"
3414                    "  A(X x)\n"
3415                    "  try : t(0) {} catch (...) {}\n"
3416                    "};"));
3417   FormatStyle Style = getLLVMStyle();
3418   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3419   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
3420   Style.BraceWrapping.AfterFunction = true;
3421   EXPECT_EQ("void f()\n"
3422             "try\n"
3423             "{\n"
3424             "}",
3425             format("void f() try {\n"
3426                    "}",
3427                    Style));
3428   EXPECT_EQ("class SomeClass {\n"
3429             "public:\n"
3430             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3431             "};",
3432             format("class SomeClass {\n"
3433                    "public:\n"
3434                    "  SomeClass()\n"
3435                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3436                    "};"));
3437   EXPECT_EQ("class SomeClass {\n"
3438             "public:\n"
3439             "  SomeClass()\n"
3440             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3441             "};",
3442             format("class SomeClass {\n"
3443                    "public:\n"
3444                    "  SomeClass()\n"
3445                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3446                    "};",
3447                    getLLVMStyleWithColumns(40)));
3448 
3449   verifyFormat("MACRO(>)");
3450 
3451   // Some macros contain an implicit semicolon.
3452   Style = getLLVMStyle();
3453   Style.StatementMacros.push_back("FOO");
3454   verifyFormat("FOO(a) int b = 0;");
3455   verifyFormat("FOO(a)\n"
3456                "int b = 0;",
3457                Style);
3458   verifyFormat("FOO(a);\n"
3459                "int b = 0;",
3460                Style);
3461   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
3462                "int b = 0;",
3463                Style);
3464   verifyFormat("FOO()\n"
3465                "int b = 0;",
3466                Style);
3467   verifyFormat("FOO\n"
3468                "int b = 0;",
3469                Style);
3470   verifyFormat("void f() {\n"
3471                "  FOO(a)\n"
3472                "  return a;\n"
3473                "}",
3474                Style);
3475   verifyFormat("FOO(a)\n"
3476                "FOO(b)",
3477                Style);
3478   verifyFormat("int a = 0;\n"
3479                "FOO(b)\n"
3480                "int c = 0;",
3481                Style);
3482   verifyFormat("int a = 0;\n"
3483                "int x = FOO(a)\n"
3484                "int b = 0;",
3485                Style);
3486   verifyFormat("void foo(int a) { FOO(a) }\n"
3487                "uint32_t bar() {}",
3488                Style);
3489 }
3490 
3491 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
3492   verifyFormat("#define A \\\n"
3493                "  f({     \\\n"
3494                "    g();  \\\n"
3495                "  });",
3496                getLLVMStyleWithColumns(11));
3497 }
3498 
3499 TEST_F(FormatTest, IndentPreprocessorDirectives) {
3500   FormatStyle Style = getLLVMStyle();
3501   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
3502   Style.ColumnLimit = 40;
3503   verifyFormat("#ifdef _WIN32\n"
3504                "#define A 0\n"
3505                "#ifdef VAR2\n"
3506                "#define B 1\n"
3507                "#include <someheader.h>\n"
3508                "#define MACRO                          \\\n"
3509                "  some_very_long_func_aaaaaaaaaa();\n"
3510                "#endif\n"
3511                "#else\n"
3512                "#define A 1\n"
3513                "#endif",
3514                Style);
3515   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
3516   verifyFormat("#ifdef _WIN32\n"
3517                "#  define A 0\n"
3518                "#  ifdef VAR2\n"
3519                "#    define B 1\n"
3520                "#    include <someheader.h>\n"
3521                "#    define MACRO                      \\\n"
3522                "      some_very_long_func_aaaaaaaaaa();\n"
3523                "#  endif\n"
3524                "#else\n"
3525                "#  define A 1\n"
3526                "#endif",
3527                Style);
3528   verifyFormat("#if A\n"
3529                "#  define MACRO                        \\\n"
3530                "    void a(int x) {                    \\\n"
3531                "      b();                             \\\n"
3532                "      c();                             \\\n"
3533                "      d();                             \\\n"
3534                "      e();                             \\\n"
3535                "      f();                             \\\n"
3536                "    }\n"
3537                "#endif",
3538                Style);
3539   // Comments before include guard.
3540   verifyFormat("// file comment\n"
3541                "// file comment\n"
3542                "#ifndef HEADER_H\n"
3543                "#define HEADER_H\n"
3544                "code();\n"
3545                "#endif",
3546                Style);
3547   // Test with include guards.
3548   verifyFormat("#ifndef HEADER_H\n"
3549                "#define HEADER_H\n"
3550                "code();\n"
3551                "#endif",
3552                Style);
3553   // Include guards must have a #define with the same variable immediately
3554   // after #ifndef.
3555   verifyFormat("#ifndef NOT_GUARD\n"
3556                "#  define FOO\n"
3557                "code();\n"
3558                "#endif",
3559                Style);
3560 
3561   // Include guards must cover the entire file.
3562   verifyFormat("code();\n"
3563                "code();\n"
3564                "#ifndef NOT_GUARD\n"
3565                "#  define NOT_GUARD\n"
3566                "code();\n"
3567                "#endif",
3568                Style);
3569   verifyFormat("#ifndef NOT_GUARD\n"
3570                "#  define NOT_GUARD\n"
3571                "code();\n"
3572                "#endif\n"
3573                "code();",
3574                Style);
3575   // Test with trailing blank lines.
3576   verifyFormat("#ifndef HEADER_H\n"
3577                "#define HEADER_H\n"
3578                "code();\n"
3579                "#endif\n",
3580                Style);
3581   // Include guards don't have #else.
3582   verifyFormat("#ifndef NOT_GUARD\n"
3583                "#  define NOT_GUARD\n"
3584                "code();\n"
3585                "#else\n"
3586                "#endif",
3587                Style);
3588   verifyFormat("#ifndef NOT_GUARD\n"
3589                "#  define NOT_GUARD\n"
3590                "code();\n"
3591                "#elif FOO\n"
3592                "#endif",
3593                Style);
3594   // Non-identifier #define after potential include guard.
3595   verifyFormat("#ifndef FOO\n"
3596                "#  define 1\n"
3597                "#endif\n",
3598                Style);
3599   // #if closes past last non-preprocessor line.
3600   verifyFormat("#ifndef FOO\n"
3601                "#define FOO\n"
3602                "#if 1\n"
3603                "int i;\n"
3604                "#  define A 0\n"
3605                "#endif\n"
3606                "#endif\n",
3607                Style);
3608   // Don't crash if there is an #elif directive without a condition.
3609   verifyFormat("#if 1\n"
3610                "int x;\n"
3611                "#elif\n"
3612                "int y;\n"
3613                "#else\n"
3614                "int z;\n"
3615                "#endif",
3616                Style);
3617   // FIXME: This doesn't handle the case where there's code between the
3618   // #ifndef and #define but all other conditions hold. This is because when
3619   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
3620   // previous code line yet, so we can't detect it.
3621   EXPECT_EQ("#ifndef NOT_GUARD\n"
3622             "code();\n"
3623             "#define NOT_GUARD\n"
3624             "code();\n"
3625             "#endif",
3626             format("#ifndef NOT_GUARD\n"
3627                    "code();\n"
3628                    "#  define NOT_GUARD\n"
3629                    "code();\n"
3630                    "#endif",
3631                    Style));
3632   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
3633   // be outside an include guard. Examples are #pragma once and
3634   // #pragma GCC diagnostic, or anything else that does not change the meaning
3635   // of the file if it's included multiple times.
3636   EXPECT_EQ("#ifdef WIN32\n"
3637             "#  pragma once\n"
3638             "#endif\n"
3639             "#ifndef HEADER_H\n"
3640             "#  define HEADER_H\n"
3641             "code();\n"
3642             "#endif",
3643             format("#ifdef WIN32\n"
3644                    "#  pragma once\n"
3645                    "#endif\n"
3646                    "#ifndef HEADER_H\n"
3647                    "#define HEADER_H\n"
3648                    "code();\n"
3649                    "#endif",
3650                    Style));
3651   // FIXME: This does not detect when there is a single non-preprocessor line
3652   // in front of an include-guard-like structure where other conditions hold
3653   // because ScopedLineState hides the line.
3654   EXPECT_EQ("code();\n"
3655             "#ifndef HEADER_H\n"
3656             "#define HEADER_H\n"
3657             "code();\n"
3658             "#endif",
3659             format("code();\n"
3660                    "#ifndef HEADER_H\n"
3661                    "#  define HEADER_H\n"
3662                    "code();\n"
3663                    "#endif",
3664                    Style));
3665   // Keep comments aligned with #, otherwise indent comments normally. These
3666   // tests cannot use verifyFormat because messUp manipulates leading
3667   // whitespace.
3668   {
3669     const char *Expected = ""
3670                            "void f() {\n"
3671                            "#if 1\n"
3672                            "// Preprocessor aligned.\n"
3673                            "#  define A 0\n"
3674                            "  // Code. Separated by blank line.\n"
3675                            "\n"
3676                            "#  define B 0\n"
3677                            "  // Code. Not aligned with #\n"
3678                            "#  define C 0\n"
3679                            "#endif";
3680     const char *ToFormat = ""
3681                            "void f() {\n"
3682                            "#if 1\n"
3683                            "// Preprocessor aligned.\n"
3684                            "#  define A 0\n"
3685                            "// Code. Separated by blank line.\n"
3686                            "\n"
3687                            "#  define B 0\n"
3688                            "   // Code. Not aligned with #\n"
3689                            "#  define C 0\n"
3690                            "#endif";
3691     EXPECT_EQ(Expected, format(ToFormat, Style));
3692     EXPECT_EQ(Expected, format(Expected, Style));
3693   }
3694   // Keep block quotes aligned.
3695   {
3696     const char *Expected = ""
3697                            "void f() {\n"
3698                            "#if 1\n"
3699                            "/* Preprocessor aligned. */\n"
3700                            "#  define A 0\n"
3701                            "  /* Code. Separated by blank line. */\n"
3702                            "\n"
3703                            "#  define B 0\n"
3704                            "  /* Code. Not aligned with # */\n"
3705                            "#  define C 0\n"
3706                            "#endif";
3707     const char *ToFormat = ""
3708                            "void f() {\n"
3709                            "#if 1\n"
3710                            "/* Preprocessor aligned. */\n"
3711                            "#  define A 0\n"
3712                            "/* Code. Separated by blank line. */\n"
3713                            "\n"
3714                            "#  define B 0\n"
3715                            "   /* Code. Not aligned with # */\n"
3716                            "#  define C 0\n"
3717                            "#endif";
3718     EXPECT_EQ(Expected, format(ToFormat, Style));
3719     EXPECT_EQ(Expected, format(Expected, Style));
3720   }
3721   // Keep comments aligned with un-indented directives.
3722   {
3723     const char *Expected = ""
3724                            "void f() {\n"
3725                            "// Preprocessor aligned.\n"
3726                            "#define A 0\n"
3727                            "  // Code. Separated by blank line.\n"
3728                            "\n"
3729                            "#define B 0\n"
3730                            "  // Code. Not aligned with #\n"
3731                            "#define C 0\n";
3732     const char *ToFormat = ""
3733                            "void f() {\n"
3734                            "// Preprocessor aligned.\n"
3735                            "#define A 0\n"
3736                            "// Code. Separated by blank line.\n"
3737                            "\n"
3738                            "#define B 0\n"
3739                            "   // Code. Not aligned with #\n"
3740                            "#define C 0\n";
3741     EXPECT_EQ(Expected, format(ToFormat, Style));
3742     EXPECT_EQ(Expected, format(Expected, Style));
3743   }
3744   // Test AfterHash with tabs.
3745   {
3746     FormatStyle Tabbed = Style;
3747     Tabbed.UseTab = FormatStyle::UT_Always;
3748     Tabbed.IndentWidth = 8;
3749     Tabbed.TabWidth = 8;
3750     verifyFormat("#ifdef _WIN32\n"
3751                  "#\tdefine A 0\n"
3752                  "#\tifdef VAR2\n"
3753                  "#\t\tdefine B 1\n"
3754                  "#\t\tinclude <someheader.h>\n"
3755                  "#\t\tdefine MACRO          \\\n"
3756                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
3757                  "#\tendif\n"
3758                  "#else\n"
3759                  "#\tdefine A 1\n"
3760                  "#endif",
3761                  Tabbed);
3762   }
3763 
3764   // Regression test: Multiline-macro inside include guards.
3765   verifyFormat("#ifndef HEADER_H\n"
3766                "#define HEADER_H\n"
3767                "#define A()        \\\n"
3768                "  int i;           \\\n"
3769                "  int j;\n"
3770                "#endif // HEADER_H",
3771                getLLVMStyleWithColumns(20));
3772 
3773   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
3774   // Basic before hash indent tests
3775   verifyFormat("#ifdef _WIN32\n"
3776                "  #define A 0\n"
3777                "  #ifdef VAR2\n"
3778                "    #define B 1\n"
3779                "    #include <someheader.h>\n"
3780                "    #define MACRO                      \\\n"
3781                "      some_very_long_func_aaaaaaaaaa();\n"
3782                "  #endif\n"
3783                "#else\n"
3784                "  #define A 1\n"
3785                "#endif",
3786                Style);
3787   verifyFormat("#if A\n"
3788                "  #define MACRO                        \\\n"
3789                "    void a(int x) {                    \\\n"
3790                "      b();                             \\\n"
3791                "      c();                             \\\n"
3792                "      d();                             \\\n"
3793                "      e();                             \\\n"
3794                "      f();                             \\\n"
3795                "    }\n"
3796                "#endif",
3797                Style);
3798   // Keep comments aligned with indented directives. These
3799   // tests cannot use verifyFormat because messUp manipulates leading
3800   // whitespace.
3801   {
3802     const char *Expected = "void f() {\n"
3803                            "// Aligned to preprocessor.\n"
3804                            "#if 1\n"
3805                            "  // Aligned to code.\n"
3806                            "  int a;\n"
3807                            "  #if 1\n"
3808                            "    // Aligned to preprocessor.\n"
3809                            "    #define A 0\n"
3810                            "  // Aligned to code.\n"
3811                            "  int b;\n"
3812                            "  #endif\n"
3813                            "#endif\n"
3814                            "}";
3815     const char *ToFormat = "void f() {\n"
3816                            "// Aligned to preprocessor.\n"
3817                            "#if 1\n"
3818                            "// Aligned to code.\n"
3819                            "int a;\n"
3820                            "#if 1\n"
3821                            "// Aligned to preprocessor.\n"
3822                            "#define A 0\n"
3823                            "// Aligned to code.\n"
3824                            "int b;\n"
3825                            "#endif\n"
3826                            "#endif\n"
3827                            "}";
3828     EXPECT_EQ(Expected, format(ToFormat, Style));
3829     EXPECT_EQ(Expected, format(Expected, Style));
3830   }
3831   {
3832     const char *Expected = "void f() {\n"
3833                            "/* Aligned to preprocessor. */\n"
3834                            "#if 1\n"
3835                            "  /* Aligned to code. */\n"
3836                            "  int a;\n"
3837                            "  #if 1\n"
3838                            "    /* Aligned to preprocessor. */\n"
3839                            "    #define A 0\n"
3840                            "  /* Aligned to code. */\n"
3841                            "  int b;\n"
3842                            "  #endif\n"
3843                            "#endif\n"
3844                            "}";
3845     const char *ToFormat = "void f() {\n"
3846                            "/* Aligned to preprocessor. */\n"
3847                            "#if 1\n"
3848                            "/* Aligned to code. */\n"
3849                            "int a;\n"
3850                            "#if 1\n"
3851                            "/* Aligned to preprocessor. */\n"
3852                            "#define A 0\n"
3853                            "/* Aligned to code. */\n"
3854                            "int b;\n"
3855                            "#endif\n"
3856                            "#endif\n"
3857                            "}";
3858     EXPECT_EQ(Expected, format(ToFormat, Style));
3859     EXPECT_EQ(Expected, format(Expected, Style));
3860   }
3861 
3862   // Test single comment before preprocessor
3863   verifyFormat("// Comment\n"
3864                "\n"
3865                "#if 1\n"
3866                "#endif",
3867                Style);
3868 }
3869 
3870 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
3871   verifyFormat("{\n  { a #c; }\n}");
3872 }
3873 
3874 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
3875   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
3876             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
3877   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
3878             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
3879 }
3880 
3881 TEST_F(FormatTest, EscapedNewlines) {
3882   FormatStyle Narrow = getLLVMStyleWithColumns(11);
3883   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
3884             format("#define A \\\nint i;\\\n  int j;", Narrow));
3885   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
3886   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3887   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
3888   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
3889 
3890   FormatStyle AlignLeft = getLLVMStyle();
3891   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
3892   EXPECT_EQ("#define MACRO(x) \\\n"
3893             "private:         \\\n"
3894             "  int x(int a);\n",
3895             format("#define MACRO(x) \\\n"
3896                    "private:         \\\n"
3897                    "  int x(int a);\n",
3898                    AlignLeft));
3899 
3900   // CRLF line endings
3901   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
3902             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
3903   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
3904   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3905   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
3906   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
3907   EXPECT_EQ("#define MACRO(x) \\\r\n"
3908             "private:         \\\r\n"
3909             "  int x(int a);\r\n",
3910             format("#define MACRO(x) \\\r\n"
3911                    "private:         \\\r\n"
3912                    "  int x(int a);\r\n",
3913                    AlignLeft));
3914 
3915   FormatStyle DontAlign = getLLVMStyle();
3916   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
3917   DontAlign.MaxEmptyLinesToKeep = 3;
3918   // FIXME: can't use verifyFormat here because the newline before
3919   // "public:" is not inserted the first time it's reformatted
3920   EXPECT_EQ("#define A \\\n"
3921             "  class Foo { \\\n"
3922             "    void bar(); \\\n"
3923             "\\\n"
3924             "\\\n"
3925             "\\\n"
3926             "  public: \\\n"
3927             "    void baz(); \\\n"
3928             "  };",
3929             format("#define A \\\n"
3930                    "  class Foo { \\\n"
3931                    "    void bar(); \\\n"
3932                    "\\\n"
3933                    "\\\n"
3934                    "\\\n"
3935                    "  public: \\\n"
3936                    "    void baz(); \\\n"
3937                    "  };",
3938                    DontAlign));
3939 }
3940 
3941 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
3942   verifyFormat("#define A \\\n"
3943                "  int v(  \\\n"
3944                "      a); \\\n"
3945                "  int i;",
3946                getLLVMStyleWithColumns(11));
3947 }
3948 
3949 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
3950   EXPECT_EQ(
3951       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3952       "                      \\\n"
3953       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3954       "\n"
3955       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3956       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
3957       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
3958              "\\\n"
3959              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3960              "  \n"
3961              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3962              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
3963 }
3964 
3965 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
3966   EXPECT_EQ("int\n"
3967             "#define A\n"
3968             "    a;",
3969             format("int\n#define A\na;"));
3970   verifyFormat("functionCallTo(\n"
3971                "    someOtherFunction(\n"
3972                "        withSomeParameters, whichInSequence,\n"
3973                "        areLongerThanALine(andAnotherCall,\n"
3974                "#define A B\n"
3975                "                           withMoreParamters,\n"
3976                "                           whichStronglyInfluenceTheLayout),\n"
3977                "        andMoreParameters),\n"
3978                "    trailing);",
3979                getLLVMStyleWithColumns(69));
3980   verifyFormat("Foo::Foo()\n"
3981                "#ifdef BAR\n"
3982                "    : baz(0)\n"
3983                "#endif\n"
3984                "{\n"
3985                "}");
3986   verifyFormat("void f() {\n"
3987                "  if (true)\n"
3988                "#ifdef A\n"
3989                "    f(42);\n"
3990                "  x();\n"
3991                "#else\n"
3992                "    g();\n"
3993                "  x();\n"
3994                "#endif\n"
3995                "}");
3996   verifyFormat("void f(param1, param2,\n"
3997                "       param3,\n"
3998                "#ifdef A\n"
3999                "       param4(param5,\n"
4000                "#ifdef A1\n"
4001                "              param6,\n"
4002                "#ifdef A2\n"
4003                "              param7),\n"
4004                "#else\n"
4005                "              param8),\n"
4006                "       param9,\n"
4007                "#endif\n"
4008                "       param10,\n"
4009                "#endif\n"
4010                "       param11)\n"
4011                "#else\n"
4012                "       param12)\n"
4013                "#endif\n"
4014                "{\n"
4015                "  x();\n"
4016                "}",
4017                getLLVMStyleWithColumns(28));
4018   verifyFormat("#if 1\n"
4019                "int i;");
4020   verifyFormat("#if 1\n"
4021                "#endif\n"
4022                "#if 1\n"
4023                "#else\n"
4024                "#endif\n");
4025   verifyFormat("DEBUG({\n"
4026                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4027                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
4028                "});\n"
4029                "#if a\n"
4030                "#else\n"
4031                "#endif");
4032 
4033   verifyIncompleteFormat("void f(\n"
4034                          "#if A\n"
4035                          ");\n"
4036                          "#else\n"
4037                          "#endif");
4038 }
4039 
4040 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
4041   verifyFormat("#endif\n"
4042                "#if B");
4043 }
4044 
4045 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
4046   FormatStyle SingleLine = getLLVMStyle();
4047   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
4048   verifyFormat("#if 0\n"
4049                "#elif 1\n"
4050                "#endif\n"
4051                "void foo() {\n"
4052                "  if (test) foo2();\n"
4053                "}",
4054                SingleLine);
4055 }
4056 
4057 TEST_F(FormatTest, LayoutBlockInsideParens) {
4058   verifyFormat("functionCall({ int i; });");
4059   verifyFormat("functionCall({\n"
4060                "  int i;\n"
4061                "  int j;\n"
4062                "});");
4063   verifyFormat("functionCall(\n"
4064                "    {\n"
4065                "      int i;\n"
4066                "      int j;\n"
4067                "    },\n"
4068                "    aaaa, bbbb, cccc);");
4069   verifyFormat("functionA(functionB({\n"
4070                "            int i;\n"
4071                "            int j;\n"
4072                "          }),\n"
4073                "          aaaa, bbbb, cccc);");
4074   verifyFormat("functionCall(\n"
4075                "    {\n"
4076                "      int i;\n"
4077                "      int j;\n"
4078                "    },\n"
4079                "    aaaa, bbbb, // comment\n"
4080                "    cccc);");
4081   verifyFormat("functionA(functionB({\n"
4082                "            int i;\n"
4083                "            int j;\n"
4084                "          }),\n"
4085                "          aaaa, bbbb, // comment\n"
4086                "          cccc);");
4087   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
4088   verifyFormat("functionCall(aaaa, bbbb, {\n"
4089                "  int i;\n"
4090                "  int j;\n"
4091                "});");
4092   verifyFormat(
4093       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
4094       "    {\n"
4095       "      int i; // break\n"
4096       "    },\n"
4097       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4098       "                                     ccccccccccccccccc));");
4099   verifyFormat("DEBUG({\n"
4100                "  if (a)\n"
4101                "    f();\n"
4102                "});");
4103 }
4104 
4105 TEST_F(FormatTest, LayoutBlockInsideStatement) {
4106   EXPECT_EQ("SOME_MACRO { int i; }\n"
4107             "int i;",
4108             format("  SOME_MACRO  {int i;}  int i;"));
4109 }
4110 
4111 TEST_F(FormatTest, LayoutNestedBlocks) {
4112   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
4113                "  struct s {\n"
4114                "    int i;\n"
4115                "  };\n"
4116                "  s kBitsToOs[] = {{10}};\n"
4117                "  for (int i = 0; i < 10; ++i)\n"
4118                "    return;\n"
4119                "}");
4120   verifyFormat("call(parameter, {\n"
4121                "  something();\n"
4122                "  // Comment using all columns.\n"
4123                "  somethingelse();\n"
4124                "});",
4125                getLLVMStyleWithColumns(40));
4126   verifyFormat("DEBUG( //\n"
4127                "    { f(); }, a);");
4128   verifyFormat("DEBUG( //\n"
4129                "    {\n"
4130                "      f(); //\n"
4131                "    },\n"
4132                "    a);");
4133 
4134   EXPECT_EQ("call(parameter, {\n"
4135             "  something();\n"
4136             "  // Comment too\n"
4137             "  // looooooooooong.\n"
4138             "  somethingElse();\n"
4139             "});",
4140             format("call(parameter, {\n"
4141                    "  something();\n"
4142                    "  // Comment too looooooooooong.\n"
4143                    "  somethingElse();\n"
4144                    "});",
4145                    getLLVMStyleWithColumns(29)));
4146   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
4147   EXPECT_EQ("DEBUG({ // comment\n"
4148             "  int i;\n"
4149             "});",
4150             format("DEBUG({ // comment\n"
4151                    "int  i;\n"
4152                    "});"));
4153   EXPECT_EQ("DEBUG({\n"
4154             "  int i;\n"
4155             "\n"
4156             "  // comment\n"
4157             "  int j;\n"
4158             "});",
4159             format("DEBUG({\n"
4160                    "  int  i;\n"
4161                    "\n"
4162                    "  // comment\n"
4163                    "  int  j;\n"
4164                    "});"));
4165 
4166   verifyFormat("DEBUG({\n"
4167                "  if (a)\n"
4168                "    return;\n"
4169                "});");
4170   verifyGoogleFormat("DEBUG({\n"
4171                      "  if (a) return;\n"
4172                      "});");
4173   FormatStyle Style = getGoogleStyle();
4174   Style.ColumnLimit = 45;
4175   verifyFormat("Debug(\n"
4176                "    aaaaa,\n"
4177                "    {\n"
4178                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
4179                "    },\n"
4180                "    a);",
4181                Style);
4182 
4183   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
4184 
4185   verifyNoCrash("^{v^{a}}");
4186 }
4187 
4188 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
4189   EXPECT_EQ("#define MACRO()                     \\\n"
4190             "  Debug(aaa, /* force line break */ \\\n"
4191             "        {                           \\\n"
4192             "          int i;                    \\\n"
4193             "          int j;                    \\\n"
4194             "        })",
4195             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
4196                    "          {  int   i;  int  j;   })",
4197                    getGoogleStyle()));
4198 
4199   EXPECT_EQ("#define A                                       \\\n"
4200             "  [] {                                          \\\n"
4201             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
4202             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
4203             "  }",
4204             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
4205                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
4206                    getGoogleStyle()));
4207 }
4208 
4209 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
4210   EXPECT_EQ("{}", format("{}"));
4211   verifyFormat("enum E {};");
4212   verifyFormat("enum E {}");
4213   FormatStyle Style = getLLVMStyle();
4214   Style.SpaceInEmptyBlock = true;
4215   EXPECT_EQ("void f() { }", format("void f() {}", Style));
4216   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
4217   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
4218 }
4219 
4220 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
4221   FormatStyle Style = getLLVMStyle();
4222   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
4223   Style.MacroBlockEnd = "^[A-Z_]+_END$";
4224   verifyFormat("FOO_BEGIN\n"
4225                "  FOO_ENTRY\n"
4226                "FOO_END",
4227                Style);
4228   verifyFormat("FOO_BEGIN\n"
4229                "  NESTED_FOO_BEGIN\n"
4230                "    NESTED_FOO_ENTRY\n"
4231                "  NESTED_FOO_END\n"
4232                "FOO_END",
4233                Style);
4234   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
4235                "  int x;\n"
4236                "  x = 1;\n"
4237                "FOO_END(Baz)",
4238                Style);
4239 }
4240 
4241 //===----------------------------------------------------------------------===//
4242 // Line break tests.
4243 //===----------------------------------------------------------------------===//
4244 
4245 TEST_F(FormatTest, PreventConfusingIndents) {
4246   verifyFormat(
4247       "void f() {\n"
4248       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
4249       "                         parameter, parameter, parameter)),\n"
4250       "                     SecondLongCall(parameter));\n"
4251       "}");
4252   verifyFormat(
4253       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4254       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4255       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4256       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
4257   verifyFormat(
4258       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4259       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
4260       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
4261       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
4262   verifyFormat(
4263       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
4264       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
4265       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
4266       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
4267   verifyFormat("int a = bbbb && ccc &&\n"
4268                "        fffff(\n"
4269                "#define A Just forcing a new line\n"
4270                "            ddd);");
4271 }
4272 
4273 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
4274   verifyFormat(
4275       "bool aaaaaaa =\n"
4276       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
4277       "    bbbbbbbb();");
4278   verifyFormat(
4279       "bool aaaaaaa =\n"
4280       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
4281       "    bbbbbbbb();");
4282 
4283   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
4284                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
4285                "    ccccccccc == ddddddddddd;");
4286   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
4287                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
4288                "    ccccccccc == ddddddddddd;");
4289   verifyFormat(
4290       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
4291       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
4292       "    ccccccccc == ddddddddddd;");
4293 
4294   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
4295                "                 aaaaaa) &&\n"
4296                "         bbbbbb && cccccc;");
4297   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
4298                "                 aaaaaa) >>\n"
4299                "         bbbbbb;");
4300   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
4301                "    SourceMgr.getSpellingColumnNumber(\n"
4302                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
4303                "    1);");
4304 
4305   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4306                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
4307                "    cccccc) {\n}");
4308   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4309                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
4310                "              cccccc) {\n}");
4311   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4312                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
4313                "              cccccc) {\n}");
4314   verifyFormat("b = a &&\n"
4315                "    // Comment\n"
4316                "    b.c && d;");
4317 
4318   // If the LHS of a comparison is not a binary expression itself, the
4319   // additional linebreak confuses many people.
4320   verifyFormat(
4321       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4322       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
4323       "}");
4324   verifyFormat(
4325       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4326       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4327       "}");
4328   verifyFormat(
4329       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
4330       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4331       "}");
4332   verifyFormat(
4333       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4334       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
4335       "}");
4336   // Even explicit parentheses stress the precedence enough to make the
4337   // additional break unnecessary.
4338   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4339                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4340                "}");
4341   // This cases is borderline, but with the indentation it is still readable.
4342   verifyFormat(
4343       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4344       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4345       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
4346       "}",
4347       getLLVMStyleWithColumns(75));
4348 
4349   // If the LHS is a binary expression, we should still use the additional break
4350   // as otherwise the formatting hides the operator precedence.
4351   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4352                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4353                "    5) {\n"
4354                "}");
4355   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4356                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
4357                "    5) {\n"
4358                "}");
4359 
4360   FormatStyle OnePerLine = getLLVMStyle();
4361   OnePerLine.BinPackParameters = false;
4362   verifyFormat(
4363       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4364       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4365       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
4366       OnePerLine);
4367 
4368   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
4369                "                .aaa(aaaaaaaaaaaaa) *\n"
4370                "            aaaaaaa +\n"
4371                "        aaaaaaa;",
4372                getLLVMStyleWithColumns(40));
4373 }
4374 
4375 TEST_F(FormatTest, ExpressionIndentation) {
4376   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4377                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4378                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4379                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4380                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
4381                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
4382                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4383                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
4384                "                 ccccccccccccccccccccccccccccccccccccccccc;");
4385   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4386                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4387                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4388                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4389   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4390                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4391                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4392                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4393   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4394                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4395                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4396                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4397   verifyFormat("if () {\n"
4398                "} else if (aaaaa && bbbbb > // break\n"
4399                "                        ccccc) {\n"
4400                "}");
4401   verifyFormat("if () {\n"
4402                "} else if constexpr (aaaaa && bbbbb > // break\n"
4403                "                                  ccccc) {\n"
4404                "}");
4405   verifyFormat("if () {\n"
4406                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
4407                "                                  ccccc) {\n"
4408                "}");
4409   verifyFormat("if () {\n"
4410                "} else if (aaaaa &&\n"
4411                "           bbbbb > // break\n"
4412                "               ccccc &&\n"
4413                "           ddddd) {\n"
4414                "}");
4415 
4416   // Presence of a trailing comment used to change indentation of b.
4417   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
4418                "       b;\n"
4419                "return aaaaaaaaaaaaaaaaaaa +\n"
4420                "       b; //",
4421                getLLVMStyleWithColumns(30));
4422 }
4423 
4424 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
4425   // Not sure what the best system is here. Like this, the LHS can be found
4426   // immediately above an operator (everything with the same or a higher
4427   // indent). The RHS is aligned right of the operator and so compasses
4428   // everything until something with the same indent as the operator is found.
4429   // FIXME: Is this a good system?
4430   FormatStyle Style = getLLVMStyle();
4431   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
4432   verifyFormat(
4433       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4434       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4435       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4436       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4437       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4438       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4439       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4440       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4441       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
4442       Style);
4443   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4444                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4445                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4446                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4447                Style);
4448   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4449                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4450                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4451                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4452                Style);
4453   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4454                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4455                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4456                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4457                Style);
4458   verifyFormat("if () {\n"
4459                "} else if (aaaaa\n"
4460                "           && bbbbb // break\n"
4461                "                  > ccccc) {\n"
4462                "}",
4463                Style);
4464   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4465                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4466                Style);
4467   verifyFormat("return (a)\n"
4468                "       // comment\n"
4469                "       + b;",
4470                Style);
4471   verifyFormat(
4472       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4473       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4474       "             + cc;",
4475       Style);
4476 
4477   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4478                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4479                Style);
4480 
4481   // Forced by comments.
4482   verifyFormat(
4483       "unsigned ContentSize =\n"
4484       "    sizeof(int16_t)   // DWARF ARange version number\n"
4485       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4486       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4487       "    + sizeof(int8_t); // Segment Size (in bytes)");
4488 
4489   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
4490                "       == boost::fusion::at_c<1>(iiii).second;",
4491                Style);
4492 
4493   Style.ColumnLimit = 60;
4494   verifyFormat("zzzzzzzzzz\n"
4495                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4496                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
4497                Style);
4498 
4499   Style.ColumnLimit = 80;
4500   Style.IndentWidth = 4;
4501   Style.TabWidth = 4;
4502   Style.UseTab = FormatStyle::UT_Always;
4503   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4504   Style.AlignOperands = FormatStyle::OAS_DontAlign;
4505   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
4506             "\t&& (someOtherLongishConditionPart1\n"
4507             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
4508             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
4509                    "(someOtherLongishConditionPart1 || "
4510                    "someOtherEvenLongerNestedConditionPart2);",
4511                    Style));
4512 }
4513 
4514 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
4515   FormatStyle Style = getLLVMStyle();
4516   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
4517   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
4518 
4519   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4520                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4521                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4522                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4523                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4524                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4525                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4526                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4527                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
4528                Style);
4529   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4530                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4531                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4532                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4533                Style);
4534   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4535                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4536                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4537                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4538                Style);
4539   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4540                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4541                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4542                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4543                Style);
4544   verifyFormat("if () {\n"
4545                "} else if (aaaaa\n"
4546                "           && bbbbb // break\n"
4547                "                  > ccccc) {\n"
4548                "}",
4549                Style);
4550   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4551                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4552                Style);
4553   verifyFormat("return (a)\n"
4554                "     // comment\n"
4555                "     + b;",
4556                Style);
4557   verifyFormat(
4558       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4559       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4560       "           + cc;",
4561       Style);
4562   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
4563                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
4564                "                        : 3333333333333333;",
4565                Style);
4566   verifyFormat(
4567       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
4568       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
4569       "                                             : eeeeeeeeeeeeeeeeee)\n"
4570       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
4571       "                        : 3333333333333333;",
4572       Style);
4573   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4574                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4575                Style);
4576 
4577   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
4578                "    == boost::fusion::at_c<1>(iiii).second;",
4579                Style);
4580 
4581   Style.ColumnLimit = 60;
4582   verifyFormat("zzzzzzzzzzzzz\n"
4583                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4584                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
4585                Style);
4586 
4587   // Forced by comments.
4588   Style.ColumnLimit = 80;
4589   verifyFormat(
4590       "unsigned ContentSize\n"
4591       "    = sizeof(int16_t) // DWARF ARange version number\n"
4592       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4593       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4594       "    + sizeof(int8_t); // Segment Size (in bytes)",
4595       Style);
4596 
4597   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4598   verifyFormat(
4599       "unsigned ContentSize =\n"
4600       "    sizeof(int16_t)   // DWARF ARange version number\n"
4601       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4602       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4603       "    + sizeof(int8_t); // Segment Size (in bytes)",
4604       Style);
4605 
4606   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
4607   verifyFormat(
4608       "unsigned ContentSize =\n"
4609       "    sizeof(int16_t)   // DWARF ARange version number\n"
4610       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4611       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4612       "    + sizeof(int8_t); // Segment Size (in bytes)",
4613       Style);
4614 }
4615 
4616 TEST_F(FormatTest, EnforcedOperatorWraps) {
4617   // Here we'd like to wrap after the || operators, but a comment is forcing an
4618   // earlier wrap.
4619   verifyFormat("bool x = aaaaa //\n"
4620                "         || bbbbb\n"
4621                "         //\n"
4622                "         || cccc;");
4623 }
4624 
4625 TEST_F(FormatTest, NoOperandAlignment) {
4626   FormatStyle Style = getLLVMStyle();
4627   Style.AlignOperands = FormatStyle::OAS_DontAlign;
4628   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
4629                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4630                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4631                Style);
4632   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4633   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4634                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4635                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4636                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4637                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4638                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4639                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4640                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4641                "        > ccccccccccccccccccccccccccccccccccccccccc;",
4642                Style);
4643 
4644   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4645                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4646                "    + cc;",
4647                Style);
4648   verifyFormat("int a = aa\n"
4649                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4650                "        * cccccccccccccccccccccccccccccccccccc;\n",
4651                Style);
4652 
4653   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4654   verifyFormat("return (a > b\n"
4655                "    // comment1\n"
4656                "    // comment2\n"
4657                "    || c);",
4658                Style);
4659 }
4660 
4661 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
4662   FormatStyle Style = getLLVMStyle();
4663   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4664   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
4665                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4666                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4667                Style);
4668 }
4669 
4670 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
4671   FormatStyle Style = getLLVMStyle();
4672   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4673   Style.BinPackArguments = false;
4674   Style.ColumnLimit = 40;
4675   verifyFormat("void test() {\n"
4676                "  someFunction(\n"
4677                "      this + argument + is + quite\n"
4678                "      + long + so + it + gets + wrapped\n"
4679                "      + but + remains + bin - packed);\n"
4680                "}",
4681                Style);
4682   verifyFormat("void test() {\n"
4683                "  someFunction(arg1,\n"
4684                "               this + argument + is\n"
4685                "                   + quite + long + so\n"
4686                "                   + it + gets + wrapped\n"
4687                "                   + but + remains + bin\n"
4688                "                   - packed,\n"
4689                "               arg3);\n"
4690                "}",
4691                Style);
4692   verifyFormat("void test() {\n"
4693                "  someFunction(\n"
4694                "      arg1,\n"
4695                "      this + argument + has\n"
4696                "          + anotherFunc(nested,\n"
4697                "                        calls + whose\n"
4698                "                            + arguments\n"
4699                "                            + are + also\n"
4700                "                            + wrapped,\n"
4701                "                        in + addition)\n"
4702                "          + to + being + bin - packed,\n"
4703                "      arg3);\n"
4704                "}",
4705                Style);
4706 
4707   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
4708   verifyFormat("void test() {\n"
4709                "  someFunction(\n"
4710                "      arg1,\n"
4711                "      this + argument + has +\n"
4712                "          anotherFunc(nested,\n"
4713                "                      calls + whose +\n"
4714                "                          arguments +\n"
4715                "                          are + also +\n"
4716                "                          wrapped,\n"
4717                "                      in + addition) +\n"
4718                "          to + being + bin - packed,\n"
4719                "      arg3);\n"
4720                "}",
4721                Style);
4722 }
4723 
4724 TEST_F(FormatTest, ConstructorInitializers) {
4725   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
4726   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
4727                getLLVMStyleWithColumns(45));
4728   verifyFormat("Constructor()\n"
4729                "    : Inttializer(FitsOnTheLine) {}",
4730                getLLVMStyleWithColumns(44));
4731   verifyFormat("Constructor()\n"
4732                "    : Inttializer(FitsOnTheLine) {}",
4733                getLLVMStyleWithColumns(43));
4734 
4735   verifyFormat("template <typename T>\n"
4736                "Constructor() : Initializer(FitsOnTheLine) {}",
4737                getLLVMStyleWithColumns(45));
4738 
4739   verifyFormat(
4740       "SomeClass::Constructor()\n"
4741       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
4742 
4743   verifyFormat(
4744       "SomeClass::Constructor()\n"
4745       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4746       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
4747   verifyFormat(
4748       "SomeClass::Constructor()\n"
4749       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4750       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
4751   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4752                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4753                "    : aaaaaaaaaa(aaaaaa) {}");
4754 
4755   verifyFormat("Constructor()\n"
4756                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4757                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4758                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4759                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
4760 
4761   verifyFormat("Constructor()\n"
4762                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4763                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4764 
4765   verifyFormat("Constructor(int Parameter = 0)\n"
4766                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
4767                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
4768   verifyFormat("Constructor()\n"
4769                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
4770                "}",
4771                getLLVMStyleWithColumns(60));
4772   verifyFormat("Constructor()\n"
4773                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4774                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
4775 
4776   // Here a line could be saved by splitting the second initializer onto two
4777   // lines, but that is not desirable.
4778   verifyFormat("Constructor()\n"
4779                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
4780                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
4781                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4782 
4783   FormatStyle OnePerLine = getLLVMStyle();
4784   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4785   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
4786   verifyFormat("SomeClass::Constructor()\n"
4787                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4788                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4789                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4790                OnePerLine);
4791   verifyFormat("SomeClass::Constructor()\n"
4792                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
4793                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4794                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4795                OnePerLine);
4796   verifyFormat("MyClass::MyClass(int var)\n"
4797                "    : some_var_(var),            // 4 space indent\n"
4798                "      some_other_var_(var + 1) { // lined up\n"
4799                "}",
4800                OnePerLine);
4801   verifyFormat("Constructor()\n"
4802                "    : aaaaa(aaaaaa),\n"
4803                "      aaaaa(aaaaaa),\n"
4804                "      aaaaa(aaaaaa),\n"
4805                "      aaaaa(aaaaaa),\n"
4806                "      aaaaa(aaaaaa) {}",
4807                OnePerLine);
4808   verifyFormat("Constructor()\n"
4809                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
4810                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
4811                OnePerLine);
4812   OnePerLine.BinPackParameters = false;
4813   verifyFormat(
4814       "Constructor()\n"
4815       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4816       "          aaaaaaaaaaa().aaa(),\n"
4817       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4818       OnePerLine);
4819   OnePerLine.ColumnLimit = 60;
4820   verifyFormat("Constructor()\n"
4821                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4822                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
4823                OnePerLine);
4824 
4825   EXPECT_EQ("Constructor()\n"
4826             "    : // Comment forcing unwanted break.\n"
4827             "      aaaa(aaaa) {}",
4828             format("Constructor() :\n"
4829                    "    // Comment forcing unwanted break.\n"
4830                    "    aaaa(aaaa) {}"));
4831 }
4832 
4833 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
4834   FormatStyle Style = getLLVMStyle();
4835   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4836   Style.ColumnLimit = 60;
4837   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4838   Style.AllowAllConstructorInitializersOnNextLine = true;
4839   Style.BinPackParameters = false;
4840 
4841   for (int i = 0; i < 4; ++i) {
4842     // Test all combinations of parameters that should not have an effect.
4843     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
4844     Style.AllowAllArgumentsOnNextLine = i & 2;
4845 
4846     Style.AllowAllConstructorInitializersOnNextLine = true;
4847     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4848     verifyFormat("Constructor()\n"
4849                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4850                  Style);
4851     verifyFormat("Constructor() : a(a), b(b) {}", Style);
4852 
4853     Style.AllowAllConstructorInitializersOnNextLine = false;
4854     verifyFormat("Constructor()\n"
4855                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4856                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4857                  Style);
4858     verifyFormat("Constructor() : a(a), b(b) {}", Style);
4859 
4860     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
4861     Style.AllowAllConstructorInitializersOnNextLine = true;
4862     verifyFormat("Constructor()\n"
4863                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4864                  Style);
4865 
4866     Style.AllowAllConstructorInitializersOnNextLine = false;
4867     verifyFormat("Constructor()\n"
4868                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4869                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4870                  Style);
4871 
4872     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4873     Style.AllowAllConstructorInitializersOnNextLine = true;
4874     verifyFormat("Constructor() :\n"
4875                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4876                  Style);
4877 
4878     Style.AllowAllConstructorInitializersOnNextLine = false;
4879     verifyFormat("Constructor() :\n"
4880                  "    aaaaaaaaaaaaaaaaaa(a),\n"
4881                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4882                  Style);
4883   }
4884 
4885   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
4886   // AllowAllConstructorInitializersOnNextLine in all
4887   // BreakConstructorInitializers modes
4888   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4889   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4890   Style.AllowAllConstructorInitializersOnNextLine = false;
4891   verifyFormat("SomeClassWithALongName::Constructor(\n"
4892                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
4893                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4894                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4895                Style);
4896 
4897   Style.AllowAllConstructorInitializersOnNextLine = true;
4898   verifyFormat("SomeClassWithALongName::Constructor(\n"
4899                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4900                "    int bbbbbbbbbbbbb,\n"
4901                "    int cccccccccccccccc)\n"
4902                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4903                Style);
4904 
4905   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4906   Style.AllowAllConstructorInitializersOnNextLine = false;
4907   verifyFormat("SomeClassWithALongName::Constructor(\n"
4908                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4909                "    int bbbbbbbbbbbbb)\n"
4910                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4911                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4912                Style);
4913 
4914   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
4915 
4916   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4917   verifyFormat("SomeClassWithALongName::Constructor(\n"
4918                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
4919                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4920                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4921                Style);
4922 
4923   Style.AllowAllConstructorInitializersOnNextLine = true;
4924   verifyFormat("SomeClassWithALongName::Constructor(\n"
4925                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4926                "    int bbbbbbbbbbbbb,\n"
4927                "    int cccccccccccccccc)\n"
4928                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4929                Style);
4930 
4931   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4932   Style.AllowAllConstructorInitializersOnNextLine = false;
4933   verifyFormat("SomeClassWithALongName::Constructor(\n"
4934                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4935                "    int bbbbbbbbbbbbb)\n"
4936                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4937                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4938                Style);
4939 
4940   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4941   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4942   verifyFormat("SomeClassWithALongName::Constructor(\n"
4943                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
4944                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
4945                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4946                Style);
4947 
4948   Style.AllowAllConstructorInitializersOnNextLine = true;
4949   verifyFormat("SomeClassWithALongName::Constructor(\n"
4950                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4951                "    int bbbbbbbbbbbbb,\n"
4952                "    int cccccccccccccccc) :\n"
4953                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4954                Style);
4955 
4956   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4957   Style.AllowAllConstructorInitializersOnNextLine = false;
4958   verifyFormat("SomeClassWithALongName::Constructor(\n"
4959                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4960                "    int bbbbbbbbbbbbb) :\n"
4961                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
4962                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4963                Style);
4964 }
4965 
4966 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
4967   FormatStyle Style = getLLVMStyle();
4968   Style.ColumnLimit = 60;
4969   Style.BinPackArguments = false;
4970   for (int i = 0; i < 4; ++i) {
4971     // Test all combinations of parameters that should not have an effect.
4972     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
4973     Style.AllowAllConstructorInitializersOnNextLine = i & 2;
4974 
4975     Style.AllowAllArgumentsOnNextLine = true;
4976     verifyFormat("void foo() {\n"
4977                  "  FunctionCallWithReallyLongName(\n"
4978                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
4979                  "}",
4980                  Style);
4981     Style.AllowAllArgumentsOnNextLine = false;
4982     verifyFormat("void foo() {\n"
4983                  "  FunctionCallWithReallyLongName(\n"
4984                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4985                  "      bbbbbbbbbbbb);\n"
4986                  "}",
4987                  Style);
4988 
4989     Style.AllowAllArgumentsOnNextLine = true;
4990     verifyFormat("void foo() {\n"
4991                  "  auto VariableWithReallyLongName = {\n"
4992                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
4993                  "}",
4994                  Style);
4995     Style.AllowAllArgumentsOnNextLine = false;
4996     verifyFormat("void foo() {\n"
4997                  "  auto VariableWithReallyLongName = {\n"
4998                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4999                  "      bbbbbbbbbbbb};\n"
5000                  "}",
5001                  Style);
5002   }
5003 
5004   // This parameter should not affect declarations.
5005   Style.BinPackParameters = false;
5006   Style.AllowAllArgumentsOnNextLine = false;
5007   Style.AllowAllParametersOfDeclarationOnNextLine = true;
5008   verifyFormat("void FunctionCallWithReallyLongName(\n"
5009                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
5010                Style);
5011   Style.AllowAllParametersOfDeclarationOnNextLine = false;
5012   verifyFormat("void FunctionCallWithReallyLongName(\n"
5013                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
5014                "    int bbbbbbbbbbbb);",
5015                Style);
5016 }
5017 
5018 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
5019   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
5020   // and BAS_Align.
5021   auto Style = getLLVMStyle();
5022   Style.ColumnLimit = 35;
5023   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
5024                     "void functionDecl(int A, int B, int C);";
5025   Style.AllowAllArgumentsOnNextLine = false;
5026   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5027   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5028                       "    paramC);\n"
5029                       "void functionDecl(int A, int B,\n"
5030                       "    int C);"),
5031             format(Input, Style));
5032   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
5033   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5034                       "             paramC);\n"
5035                       "void functionDecl(int A, int B,\n"
5036                       "                  int C);"),
5037             format(Input, Style));
5038   // However, BAS_AlwaysBreak should take precedence over
5039   // AllowAllArgumentsOnNextLine.
5040   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
5041   EXPECT_EQ(StringRef("functionCall(\n"
5042                       "    paramA, paramB, paramC);\n"
5043                       "void functionDecl(\n"
5044                       "    int A, int B, int C);"),
5045             format(Input, Style));
5046 
5047   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
5048   // first argument.
5049   Style.AllowAllArgumentsOnNextLine = true;
5050   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
5051   EXPECT_EQ(StringRef("functionCall(\n"
5052                       "    paramA, paramB, paramC);\n"
5053                       "void functionDecl(\n"
5054                       "    int A, int B, int C);"),
5055             format(Input, Style));
5056   // It wouldn't fit on one line with aligned parameters so this setting
5057   // doesn't change anything for BAS_Align.
5058   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
5059   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5060                       "             paramC);\n"
5061                       "void functionDecl(int A, int B,\n"
5062                       "                  int C);"),
5063             format(Input, Style));
5064   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5065   EXPECT_EQ(StringRef("functionCall(\n"
5066                       "    paramA, paramB, paramC);\n"
5067                       "void functionDecl(\n"
5068                       "    int A, int B, int C);"),
5069             format(Input, Style));
5070 }
5071 
5072 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
5073   FormatStyle Style = getLLVMStyle();
5074   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
5075 
5076   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
5077   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
5078                getStyleWithColumns(Style, 45));
5079   verifyFormat("Constructor() :\n"
5080                "    Initializer(FitsOnTheLine) {}",
5081                getStyleWithColumns(Style, 44));
5082   verifyFormat("Constructor() :\n"
5083                "    Initializer(FitsOnTheLine) {}",
5084                getStyleWithColumns(Style, 43));
5085 
5086   verifyFormat("template <typename T>\n"
5087                "Constructor() : Initializer(FitsOnTheLine) {}",
5088                getStyleWithColumns(Style, 50));
5089   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5090   verifyFormat(
5091       "SomeClass::Constructor() :\n"
5092       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5093       Style);
5094 
5095   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
5096   verifyFormat(
5097       "SomeClass::Constructor() :\n"
5098       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5099       Style);
5100 
5101   verifyFormat(
5102       "SomeClass::Constructor() :\n"
5103       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5104       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5105       Style);
5106   verifyFormat(
5107       "SomeClass::Constructor() :\n"
5108       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5109       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5110       Style);
5111   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5112                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
5113                "    aaaaaaaaaa(aaaaaa) {}",
5114                Style);
5115 
5116   verifyFormat("Constructor() :\n"
5117                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5118                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5119                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5120                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
5121                Style);
5122 
5123   verifyFormat("Constructor() :\n"
5124                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5125                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5126                Style);
5127 
5128   verifyFormat("Constructor(int Parameter = 0) :\n"
5129                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
5130                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
5131                Style);
5132   verifyFormat("Constructor() :\n"
5133                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
5134                "}",
5135                getStyleWithColumns(Style, 60));
5136   verifyFormat("Constructor() :\n"
5137                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5138                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
5139                Style);
5140 
5141   // Here a line could be saved by splitting the second initializer onto two
5142   // lines, but that is not desirable.
5143   verifyFormat("Constructor() :\n"
5144                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
5145                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
5146                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5147                Style);
5148 
5149   FormatStyle OnePerLine = Style;
5150   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5151   OnePerLine.AllowAllConstructorInitializersOnNextLine = false;
5152   verifyFormat("SomeClass::Constructor() :\n"
5153                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5154                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5155                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5156                OnePerLine);
5157   verifyFormat("SomeClass::Constructor() :\n"
5158                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
5159                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5160                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5161                OnePerLine);
5162   verifyFormat("MyClass::MyClass(int var) :\n"
5163                "    some_var_(var),            // 4 space indent\n"
5164                "    some_other_var_(var + 1) { // lined up\n"
5165                "}",
5166                OnePerLine);
5167   verifyFormat("Constructor() :\n"
5168                "    aaaaa(aaaaaa),\n"
5169                "    aaaaa(aaaaaa),\n"
5170                "    aaaaa(aaaaaa),\n"
5171                "    aaaaa(aaaaaa),\n"
5172                "    aaaaa(aaaaaa) {}",
5173                OnePerLine);
5174   verifyFormat("Constructor() :\n"
5175                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
5176                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
5177                OnePerLine);
5178   OnePerLine.BinPackParameters = false;
5179   verifyFormat("Constructor() :\n"
5180                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5181                "        aaaaaaaaaaa().aaa(),\n"
5182                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5183                OnePerLine);
5184   OnePerLine.ColumnLimit = 60;
5185   verifyFormat("Constructor() :\n"
5186                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
5187                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
5188                OnePerLine);
5189 
5190   EXPECT_EQ("Constructor() :\n"
5191             "    // Comment forcing unwanted break.\n"
5192             "    aaaa(aaaa) {}",
5193             format("Constructor() :\n"
5194                    "    // Comment forcing unwanted break.\n"
5195                    "    aaaa(aaaa) {}",
5196                    Style));
5197 
5198   Style.ColumnLimit = 0;
5199   verifyFormat("SomeClass::Constructor() :\n"
5200                "    a(a) {}",
5201                Style);
5202   verifyFormat("SomeClass::Constructor() noexcept :\n"
5203                "    a(a) {}",
5204                Style);
5205   verifyFormat("SomeClass::Constructor() :\n"
5206                "    a(a), b(b), c(c) {}",
5207                Style);
5208   verifyFormat("SomeClass::Constructor() :\n"
5209                "    a(a) {\n"
5210                "  foo();\n"
5211                "  bar();\n"
5212                "}",
5213                Style);
5214 
5215   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
5216   verifyFormat("SomeClass::Constructor() :\n"
5217                "    a(a), b(b), c(c) {\n"
5218                "}",
5219                Style);
5220   verifyFormat("SomeClass::Constructor() :\n"
5221                "    a(a) {\n"
5222                "}",
5223                Style);
5224 
5225   Style.ColumnLimit = 80;
5226   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
5227   Style.ConstructorInitializerIndentWidth = 2;
5228   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
5229   verifyFormat("SomeClass::Constructor() :\n"
5230                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5231                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
5232                Style);
5233 
5234   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
5235   // well
5236   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
5237   verifyFormat(
5238       "class SomeClass\n"
5239       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5240       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5241       Style);
5242   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
5243   verifyFormat(
5244       "class SomeClass\n"
5245       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5246       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5247       Style);
5248   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
5249   verifyFormat(
5250       "class SomeClass :\n"
5251       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5252       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5253       Style);
5254 }
5255 
5256 #ifndef EXPENSIVE_CHECKS
5257 // Expensive checks enables libstdc++ checking which includes validating the
5258 // state of ranges used in std::priority_queue - this blows out the
5259 // runtime/scalability of the function and makes this test unacceptably slow.
5260 TEST_F(FormatTest, MemoizationTests) {
5261   // This breaks if the memoization lookup does not take \c Indent and
5262   // \c LastSpace into account.
5263   verifyFormat(
5264       "extern CFRunLoopTimerRef\n"
5265       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
5266       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
5267       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
5268       "                     CFRunLoopTimerContext *context) {}");
5269 
5270   // Deep nesting somewhat works around our memoization.
5271   verifyFormat(
5272       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5273       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5274       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5275       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5276       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
5277       getLLVMStyleWithColumns(65));
5278   verifyFormat(
5279       "aaaaa(\n"
5280       "    aaaaa,\n"
5281       "    aaaaa(\n"
5282       "        aaaaa,\n"
5283       "        aaaaa(\n"
5284       "            aaaaa,\n"
5285       "            aaaaa(\n"
5286       "                aaaaa,\n"
5287       "                aaaaa(\n"
5288       "                    aaaaa,\n"
5289       "                    aaaaa(\n"
5290       "                        aaaaa,\n"
5291       "                        aaaaa(\n"
5292       "                            aaaaa,\n"
5293       "                            aaaaa(\n"
5294       "                                aaaaa,\n"
5295       "                                aaaaa(\n"
5296       "                                    aaaaa,\n"
5297       "                                    aaaaa(\n"
5298       "                                        aaaaa,\n"
5299       "                                        aaaaa(\n"
5300       "                                            aaaaa,\n"
5301       "                                            aaaaa(\n"
5302       "                                                aaaaa,\n"
5303       "                                                aaaaa))))))))))));",
5304       getLLVMStyleWithColumns(65));
5305   verifyFormat(
5306       "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"
5307       "                                  a),\n"
5308       "                                a),\n"
5309       "                              a),\n"
5310       "                            a),\n"
5311       "                          a),\n"
5312       "                        a),\n"
5313       "                      a),\n"
5314       "                    a),\n"
5315       "                  a),\n"
5316       "                a),\n"
5317       "              a),\n"
5318       "            a),\n"
5319       "          a),\n"
5320       "        a),\n"
5321       "      a),\n"
5322       "    a),\n"
5323       "  a)",
5324       getLLVMStyleWithColumns(65));
5325 
5326   // This test takes VERY long when memoization is broken.
5327   FormatStyle OnePerLine = getLLVMStyle();
5328   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5329   OnePerLine.BinPackParameters = false;
5330   std::string input = "Constructor()\n"
5331                       "    : aaaa(a,\n";
5332   for (unsigned i = 0, e = 80; i != e; ++i) {
5333     input += "           a,\n";
5334   }
5335   input += "           a) {}";
5336   verifyFormat(input, OnePerLine);
5337 }
5338 #endif
5339 
5340 TEST_F(FormatTest, BreaksAsHighAsPossible) {
5341   verifyFormat(
5342       "void f() {\n"
5343       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
5344       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
5345       "    f();\n"
5346       "}");
5347   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
5348                "    Intervals[i - 1].getRange().getLast()) {\n}");
5349 }
5350 
5351 TEST_F(FormatTest, BreaksFunctionDeclarations) {
5352   // Principially, we break function declarations in a certain order:
5353   // 1) break amongst arguments.
5354   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
5355                "                              Cccccccccccccc cccccccccccccc);");
5356   verifyFormat("template <class TemplateIt>\n"
5357                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
5358                "                            TemplateIt *stop) {}");
5359 
5360   // 2) break after return type.
5361   verifyFormat(
5362       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5363       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
5364       getGoogleStyle());
5365 
5366   // 3) break after (.
5367   verifyFormat(
5368       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
5369       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
5370       getGoogleStyle());
5371 
5372   // 4) break before after nested name specifiers.
5373   verifyFormat(
5374       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5375       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
5376       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
5377       getGoogleStyle());
5378 
5379   // However, there are exceptions, if a sufficient amount of lines can be
5380   // saved.
5381   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
5382   // more adjusting.
5383   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
5384                "                                  Cccccccccccccc cccccccccc,\n"
5385                "                                  Cccccccccccccc cccccccccc,\n"
5386                "                                  Cccccccccccccc cccccccccc,\n"
5387                "                                  Cccccccccccccc cccccccccc);");
5388   verifyFormat(
5389       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5390       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5391       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5392       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
5393       getGoogleStyle());
5394   verifyFormat(
5395       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
5396       "                                          Cccccccccccccc cccccccccc,\n"
5397       "                                          Cccccccccccccc cccccccccc,\n"
5398       "                                          Cccccccccccccc cccccccccc,\n"
5399       "                                          Cccccccccccccc cccccccccc,\n"
5400       "                                          Cccccccccccccc cccccccccc,\n"
5401       "                                          Cccccccccccccc cccccccccc);");
5402   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5403                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5404                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5405                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5406                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
5407 
5408   // Break after multi-line parameters.
5409   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5410                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5411                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5412                "    bbbb bbbb);");
5413   verifyFormat("void SomeLoooooooooooongFunction(\n"
5414                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
5415                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5416                "    int bbbbbbbbbbbbb);");
5417 
5418   // Treat overloaded operators like other functions.
5419   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5420                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
5421   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5422                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
5423   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5424                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
5425   verifyGoogleFormat(
5426       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
5427       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
5428   verifyGoogleFormat(
5429       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
5430       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
5431   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5432                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
5433   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
5434                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
5435   verifyGoogleFormat(
5436       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
5437       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5438       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
5439   verifyGoogleFormat("template <typename T>\n"
5440                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5441                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
5442                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
5443 
5444   FormatStyle Style = getLLVMStyle();
5445   Style.PointerAlignment = FormatStyle::PAS_Left;
5446   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5447                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
5448                Style);
5449   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
5450                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5451                Style);
5452 }
5453 
5454 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
5455   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
5456   // Prefer keeping `::` followed by `operator` together.
5457   EXPECT_EQ("const aaaa::bbbbbbb &\n"
5458             "ccccccccc::operator++() {\n"
5459             "  stuff();\n"
5460             "}",
5461             format("const aaaa::bbbbbbb\n"
5462                    "&ccccccccc::operator++() { stuff(); }",
5463                    getLLVMStyleWithColumns(40)));
5464 }
5465 
5466 TEST_F(FormatTest, TrailingReturnType) {
5467   verifyFormat("auto foo() -> int;\n");
5468   // correct trailing return type spacing
5469   verifyFormat("auto operator->() -> int;\n");
5470   verifyFormat("auto operator++(int) -> int;\n");
5471 
5472   verifyFormat("struct S {\n"
5473                "  auto bar() const -> int;\n"
5474                "};");
5475   verifyFormat("template <size_t Order, typename T>\n"
5476                "auto load_img(const std::string &filename)\n"
5477                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
5478   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
5479                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
5480   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
5481   verifyFormat("template <typename T>\n"
5482                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
5483                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
5484 
5485   // Not trailing return types.
5486   verifyFormat("void f() { auto a = b->c(); }");
5487 }
5488 
5489 TEST_F(FormatTest, DeductionGuides) {
5490   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
5491   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
5492   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
5493   verifyFormat(
5494       "template <class... T>\n"
5495       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
5496   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
5497   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
5498   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
5499   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
5500   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
5501   verifyFormat("template <class T> x() -> x<1>;");
5502   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
5503 
5504   // Ensure not deduction guides.
5505   verifyFormat("c()->f<int>();");
5506   verifyFormat("x()->foo<1>;");
5507   verifyFormat("x = p->foo<3>();");
5508   verifyFormat("x()->x<1>();");
5509   verifyFormat("x()->x<1>;");
5510 }
5511 
5512 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
5513   // Avoid breaking before trailing 'const' or other trailing annotations, if
5514   // they are not function-like.
5515   FormatStyle Style = getGoogleStyle();
5516   Style.ColumnLimit = 47;
5517   verifyFormat("void someLongFunction(\n"
5518                "    int someLoooooooooooooongParameter) const {\n}",
5519                getLLVMStyleWithColumns(47));
5520   verifyFormat("LoooooongReturnType\n"
5521                "someLoooooooongFunction() const {}",
5522                getLLVMStyleWithColumns(47));
5523   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
5524                "    const {}",
5525                Style);
5526   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5527                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
5528   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5529                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
5530   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5531                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
5532   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
5533                "                   aaaaaaaaaaa aaaaa) const override;");
5534   verifyGoogleFormat(
5535       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5536       "    const override;");
5537 
5538   // Even if the first parameter has to be wrapped.
5539   verifyFormat("void someLongFunction(\n"
5540                "    int someLongParameter) const {}",
5541                getLLVMStyleWithColumns(46));
5542   verifyFormat("void someLongFunction(\n"
5543                "    int someLongParameter) const {}",
5544                Style);
5545   verifyFormat("void someLongFunction(\n"
5546                "    int someLongParameter) override {}",
5547                Style);
5548   verifyFormat("void someLongFunction(\n"
5549                "    int someLongParameter) OVERRIDE {}",
5550                Style);
5551   verifyFormat("void someLongFunction(\n"
5552                "    int someLongParameter) final {}",
5553                Style);
5554   verifyFormat("void someLongFunction(\n"
5555                "    int someLongParameter) FINAL {}",
5556                Style);
5557   verifyFormat("void someLongFunction(\n"
5558                "    int parameter) const override {}",
5559                Style);
5560 
5561   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
5562   verifyFormat("void someLongFunction(\n"
5563                "    int someLongParameter) const\n"
5564                "{\n"
5565                "}",
5566                Style);
5567 
5568   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
5569   verifyFormat("void someLongFunction(\n"
5570                "    int someLongParameter) const\n"
5571                "  {\n"
5572                "  }",
5573                Style);
5574 
5575   // Unless these are unknown annotations.
5576   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
5577                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5578                "    LONG_AND_UGLY_ANNOTATION;");
5579 
5580   // Breaking before function-like trailing annotations is fine to keep them
5581   // close to their arguments.
5582   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5583                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5584   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5585                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5586   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5587                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
5588   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
5589                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
5590   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
5591 
5592   verifyFormat(
5593       "void aaaaaaaaaaaaaaaaaa()\n"
5594       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
5595       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
5596   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5597                "    __attribute__((unused));");
5598   verifyGoogleFormat(
5599       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5600       "    GUARDED_BY(aaaaaaaaaaaa);");
5601   verifyGoogleFormat(
5602       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5603       "    GUARDED_BY(aaaaaaaaaaaa);");
5604   verifyGoogleFormat(
5605       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
5606       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5607   verifyGoogleFormat(
5608       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
5609       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
5610 }
5611 
5612 TEST_F(FormatTest, FunctionAnnotations) {
5613   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5614                "int OldFunction(const string &parameter) {}");
5615   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5616                "string OldFunction(const string &parameter) {}");
5617   verifyFormat("template <typename T>\n"
5618                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5619                "string OldFunction(const string &parameter) {}");
5620 
5621   // Not function annotations.
5622   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5623                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
5624   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
5625                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
5626   verifyFormat("MACRO(abc).function() // wrap\n"
5627                "    << abc;");
5628   verifyFormat("MACRO(abc)->function() // wrap\n"
5629                "    << abc;");
5630   verifyFormat("MACRO(abc)::function() // wrap\n"
5631                "    << abc;");
5632 }
5633 
5634 TEST_F(FormatTest, BreaksDesireably) {
5635   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
5636                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
5637                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
5638   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5639                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
5640                "}");
5641 
5642   verifyFormat(
5643       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5644       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5645 
5646   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5647                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5648                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5649 
5650   verifyFormat(
5651       "aaaaaaaa(aaaaaaaaaaaaa,\n"
5652       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5653       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
5654       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5655       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
5656 
5657   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5658                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5659 
5660   verifyFormat(
5661       "void f() {\n"
5662       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
5663       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5664       "}");
5665   verifyFormat(
5666       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5667       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5668   verifyFormat(
5669       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5670       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5671   verifyFormat(
5672       "aaaaaa(aaa,\n"
5673       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5674       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5675       "       aaaa);");
5676   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5677                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5678                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5679 
5680   // Indent consistently independent of call expression and unary operator.
5681   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5682                "    dddddddddddddddddddddddddddddd));");
5683   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5684                "    dddddddddddddddddddddddddddddd));");
5685   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
5686                "    dddddddddddddddddddddddddddddd));");
5687 
5688   // This test case breaks on an incorrect memoization, i.e. an optimization not
5689   // taking into account the StopAt value.
5690   verifyFormat(
5691       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5692       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5693       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5694       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5695 
5696   verifyFormat("{\n  {\n    {\n"
5697                "      Annotation.SpaceRequiredBefore =\n"
5698                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
5699                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
5700                "    }\n  }\n}");
5701 
5702   // Break on an outer level if there was a break on an inner level.
5703   EXPECT_EQ("f(g(h(a, // comment\n"
5704             "      b, c),\n"
5705             "    d, e),\n"
5706             "  x, y);",
5707             format("f(g(h(a, // comment\n"
5708                    "    b, c), d, e), x, y);"));
5709 
5710   // Prefer breaking similar line breaks.
5711   verifyFormat(
5712       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
5713       "                             NSTrackingMouseEnteredAndExited |\n"
5714       "                             NSTrackingActiveAlways;");
5715 }
5716 
5717 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
5718   FormatStyle NoBinPacking = getGoogleStyle();
5719   NoBinPacking.BinPackParameters = false;
5720   NoBinPacking.BinPackArguments = true;
5721   verifyFormat("void f() {\n"
5722                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
5723                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5724                "}",
5725                NoBinPacking);
5726   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
5727                "       int aaaaaaaaaaaaaaaaaaaa,\n"
5728                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5729                NoBinPacking);
5730 
5731   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
5732   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5733                "                        vector<int> bbbbbbbbbbbbbbb);",
5734                NoBinPacking);
5735   // FIXME: This behavior difference is probably not wanted. However, currently
5736   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
5737   // template arguments from BreakBeforeParameter being set because of the
5738   // one-per-line formatting.
5739   verifyFormat(
5740       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
5741       "                                             aaaaaaaaaa> aaaaaaaaaa);",
5742       NoBinPacking);
5743   verifyFormat(
5744       "void fffffffffff(\n"
5745       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
5746       "        aaaaaaaaaa);");
5747 }
5748 
5749 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
5750   FormatStyle NoBinPacking = getGoogleStyle();
5751   NoBinPacking.BinPackParameters = false;
5752   NoBinPacking.BinPackArguments = false;
5753   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
5754                "  aaaaaaaaaaaaaaaaaaaa,\n"
5755                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
5756                NoBinPacking);
5757   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
5758                "        aaaaaaaaaaaaa,\n"
5759                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
5760                NoBinPacking);
5761   verifyFormat(
5762       "aaaaaaaa(aaaaaaaaaaaaa,\n"
5763       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5764       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
5765       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5766       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
5767       NoBinPacking);
5768   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
5769                "    .aaaaaaaaaaaaaaaaaa();",
5770                NoBinPacking);
5771   verifyFormat("void f() {\n"
5772                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5773                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
5774                "}",
5775                NoBinPacking);
5776 
5777   verifyFormat(
5778       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5779       "             aaaaaaaaaaaa,\n"
5780       "             aaaaaaaaaaaa);",
5781       NoBinPacking);
5782   verifyFormat(
5783       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
5784       "                               ddddddddddddddddddddddddddddd),\n"
5785       "             test);",
5786       NoBinPacking);
5787 
5788   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
5789                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
5790                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
5791                "    aaaaaaaaaaaaaaaaaa;",
5792                NoBinPacking);
5793   verifyFormat("a(\"a\"\n"
5794                "  \"a\",\n"
5795                "  a);");
5796 
5797   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
5798   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
5799                "                aaaaaaaaa,\n"
5800                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5801                NoBinPacking);
5802   verifyFormat(
5803       "void f() {\n"
5804       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
5805       "      .aaaaaaa();\n"
5806       "}",
5807       NoBinPacking);
5808   verifyFormat(
5809       "template <class SomeType, class SomeOtherType>\n"
5810       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
5811       NoBinPacking);
5812 }
5813 
5814 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
5815   FormatStyle Style = getLLVMStyleWithColumns(15);
5816   Style.ExperimentalAutoDetectBinPacking = true;
5817   EXPECT_EQ("aaa(aaaa,\n"
5818             "    aaaa,\n"
5819             "    aaaa);\n"
5820             "aaa(aaaa,\n"
5821             "    aaaa,\n"
5822             "    aaaa);",
5823             format("aaa(aaaa,\n" // one-per-line
5824                    "  aaaa,\n"
5825                    "    aaaa  );\n"
5826                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
5827                    Style));
5828   EXPECT_EQ("aaa(aaaa, aaaa,\n"
5829             "    aaaa);\n"
5830             "aaa(aaaa, aaaa,\n"
5831             "    aaaa);",
5832             format("aaa(aaaa,  aaaa,\n" // bin-packed
5833                    "    aaaa  );\n"
5834                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
5835                    Style));
5836 }
5837 
5838 TEST_F(FormatTest, FormatsBuilderPattern) {
5839   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
5840                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
5841                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
5842                "    .StartsWith(\".init\", ORDER_INIT)\n"
5843                "    .StartsWith(\".fini\", ORDER_FINI)\n"
5844                "    .StartsWith(\".hash\", ORDER_HASH)\n"
5845                "    .Default(ORDER_TEXT);\n");
5846 
5847   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
5848                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
5849   verifyFormat("aaaaaaa->aaaaaaa\n"
5850                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5851                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5852                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
5853   verifyFormat(
5854       "aaaaaaa->aaaaaaa\n"
5855       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5856       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
5857   verifyFormat(
5858       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
5859       "    aaaaaaaaaaaaaa);");
5860   verifyFormat(
5861       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
5862       "    aaaaaa->aaaaaaaaaaaa()\n"
5863       "        ->aaaaaaaaaaaaaaaa(\n"
5864       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5865       "        ->aaaaaaaaaaaaaaaaa();");
5866   verifyGoogleFormat(
5867       "void f() {\n"
5868       "  someo->Add((new util::filetools::Handler(dir))\n"
5869       "                 ->OnEvent1(NewPermanentCallback(\n"
5870       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
5871       "                 ->OnEvent2(NewPermanentCallback(\n"
5872       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
5873       "                 ->OnEvent3(NewPermanentCallback(\n"
5874       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
5875       "                 ->OnEvent5(NewPermanentCallback(\n"
5876       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
5877       "                 ->OnEvent6(NewPermanentCallback(\n"
5878       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
5879       "}");
5880 
5881   verifyFormat(
5882       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
5883   verifyFormat("aaaaaaaaaaaaaaa()\n"
5884                "    .aaaaaaaaaaaaaaa()\n"
5885                "    .aaaaaaaaaaaaaaa()\n"
5886                "    .aaaaaaaaaaaaaaa()\n"
5887                "    .aaaaaaaaaaaaaaa();");
5888   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5889                "    .aaaaaaaaaaaaaaa()\n"
5890                "    .aaaaaaaaaaaaaaa()\n"
5891                "    .aaaaaaaaaaaaaaa();");
5892   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5893                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5894                "    .aaaaaaaaaaaaaaa();");
5895   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
5896                "    ->aaaaaaaaaaaaaae(0)\n"
5897                "    ->aaaaaaaaaaaaaaa();");
5898 
5899   // Don't linewrap after very short segments.
5900   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5901                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5902                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5903   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5904                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5905                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5906   verifyFormat("aaa()\n"
5907                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5908                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5909                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5910 
5911   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
5912                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5913                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
5914   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
5915                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5916                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
5917 
5918   // Prefer not to break after empty parentheses.
5919   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
5920                "    First->LastNewlineOffset);");
5921 
5922   // Prefer not to create "hanging" indents.
5923   verifyFormat(
5924       "return !soooooooooooooome_map\n"
5925       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5926       "            .second;");
5927   verifyFormat(
5928       "return aaaaaaaaaaaaaaaa\n"
5929       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
5930       "    .aaaa(aaaaaaaaaaaaaa);");
5931   // No hanging indent here.
5932   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
5933                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5934   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
5935                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5936   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
5937                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5938                getLLVMStyleWithColumns(60));
5939   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
5940                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
5941                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5942                getLLVMStyleWithColumns(59));
5943   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5944                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5945                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5946 
5947   // Dont break if only closing statements before member call
5948   verifyFormat("test() {\n"
5949                "  ([]() -> {\n"
5950                "    int b = 32;\n"
5951                "    return 3;\n"
5952                "  }).foo();\n"
5953                "}");
5954   verifyFormat("test() {\n"
5955                "  (\n"
5956                "      []() -> {\n"
5957                "        int b = 32;\n"
5958                "        return 3;\n"
5959                "      },\n"
5960                "      foo, bar)\n"
5961                "      .foo();\n"
5962                "}");
5963   verifyFormat("test() {\n"
5964                "  ([]() -> {\n"
5965                "    int b = 32;\n"
5966                "    return 3;\n"
5967                "  })\n"
5968                "      .foo()\n"
5969                "      .bar();\n"
5970                "}");
5971   verifyFormat("test() {\n"
5972                "  ([]() -> {\n"
5973                "    int b = 32;\n"
5974                "    return 3;\n"
5975                "  })\n"
5976                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
5977                "           \"bbbb\");\n"
5978                "}",
5979                getLLVMStyleWithColumns(30));
5980 }
5981 
5982 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
5983   verifyFormat(
5984       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5985       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
5986   verifyFormat(
5987       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
5988       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
5989 
5990   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
5991                "    ccccccccccccccccccccccccc) {\n}");
5992   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
5993                "    ccccccccccccccccccccccccc) {\n}");
5994 
5995   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
5996                "    ccccccccccccccccccccccccc) {\n}");
5997   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
5998                "    ccccccccccccccccccccccccc) {\n}");
5999 
6000   verifyFormat(
6001       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
6002       "    ccccccccccccccccccccccccc) {\n}");
6003   verifyFormat(
6004       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
6005       "    ccccccccccccccccccccccccc) {\n}");
6006 
6007   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
6008                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
6009                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
6010                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
6011   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
6012                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
6013                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
6014                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
6015 
6016   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
6017                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
6018                "    aaaaaaaaaaaaaaa != aa) {\n}");
6019   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
6020                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
6021                "    aaaaaaaaaaaaaaa != aa) {\n}");
6022 }
6023 
6024 TEST_F(FormatTest, BreaksAfterAssignments) {
6025   verifyFormat(
6026       "unsigned Cost =\n"
6027       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
6028       "                        SI->getPointerAddressSpaceee());\n");
6029   verifyFormat(
6030       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
6031       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
6032 
6033   verifyFormat(
6034       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
6035       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
6036   verifyFormat("unsigned OriginalStartColumn =\n"
6037                "    SourceMgr.getSpellingColumnNumber(\n"
6038                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
6039                "    1;");
6040 }
6041 
6042 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
6043   FormatStyle Style = getLLVMStyle();
6044   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6045                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
6046                Style);
6047 
6048   Style.PenaltyBreakAssignment = 20;
6049   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6050                "                                 cccccccccccccccccccccccccc;",
6051                Style);
6052 }
6053 
6054 TEST_F(FormatTest, AlignsAfterAssignments) {
6055   verifyFormat(
6056       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6057       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
6058   verifyFormat(
6059       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6060       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
6061   verifyFormat(
6062       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6063       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
6064   verifyFormat(
6065       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6066       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
6067   verifyFormat(
6068       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
6069       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
6070       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
6071 }
6072 
6073 TEST_F(FormatTest, AlignsAfterReturn) {
6074   verifyFormat(
6075       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6076       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
6077   verifyFormat(
6078       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6079       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
6080   verifyFormat(
6081       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
6082       "       aaaaaaaaaaaaaaaaaaaaaa();");
6083   verifyFormat(
6084       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
6085       "        aaaaaaaaaaaaaaaaaaaaaa());");
6086   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6087                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6088   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6089                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
6090                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6091   verifyFormat("return\n"
6092                "    // true if code is one of a or b.\n"
6093                "    code == a || code == b;");
6094 }
6095 
6096 TEST_F(FormatTest, AlignsAfterOpenBracket) {
6097   verifyFormat(
6098       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
6099       "                                                aaaaaaaaa aaaaaaa) {}");
6100   verifyFormat(
6101       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
6102       "                                               aaaaaaaaaaa aaaaaaaaa);");
6103   verifyFormat(
6104       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
6105       "                                             aaaaaaaaaaaaaaaaaaaaa));");
6106   FormatStyle Style = getLLVMStyle();
6107   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6108   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6109                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
6110                Style);
6111   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
6112                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
6113                Style);
6114   verifyFormat("SomeLongVariableName->someFunction(\n"
6115                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
6116                Style);
6117   verifyFormat(
6118       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
6119       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6120       Style);
6121   verifyFormat(
6122       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
6123       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6124       Style);
6125   verifyFormat(
6126       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
6127       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
6128       Style);
6129 
6130   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
6131                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
6132                "        b));",
6133                Style);
6134 
6135   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6136   Style.BinPackArguments = false;
6137   Style.BinPackParameters = false;
6138   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6139                "    aaaaaaaaaaa aaaaaaaa,\n"
6140                "    aaaaaaaaa aaaaaaa,\n"
6141                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6142                Style);
6143   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
6144                "    aaaaaaaaaaa aaaaaaaaa,\n"
6145                "    aaaaaaaaaaa aaaaaaaaa,\n"
6146                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6147                Style);
6148   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
6149                "    aaaaaaaaaaaaaaa,\n"
6150                "    aaaaaaaaaaaaaaaaaaaaa,\n"
6151                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
6152                Style);
6153   verifyFormat(
6154       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
6155       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
6156       Style);
6157   verifyFormat(
6158       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
6159       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
6160       Style);
6161   verifyFormat(
6162       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6163       "    aaaaaaaaaaaaaaaaaaaaa(\n"
6164       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
6165       "    aaaaaaaaaaaaaaaa);",
6166       Style);
6167   verifyFormat(
6168       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6169       "    aaaaaaaaaaaaaaaaaaaaa(\n"
6170       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
6171       "    aaaaaaaaaaaaaaaa);",
6172       Style);
6173 }
6174 
6175 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
6176   FormatStyle Style = getLLVMStyleWithColumns(40);
6177   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6178                "          bbbbbbbbbbbbbbbbbbbbbb);",
6179                Style);
6180   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6181   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6182   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6183                "          bbbbbbbbbbbbbbbbbbbbbb);",
6184                Style);
6185   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6186   Style.AlignOperands = FormatStyle::OAS_Align;
6187   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6188                "          bbbbbbbbbbbbbbbbbbbbbb);",
6189                Style);
6190   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6191   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6192   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6193                "    bbbbbbbbbbbbbbbbbbbbbb);",
6194                Style);
6195 }
6196 
6197 TEST_F(FormatTest, BreaksConditionalExpressions) {
6198   verifyFormat(
6199       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6200       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6201       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6202   verifyFormat(
6203       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
6204       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6205       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6206   verifyFormat(
6207       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6208       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6209   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
6210                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6211                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6212   verifyFormat(
6213       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
6214       "                                                    : aaaaaaaaaaaaa);");
6215   verifyFormat(
6216       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6217       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6218       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6219       "                   aaaaaaaaaaaaa);");
6220   verifyFormat(
6221       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6222       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6223       "                   aaaaaaaaaaaaa);");
6224   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6225                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6226                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6227                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6228                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6229   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6230                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6231                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6232                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6233                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6234                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6235                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6236   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6237                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6238                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6239                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6240                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6241   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6242                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6243                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6244   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
6245                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6246                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6247                "        : aaaaaaaaaaaaaaaa;");
6248   verifyFormat(
6249       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6250       "    ? aaaaaaaaaaaaaaa\n"
6251       "    : aaaaaaaaaaaaaaa;");
6252   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
6253                "          aaaaaaaaa\n"
6254                "      ? b\n"
6255                "      : c);");
6256   verifyFormat("return aaaa == bbbb\n"
6257                "           // comment\n"
6258                "           ? aaaa\n"
6259                "           : bbbb;");
6260   verifyFormat("unsigned Indent =\n"
6261                "    format(TheLine.First,\n"
6262                "           IndentForLevel[TheLine.Level] >= 0\n"
6263                "               ? IndentForLevel[TheLine.Level]\n"
6264                "               : TheLine * 2,\n"
6265                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
6266                getLLVMStyleWithColumns(60));
6267   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
6268                "                  ? aaaaaaaaaaaaaaa\n"
6269                "                  : bbbbbbbbbbbbbbb //\n"
6270                "                        ? ccccccccccccccc\n"
6271                "                        : ddddddddddddddd;");
6272   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
6273                "                  ? aaaaaaaaaaaaaaa\n"
6274                "                  : (bbbbbbbbbbbbbbb //\n"
6275                "                         ? ccccccccccccccc\n"
6276                "                         : ddddddddddddddd);");
6277   verifyFormat(
6278       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6279       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6280       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
6281       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
6282       "                                      : aaaaaaaaaa;");
6283   verifyFormat(
6284       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6285       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
6286       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6287 
6288   FormatStyle NoBinPacking = getLLVMStyle();
6289   NoBinPacking.BinPackArguments = false;
6290   verifyFormat(
6291       "void f() {\n"
6292       "  g(aaa,\n"
6293       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
6294       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6295       "        ? aaaaaaaaaaaaaaa\n"
6296       "        : aaaaaaaaaaaaaaa);\n"
6297       "}",
6298       NoBinPacking);
6299   verifyFormat(
6300       "void f() {\n"
6301       "  g(aaa,\n"
6302       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
6303       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6304       "        ?: aaaaaaaaaaaaaaa);\n"
6305       "}",
6306       NoBinPacking);
6307 
6308   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
6309                "             // comment.\n"
6310                "             ccccccccccccccccccccccccccccccccccccccc\n"
6311                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6312                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
6313 
6314   // Assignments in conditional expressions. Apparently not uncommon :-(.
6315   verifyFormat("return a != b\n"
6316                "           // comment\n"
6317                "           ? a = b\n"
6318                "           : a = b;");
6319   verifyFormat("return a != b\n"
6320                "           // comment\n"
6321                "           ? a = a != b\n"
6322                "                     // comment\n"
6323                "                     ? a = b\n"
6324                "                     : a\n"
6325                "           : a;\n");
6326   verifyFormat("return a != b\n"
6327                "           // comment\n"
6328                "           ? a\n"
6329                "           : a = a != b\n"
6330                "                     // comment\n"
6331                "                     ? a = b\n"
6332                "                     : a;");
6333 
6334   // Chained conditionals
6335   FormatStyle Style = getLLVMStyle();
6336   Style.ColumnLimit = 70;
6337   Style.AlignOperands = FormatStyle::OAS_Align;
6338   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6339                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6340                "                        : 3333333333333333;",
6341                Style);
6342   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6343                "       : bbbbbbbbbb     ? 2222222222222222\n"
6344                "                        : 3333333333333333;",
6345                Style);
6346   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
6347                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6348                "                          : 3333333333333333;",
6349                Style);
6350   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6351                "       : bbbbbbbbbbbbbb ? 222222\n"
6352                "                        : 333333;",
6353                Style);
6354   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6355                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6356                "       : cccccccccccccc ? 3333333333333333\n"
6357                "                        : 4444444444444444;",
6358                Style);
6359   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
6360                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6361                "                        : 3333333333333333;",
6362                Style);
6363   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6364                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6365                "                        : (aaa ? bbb : ccc);",
6366                Style);
6367   verifyFormat(
6368       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6369       "                                             : cccccccccccccccccc)\n"
6370       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6371       "                        : 3333333333333333;",
6372       Style);
6373   verifyFormat(
6374       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6375       "                                             : cccccccccccccccccc)\n"
6376       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6377       "                        : 3333333333333333;",
6378       Style);
6379   verifyFormat(
6380       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6381       "                                             : dddddddddddddddddd)\n"
6382       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6383       "                        : 3333333333333333;",
6384       Style);
6385   verifyFormat(
6386       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6387       "                                             : dddddddddddddddddd)\n"
6388       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6389       "                        : 3333333333333333;",
6390       Style);
6391   verifyFormat(
6392       "return aaaaaaaaa        ? 1111111111111111\n"
6393       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6394       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6395       "                                             : dddddddddddddddddd)\n",
6396       Style);
6397   verifyFormat(
6398       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6399       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6400       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6401       "                                             : cccccccccccccccccc);",
6402       Style);
6403   verifyFormat(
6404       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6405       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6406       "                                             : eeeeeeeeeeeeeeeeee)\n"
6407       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6408       "                        : 3333333333333333;",
6409       Style);
6410   verifyFormat(
6411       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6412       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6413       "                                             : eeeeeeeeeeeeeeeeee)\n"
6414       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6415       "                        : 3333333333333333;",
6416       Style);
6417   verifyFormat(
6418       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6419       "                           : cccccccccccc    ? dddddddddddddddddd\n"
6420       "                                             : eeeeeeeeeeeeeeeeee)\n"
6421       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6422       "                        : 3333333333333333;",
6423       Style);
6424   verifyFormat(
6425       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6426       "                                             : cccccccccccccccccc\n"
6427       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6428       "                        : 3333333333333333;",
6429       Style);
6430   verifyFormat(
6431       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6432       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
6433       "                                             : eeeeeeeeeeeeeeeeee\n"
6434       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6435       "                        : 3333333333333333;",
6436       Style);
6437   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
6438                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
6439                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
6440                "                                   : eeeeeeeeeeeeeeeeee)\n"
6441                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
6442                "                             : 3333333333333333;",
6443                Style);
6444   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
6445                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6446                "             : cccccccccccccccc ? dddddddddddddddddd\n"
6447                "                                : eeeeeeeeeeeeeeeeee\n"
6448                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
6449                "                                 : 3333333333333333;",
6450                Style);
6451 
6452   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6453   Style.BreakBeforeTernaryOperators = false;
6454   // FIXME: Aligning the question marks is weird given DontAlign.
6455   // Consider disabling this alignment in this case. Also check whether this
6456   // will render the adjustment from https://reviews.llvm.org/D82199
6457   // unnecessary.
6458   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
6459                "    bbbb                ? cccccccccccccccccc :\n"
6460                "                          ddddd;\n",
6461                Style);
6462 }
6463 
6464 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
6465   FormatStyle Style = getLLVMStyle();
6466   Style.BreakBeforeTernaryOperators = false;
6467   Style.ColumnLimit = 70;
6468   verifyFormat(
6469       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6470       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6471       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6472       Style);
6473   verifyFormat(
6474       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
6475       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6476       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6477       Style);
6478   verifyFormat(
6479       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6480       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6481       Style);
6482   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
6483                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6484                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6485                Style);
6486   verifyFormat(
6487       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
6488       "                                                      aaaaaaaaaaaaa);",
6489       Style);
6490   verifyFormat(
6491       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6492       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6493       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6494       "                   aaaaaaaaaaaaa);",
6495       Style);
6496   verifyFormat(
6497       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6498       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6499       "                   aaaaaaaaaaaaa);",
6500       Style);
6501   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6502                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6503                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6504                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6505                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6506                Style);
6507   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6508                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6509                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6510                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6511                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6512                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6513                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6514                Style);
6515   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6516                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
6517                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6518                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6519                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6520                Style);
6521   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6522                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6523                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6524                Style);
6525   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
6526                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6527                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6528                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6529                Style);
6530   verifyFormat(
6531       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6532       "    aaaaaaaaaaaaaaa :\n"
6533       "    aaaaaaaaaaaaaaa;",
6534       Style);
6535   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
6536                "          aaaaaaaaa ?\n"
6537                "      b :\n"
6538                "      c);",
6539                Style);
6540   verifyFormat("unsigned Indent =\n"
6541                "    format(TheLine.First,\n"
6542                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
6543                "               IndentForLevel[TheLine.Level] :\n"
6544                "               TheLine * 2,\n"
6545                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
6546                Style);
6547   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6548                "                  aaaaaaaaaaaaaaa :\n"
6549                "                  bbbbbbbbbbbbbbb ? //\n"
6550                "                      ccccccccccccccc :\n"
6551                "                      ddddddddddddddd;",
6552                Style);
6553   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6554                "                  aaaaaaaaaaaaaaa :\n"
6555                "                  (bbbbbbbbbbbbbbb ? //\n"
6556                "                       ccccccccccccccc :\n"
6557                "                       ddddddddddddddd);",
6558                Style);
6559   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6560                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
6561                "            ccccccccccccccccccccccccccc;",
6562                Style);
6563   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6564                "           aaaaa :\n"
6565                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
6566                Style);
6567 
6568   // Chained conditionals
6569   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6570                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6571                "                          3333333333333333;",
6572                Style);
6573   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6574                "       bbbbbbbbbb       ? 2222222222222222 :\n"
6575                "                          3333333333333333;",
6576                Style);
6577   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
6578                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6579                "                          3333333333333333;",
6580                Style);
6581   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6582                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
6583                "                          333333;",
6584                Style);
6585   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6586                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6587                "       cccccccccccccccc ? 3333333333333333 :\n"
6588                "                          4444444444444444;",
6589                Style);
6590   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
6591                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6592                "                          3333333333333333;",
6593                Style);
6594   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6595                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6596                "                          (aaa ? bbb : ccc);",
6597                Style);
6598   verifyFormat(
6599       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6600       "                                               cccccccccccccccccc) :\n"
6601       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6602       "                          3333333333333333;",
6603       Style);
6604   verifyFormat(
6605       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6606       "                                               cccccccccccccccccc) :\n"
6607       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6608       "                          3333333333333333;",
6609       Style);
6610   verifyFormat(
6611       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6612       "                                               dddddddddddddddddd) :\n"
6613       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6614       "                          3333333333333333;",
6615       Style);
6616   verifyFormat(
6617       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6618       "                                               dddddddddddddddddd) :\n"
6619       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6620       "                          3333333333333333;",
6621       Style);
6622   verifyFormat(
6623       "return aaaaaaaaa        ? 1111111111111111 :\n"
6624       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6625       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6626       "                                               dddddddddddddddddd)\n",
6627       Style);
6628   verifyFormat(
6629       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6630       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6631       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6632       "                                               cccccccccccccccccc);",
6633       Style);
6634   verifyFormat(
6635       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6636       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
6637       "                                               eeeeeeeeeeeeeeeeee) :\n"
6638       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6639       "                          3333333333333333;",
6640       Style);
6641   verifyFormat(
6642       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6643       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
6644       "                                               eeeeeeeeeeeeeeeeee) :\n"
6645       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6646       "                          3333333333333333;",
6647       Style);
6648   verifyFormat(
6649       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
6650       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
6651       "                                               eeeeeeeeeeeeeeeeee) :\n"
6652       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6653       "                          3333333333333333;",
6654       Style);
6655   verifyFormat(
6656       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6657       "                                               cccccccccccccccccc :\n"
6658       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6659       "                          3333333333333333;",
6660       Style);
6661   verifyFormat(
6662       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6663       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
6664       "                                               eeeeeeeeeeeeeeeeee :\n"
6665       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6666       "                          3333333333333333;",
6667       Style);
6668   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
6669                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6670                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
6671                "                                 eeeeeeeeeeeeeeeeee) :\n"
6672                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6673                "                               3333333333333333;",
6674                Style);
6675   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
6676                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6677                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
6678                "                                  eeeeeeeeeeeeeeeeee :\n"
6679                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6680                "                               3333333333333333;",
6681                Style);
6682 }
6683 
6684 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
6685   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
6686                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
6687   verifyFormat("bool a = true, b = false;");
6688 
6689   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6690                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
6691                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
6692                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
6693   verifyFormat(
6694       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6695       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
6696       "     d = e && f;");
6697   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
6698                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
6699   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
6700                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
6701   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
6702                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
6703 
6704   FormatStyle Style = getGoogleStyle();
6705   Style.PointerAlignment = FormatStyle::PAS_Left;
6706   Style.DerivePointerAlignment = false;
6707   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6708                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
6709                "    *b = bbbbbbbbbbbbbbbbbbb;",
6710                Style);
6711   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
6712                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
6713                Style);
6714   verifyFormat("vector<int*> a, b;", Style);
6715   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
6716 }
6717 
6718 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
6719   verifyFormat("arr[foo ? bar : baz];");
6720   verifyFormat("f()[foo ? bar : baz];");
6721   verifyFormat("(a + b)[foo ? bar : baz];");
6722   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
6723 }
6724 
6725 TEST_F(FormatTest, AlignsStringLiterals) {
6726   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
6727                "                                      \"short literal\");");
6728   verifyFormat(
6729       "looooooooooooooooooooooooongFunction(\n"
6730       "    \"short literal\"\n"
6731       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
6732   verifyFormat("someFunction(\"Always break between multi-line\"\n"
6733                "             \" string literals\",\n"
6734                "             and, other, parameters);");
6735   EXPECT_EQ("fun + \"1243\" /* comment */\n"
6736             "      \"5678\";",
6737             format("fun + \"1243\" /* comment */\n"
6738                    "    \"5678\";",
6739                    getLLVMStyleWithColumns(28)));
6740   EXPECT_EQ(
6741       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
6742       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
6743       "         \"aaaaaaaaaaaaaaaa\";",
6744       format("aaaaaa ="
6745              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
6746              "aaaaaaaaaaaaaaaaaaaaa\" "
6747              "\"aaaaaaaaaaaaaaaa\";"));
6748   verifyFormat("a = a + \"a\"\n"
6749                "        \"a\"\n"
6750                "        \"a\";");
6751   verifyFormat("f(\"a\", \"b\"\n"
6752                "       \"c\");");
6753 
6754   verifyFormat(
6755       "#define LL_FORMAT \"ll\"\n"
6756       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
6757       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
6758 
6759   verifyFormat("#define A(X)          \\\n"
6760                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
6761                "  \"ccccc\"",
6762                getLLVMStyleWithColumns(23));
6763   verifyFormat("#define A \"def\"\n"
6764                "f(\"abc\" A \"ghi\"\n"
6765                "  \"jkl\");");
6766 
6767   verifyFormat("f(L\"a\"\n"
6768                "  L\"b\");");
6769   verifyFormat("#define A(X)            \\\n"
6770                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
6771                "  L\"ccccc\"",
6772                getLLVMStyleWithColumns(25));
6773 
6774   verifyFormat("f(@\"a\"\n"
6775                "  @\"b\");");
6776   verifyFormat("NSString s = @\"a\"\n"
6777                "             @\"b\"\n"
6778                "             @\"c\";");
6779   verifyFormat("NSString s = @\"a\"\n"
6780                "              \"b\"\n"
6781                "              \"c\";");
6782 }
6783 
6784 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
6785   FormatStyle Style = getLLVMStyle();
6786   // No declarations or definitions should be moved to own line.
6787   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
6788   verifyFormat("class A {\n"
6789                "  int f() { return 1; }\n"
6790                "  int g();\n"
6791                "};\n"
6792                "int f() { return 1; }\n"
6793                "int g();\n",
6794                Style);
6795 
6796   // All declarations and definitions should have the return type moved to its
6797   // own line.
6798   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
6799   Style.TypenameMacros = {"LIST"};
6800   verifyFormat("SomeType\n"
6801                "funcdecl(LIST(uint64_t));",
6802                Style);
6803   verifyFormat("class E {\n"
6804                "  int\n"
6805                "  f() {\n"
6806                "    return 1;\n"
6807                "  }\n"
6808                "  int\n"
6809                "  g();\n"
6810                "};\n"
6811                "int\n"
6812                "f() {\n"
6813                "  return 1;\n"
6814                "}\n"
6815                "int\n"
6816                "g();\n",
6817                Style);
6818 
6819   // Top-level definitions, and no kinds of declarations should have the
6820   // return type moved to its own line.
6821   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
6822   verifyFormat("class B {\n"
6823                "  int f() { return 1; }\n"
6824                "  int g();\n"
6825                "};\n"
6826                "int\n"
6827                "f() {\n"
6828                "  return 1;\n"
6829                "}\n"
6830                "int g();\n",
6831                Style);
6832 
6833   // Top-level definitions and declarations should have the return type moved
6834   // to its own line.
6835   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
6836   verifyFormat("class C {\n"
6837                "  int f() { return 1; }\n"
6838                "  int g();\n"
6839                "};\n"
6840                "int\n"
6841                "f() {\n"
6842                "  return 1;\n"
6843                "}\n"
6844                "int\n"
6845                "g();\n",
6846                Style);
6847 
6848   // All definitions should have the return type moved to its own line, but no
6849   // kinds of declarations.
6850   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
6851   verifyFormat("class D {\n"
6852                "  int\n"
6853                "  f() {\n"
6854                "    return 1;\n"
6855                "  }\n"
6856                "  int g();\n"
6857                "};\n"
6858                "int\n"
6859                "f() {\n"
6860                "  return 1;\n"
6861                "}\n"
6862                "int g();\n",
6863                Style);
6864   verifyFormat("const char *\n"
6865                "f(void) {\n" // Break here.
6866                "  return \"\";\n"
6867                "}\n"
6868                "const char *bar(void);\n", // No break here.
6869                Style);
6870   verifyFormat("template <class T>\n"
6871                "T *\n"
6872                "f(T &c) {\n" // Break here.
6873                "  return NULL;\n"
6874                "}\n"
6875                "template <class T> T *f(T &c);\n", // No break here.
6876                Style);
6877   verifyFormat("class C {\n"
6878                "  int\n"
6879                "  operator+() {\n"
6880                "    return 1;\n"
6881                "  }\n"
6882                "  int\n"
6883                "  operator()() {\n"
6884                "    return 1;\n"
6885                "  }\n"
6886                "};\n",
6887                Style);
6888   verifyFormat("void\n"
6889                "A::operator()() {}\n"
6890                "void\n"
6891                "A::operator>>() {}\n"
6892                "void\n"
6893                "A::operator+() {}\n"
6894                "void\n"
6895                "A::operator*() {}\n"
6896                "void\n"
6897                "A::operator->() {}\n"
6898                "void\n"
6899                "A::operator void *() {}\n"
6900                "void\n"
6901                "A::operator void &() {}\n"
6902                "void\n"
6903                "A::operator void &&() {}\n"
6904                "void\n"
6905                "A::operator char *() {}\n"
6906                "void\n"
6907                "A::operator[]() {}\n"
6908                "void\n"
6909                "A::operator!() {}\n"
6910                "void\n"
6911                "A::operator**() {}\n"
6912                "void\n"
6913                "A::operator<Foo> *() {}\n"
6914                "void\n"
6915                "A::operator<Foo> **() {}\n"
6916                "void\n"
6917                "A::operator<Foo> &() {}\n"
6918                "void\n"
6919                "A::operator void **() {}\n",
6920                Style);
6921   verifyFormat("constexpr auto\n"
6922                "operator()() const -> reference {}\n"
6923                "constexpr auto\n"
6924                "operator>>() const -> reference {}\n"
6925                "constexpr auto\n"
6926                "operator+() const -> reference {}\n"
6927                "constexpr auto\n"
6928                "operator*() const -> reference {}\n"
6929                "constexpr auto\n"
6930                "operator->() const -> reference {}\n"
6931                "constexpr auto\n"
6932                "operator++() const -> reference {}\n"
6933                "constexpr auto\n"
6934                "operator void *() const -> reference {}\n"
6935                "constexpr auto\n"
6936                "operator void **() const -> reference {}\n"
6937                "constexpr auto\n"
6938                "operator void *() const -> reference {}\n"
6939                "constexpr auto\n"
6940                "operator void &() const -> reference {}\n"
6941                "constexpr auto\n"
6942                "operator void &&() const -> reference {}\n"
6943                "constexpr auto\n"
6944                "operator char *() const -> reference {}\n"
6945                "constexpr auto\n"
6946                "operator!() const -> reference {}\n"
6947                "constexpr auto\n"
6948                "operator[]() const -> reference {}\n",
6949                Style);
6950   verifyFormat("void *operator new(std::size_t s);", // No break here.
6951                Style);
6952   verifyFormat("void *\n"
6953                "operator new(std::size_t s) {}",
6954                Style);
6955   verifyFormat("void *\n"
6956                "operator delete[](void *ptr) {}",
6957                Style);
6958   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
6959   verifyFormat("const char *\n"
6960                "f(void)\n" // Break here.
6961                "{\n"
6962                "  return \"\";\n"
6963                "}\n"
6964                "const char *bar(void);\n", // No break here.
6965                Style);
6966   verifyFormat("template <class T>\n"
6967                "T *\n"     // Problem here: no line break
6968                "f(T &c)\n" // Break here.
6969                "{\n"
6970                "  return NULL;\n"
6971                "}\n"
6972                "template <class T> T *f(T &c);\n", // No break here.
6973                Style);
6974   verifyFormat("int\n"
6975                "foo(A<bool> a)\n"
6976                "{\n"
6977                "  return a;\n"
6978                "}\n",
6979                Style);
6980   verifyFormat("int\n"
6981                "foo(A<8> a)\n"
6982                "{\n"
6983                "  return a;\n"
6984                "}\n",
6985                Style);
6986   verifyFormat("int\n"
6987                "foo(A<B<bool>, 8> a)\n"
6988                "{\n"
6989                "  return a;\n"
6990                "}\n",
6991                Style);
6992   verifyFormat("int\n"
6993                "foo(A<B<8>, bool> a)\n"
6994                "{\n"
6995                "  return a;\n"
6996                "}\n",
6997                Style);
6998   verifyFormat("int\n"
6999                "foo(A<B<bool>, bool> a)\n"
7000                "{\n"
7001                "  return a;\n"
7002                "}\n",
7003                Style);
7004   verifyFormat("int\n"
7005                "foo(A<B<8>, 8> a)\n"
7006                "{\n"
7007                "  return a;\n"
7008                "}\n",
7009                Style);
7010 
7011   Style = getGNUStyle();
7012 
7013   // Test for comments at the end of function declarations.
7014   verifyFormat("void\n"
7015                "foo (int a, /*abc*/ int b) // def\n"
7016                "{\n"
7017                "}\n",
7018                Style);
7019 
7020   verifyFormat("void\n"
7021                "foo (int a, /* abc */ int b) /* def */\n"
7022                "{\n"
7023                "}\n",
7024                Style);
7025 
7026   // Definitions that should not break after return type
7027   verifyFormat("void foo (int a, int b); // def\n", Style);
7028   verifyFormat("void foo (int a, int b); /* def */\n", Style);
7029   verifyFormat("void foo (int a, int b);\n", Style);
7030 }
7031 
7032 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
7033   FormatStyle NoBreak = getLLVMStyle();
7034   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
7035   FormatStyle Break = getLLVMStyle();
7036   Break.AlwaysBreakBeforeMultilineStrings = true;
7037   verifyFormat("aaaa = \"bbbb\"\n"
7038                "       \"cccc\";",
7039                NoBreak);
7040   verifyFormat("aaaa =\n"
7041                "    \"bbbb\"\n"
7042                "    \"cccc\";",
7043                Break);
7044   verifyFormat("aaaa(\"bbbb\"\n"
7045                "     \"cccc\");",
7046                NoBreak);
7047   verifyFormat("aaaa(\n"
7048                "    \"bbbb\"\n"
7049                "    \"cccc\");",
7050                Break);
7051   verifyFormat("aaaa(qqq, \"bbbb\"\n"
7052                "          \"cccc\");",
7053                NoBreak);
7054   verifyFormat("aaaa(qqq,\n"
7055                "     \"bbbb\"\n"
7056                "     \"cccc\");",
7057                Break);
7058   verifyFormat("aaaa(qqq,\n"
7059                "     L\"bbbb\"\n"
7060                "     L\"cccc\");",
7061                Break);
7062   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
7063                "                      \"bbbb\"));",
7064                Break);
7065   verifyFormat("string s = someFunction(\n"
7066                "    \"abc\"\n"
7067                "    \"abc\");",
7068                Break);
7069 
7070   // As we break before unary operators, breaking right after them is bad.
7071   verifyFormat("string foo = abc ? \"x\"\n"
7072                "                   \"blah blah blah blah blah blah\"\n"
7073                "                 : \"y\";",
7074                Break);
7075 
7076   // Don't break if there is no column gain.
7077   verifyFormat("f(\"aaaa\"\n"
7078                "  \"bbbb\");",
7079                Break);
7080 
7081   // Treat literals with escaped newlines like multi-line string literals.
7082   EXPECT_EQ("x = \"a\\\n"
7083             "b\\\n"
7084             "c\";",
7085             format("x = \"a\\\n"
7086                    "b\\\n"
7087                    "c\";",
7088                    NoBreak));
7089   EXPECT_EQ("xxxx =\n"
7090             "    \"a\\\n"
7091             "b\\\n"
7092             "c\";",
7093             format("xxxx = \"a\\\n"
7094                    "b\\\n"
7095                    "c\";",
7096                    Break));
7097 
7098   EXPECT_EQ("NSString *const kString =\n"
7099             "    @\"aaaa\"\n"
7100             "    @\"bbbb\";",
7101             format("NSString *const kString = @\"aaaa\"\n"
7102                    "@\"bbbb\";",
7103                    Break));
7104 
7105   Break.ColumnLimit = 0;
7106   verifyFormat("const char *hello = \"hello llvm\";", Break);
7107 }
7108 
7109 TEST_F(FormatTest, AlignsPipes) {
7110   verifyFormat(
7111       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7112       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7113       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7114   verifyFormat(
7115       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
7116       "                     << aaaaaaaaaaaaaaaaaaaa;");
7117   verifyFormat(
7118       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7119       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7120   verifyFormat(
7121       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7122       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7123   verifyFormat(
7124       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
7125       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
7126       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
7127   verifyFormat(
7128       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7129       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7130       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7131   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7132                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7133                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7134                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7135   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
7136                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
7137   verifyFormat(
7138       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7139       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7140   verifyFormat(
7141       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
7142       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
7143 
7144   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
7145                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
7146   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7147                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7148                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
7149                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
7150   verifyFormat("LOG_IF(aaa == //\n"
7151                "       bbb)\n"
7152                "    << a << b;");
7153 
7154   // But sometimes, breaking before the first "<<" is desirable.
7155   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7156                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
7157   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
7158                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7159                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7160   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
7161                "    << BEF << IsTemplate << Description << E->getType();");
7162   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7163                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7164                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7165   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7166                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7167                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7168                "    << aaa;");
7169 
7170   verifyFormat(
7171       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7172       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7173 
7174   // Incomplete string literal.
7175   EXPECT_EQ("llvm::errs() << \"\n"
7176             "             << a;",
7177             format("llvm::errs() << \"\n<<a;"));
7178 
7179   verifyFormat("void f() {\n"
7180                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
7181                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
7182                "}");
7183 
7184   // Handle 'endl'.
7185   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
7186                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
7187   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
7188 
7189   // Handle '\n'.
7190   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
7191                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
7192   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
7193                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
7194   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
7195                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
7196   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
7197 }
7198 
7199 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
7200   verifyFormat("return out << \"somepacket = {\\n\"\n"
7201                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
7202                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
7203                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
7204                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
7205                "           << \"}\";");
7206 
7207   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
7208                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
7209                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
7210   verifyFormat(
7211       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
7212       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
7213       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
7214       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
7215       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
7216   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
7217                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7218   verifyFormat(
7219       "void f() {\n"
7220       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
7221       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7222       "}");
7223 
7224   // Breaking before the first "<<" is generally not desirable.
7225   verifyFormat(
7226       "llvm::errs()\n"
7227       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7228       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7229       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7230       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7231       getLLVMStyleWithColumns(70));
7232   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7233                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7234                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7235                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7236                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7237                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7238                getLLVMStyleWithColumns(70));
7239 
7240   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
7241                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
7242                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
7243   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
7244                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
7245                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
7246   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
7247                "           (aaaa + aaaa);",
7248                getLLVMStyleWithColumns(40));
7249   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
7250                "                  (aaaaaaa + aaaaa));",
7251                getLLVMStyleWithColumns(40));
7252   verifyFormat(
7253       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
7254       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
7255       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
7256 }
7257 
7258 TEST_F(FormatTest, UnderstandsEquals) {
7259   verifyFormat(
7260       "aaaaaaaaaaaaaaaaa =\n"
7261       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7262   verifyFormat(
7263       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7264       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
7265   verifyFormat(
7266       "if (a) {\n"
7267       "  f();\n"
7268       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7269       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
7270       "}");
7271 
7272   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7273                "        100000000 + 10000000) {\n}");
7274 }
7275 
7276 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
7277   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
7278                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
7279 
7280   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
7281                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
7282 
7283   verifyFormat(
7284       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
7285       "                                                          Parameter2);");
7286 
7287   verifyFormat(
7288       "ShortObject->shortFunction(\n"
7289       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
7290       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
7291 
7292   verifyFormat("loooooooooooooongFunction(\n"
7293                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
7294 
7295   verifyFormat(
7296       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
7297       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
7298 
7299   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
7300                "    .WillRepeatedly(Return(SomeValue));");
7301   verifyFormat("void f() {\n"
7302                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
7303                "      .Times(2)\n"
7304                "      .WillRepeatedly(Return(SomeValue));\n"
7305                "}");
7306   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
7307                "    ccccccccccccccccccccccc);");
7308   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7309                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7310                "          .aaaaa(aaaaa),\n"
7311                "      aaaaaaaaaaaaaaaaaaaaa);");
7312   verifyFormat("void f() {\n"
7313                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7314                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
7315                "}");
7316   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7317                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7318                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7319                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7320                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7321   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7322                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7323                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7324                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
7325                "}");
7326 
7327   // Here, it is not necessary to wrap at "." or "->".
7328   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
7329                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
7330   verifyFormat(
7331       "aaaaaaaaaaa->aaaaaaaaa(\n"
7332       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7333       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
7334 
7335   verifyFormat(
7336       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7337       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
7338   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
7339                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
7340   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
7341                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
7342 
7343   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7344                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7345                "    .a();");
7346 
7347   FormatStyle NoBinPacking = getLLVMStyle();
7348   NoBinPacking.BinPackParameters = false;
7349   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7350                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7351                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
7352                "                         aaaaaaaaaaaaaaaaaaa,\n"
7353                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7354                NoBinPacking);
7355 
7356   // If there is a subsequent call, change to hanging indentation.
7357   verifyFormat(
7358       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7359       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
7360       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7361   verifyFormat(
7362       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7363       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
7364   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7365                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7366                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7367   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7368                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7369                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
7370 }
7371 
7372 TEST_F(FormatTest, WrapsTemplateDeclarations) {
7373   verifyFormat("template <typename T>\n"
7374                "virtual void loooooooooooongFunction(int Param1, int Param2);");
7375   verifyFormat("template <typename T>\n"
7376                "// T should be one of {A, B}.\n"
7377                "virtual void loooooooooooongFunction(int Param1, int Param2);");
7378   verifyFormat(
7379       "template <typename T>\n"
7380       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
7381   verifyFormat("template <typename T>\n"
7382                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
7383                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
7384   verifyFormat(
7385       "template <typename T>\n"
7386       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
7387       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
7388   verifyFormat(
7389       "template <typename T>\n"
7390       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
7391       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
7392       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7393   verifyFormat("template <typename T>\n"
7394                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7395                "    int aaaaaaaaaaaaaaaaaaaaaa);");
7396   verifyFormat(
7397       "template <typename T1, typename T2 = char, typename T3 = char,\n"
7398       "          typename T4 = char>\n"
7399       "void f();");
7400   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
7401                "          template <typename> class cccccccccccccccccccccc,\n"
7402                "          typename ddddddddddddd>\n"
7403                "class C {};");
7404   verifyFormat(
7405       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
7406       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7407 
7408   verifyFormat("void f() {\n"
7409                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
7410                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
7411                "}");
7412 
7413   verifyFormat("template <typename T> class C {};");
7414   verifyFormat("template <typename T> void f();");
7415   verifyFormat("template <typename T> void f() {}");
7416   verifyFormat(
7417       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
7418       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7419       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
7420       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
7421       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7422       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
7423       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
7424       getLLVMStyleWithColumns(72));
7425   EXPECT_EQ("static_cast<A< //\n"
7426             "    B> *>(\n"
7427             "\n"
7428             ");",
7429             format("static_cast<A<//\n"
7430                    "    B>*>(\n"
7431                    "\n"
7432                    "    );"));
7433   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7434                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
7435 
7436   FormatStyle AlwaysBreak = getLLVMStyle();
7437   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7438   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
7439   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
7440   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
7441   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7442                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
7443                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
7444   verifyFormat("template <template <typename> class Fooooooo,\n"
7445                "          template <typename> class Baaaaaaar>\n"
7446                "struct C {};",
7447                AlwaysBreak);
7448   verifyFormat("template <typename T> // T can be A, B or C.\n"
7449                "struct C {};",
7450                AlwaysBreak);
7451   verifyFormat("template <enum E> class A {\n"
7452                "public:\n"
7453                "  E *f();\n"
7454                "};");
7455 
7456   FormatStyle NeverBreak = getLLVMStyle();
7457   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
7458   verifyFormat("template <typename T> class C {};", NeverBreak);
7459   verifyFormat("template <typename T> void f();", NeverBreak);
7460   verifyFormat("template <typename T> void f() {}", NeverBreak);
7461   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
7462                "bbbbbbbbbbbbbbbbbbbb) {}",
7463                NeverBreak);
7464   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7465                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
7466                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
7467                NeverBreak);
7468   verifyFormat("template <template <typename> class Fooooooo,\n"
7469                "          template <typename> class Baaaaaaar>\n"
7470                "struct C {};",
7471                NeverBreak);
7472   verifyFormat("template <typename T> // T can be A, B or C.\n"
7473                "struct C {};",
7474                NeverBreak);
7475   verifyFormat("template <enum E> class A {\n"
7476                "public:\n"
7477                "  E *f();\n"
7478                "};",
7479                NeverBreak);
7480   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
7481   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
7482                "bbbbbbbbbbbbbbbbbbbb) {}",
7483                NeverBreak);
7484 }
7485 
7486 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
7487   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
7488   Style.ColumnLimit = 60;
7489   EXPECT_EQ("// Baseline - no comments.\n"
7490             "template <\n"
7491             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
7492             "void f() {}",
7493             format("// Baseline - no comments.\n"
7494                    "template <\n"
7495                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
7496                    "void f() {}",
7497                    Style));
7498 
7499   EXPECT_EQ("template <\n"
7500             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
7501             "void f() {}",
7502             format("template <\n"
7503                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7504                    "void f() {}",
7505                    Style));
7506 
7507   EXPECT_EQ(
7508       "template <\n"
7509       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
7510       "void f() {}",
7511       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
7512              "void f() {}",
7513              Style));
7514 
7515   EXPECT_EQ(
7516       "template <\n"
7517       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
7518       "                                               // multiline\n"
7519       "void f() {}",
7520       format("template <\n"
7521              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7522              "                                              // multiline\n"
7523              "void f() {}",
7524              Style));
7525 
7526   EXPECT_EQ(
7527       "template <typename aaaaaaaaaa<\n"
7528       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
7529       "void f() {}",
7530       format(
7531           "template <\n"
7532           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
7533           "void f() {}",
7534           Style));
7535 }
7536 
7537 TEST_F(FormatTest, WrapsTemplateParameters) {
7538   FormatStyle Style = getLLVMStyle();
7539   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7540   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
7541   verifyFormat(
7542       "template <typename... a> struct q {};\n"
7543       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
7544       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
7545       "    y;",
7546       Style);
7547   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7548   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
7549   verifyFormat(
7550       "template <typename... a> struct r {};\n"
7551       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
7552       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
7553       "    y;",
7554       Style);
7555   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7556   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
7557   verifyFormat("template <typename... a> struct s {};\n"
7558                "extern s<\n"
7559                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7560                "aaaaaaaaaaaaaaaaaaaaaa,\n"
7561                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7562                "aaaaaaaaaaaaaaaaaaaaaa>\n"
7563                "    y;",
7564                Style);
7565   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7566   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
7567   verifyFormat("template <typename... a> struct t {};\n"
7568                "extern t<\n"
7569                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7570                "aaaaaaaaaaaaaaaaaaaaaa,\n"
7571                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7572                "aaaaaaaaaaaaaaaaaaaaaa>\n"
7573                "    y;",
7574                Style);
7575 }
7576 
7577 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
7578   verifyFormat(
7579       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7580       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7581   verifyFormat(
7582       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7583       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7584       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
7585 
7586   // FIXME: Should we have the extra indent after the second break?
7587   verifyFormat(
7588       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7589       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7590       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7591 
7592   verifyFormat(
7593       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
7594       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
7595 
7596   // Breaking at nested name specifiers is generally not desirable.
7597   verifyFormat(
7598       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7599       "    aaaaaaaaaaaaaaaaaaaaaaa);");
7600 
7601   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
7602                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7603                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7604                "                   aaaaaaaaaaaaaaaaaaaaa);",
7605                getLLVMStyleWithColumns(74));
7606 
7607   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7608                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7609                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7610 }
7611 
7612 TEST_F(FormatTest, UnderstandsTemplateParameters) {
7613   verifyFormat("A<int> a;");
7614   verifyFormat("A<A<A<int>>> a;");
7615   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
7616   verifyFormat("bool x = a < 1 || 2 > a;");
7617   verifyFormat("bool x = 5 < f<int>();");
7618   verifyFormat("bool x = f<int>() > 5;");
7619   verifyFormat("bool x = 5 < a<int>::x;");
7620   verifyFormat("bool x = a < 4 ? a > 2 : false;");
7621   verifyFormat("bool x = f() ? a < 2 : a > 2;");
7622 
7623   verifyGoogleFormat("A<A<int>> a;");
7624   verifyGoogleFormat("A<A<A<int>>> a;");
7625   verifyGoogleFormat("A<A<A<A<int>>>> a;");
7626   verifyGoogleFormat("A<A<int> > a;");
7627   verifyGoogleFormat("A<A<A<int> > > a;");
7628   verifyGoogleFormat("A<A<A<A<int> > > > a;");
7629   verifyGoogleFormat("A<::A<int>> a;");
7630   verifyGoogleFormat("A<::A> a;");
7631   verifyGoogleFormat("A< ::A> a;");
7632   verifyGoogleFormat("A< ::A<int> > a;");
7633   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
7634   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
7635   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
7636   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
7637   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
7638             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
7639 
7640   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
7641 
7642   // template closer followed by a token that starts with > or =
7643   verifyFormat("bool b = a<1> > 1;");
7644   verifyFormat("bool b = a<1> >= 1;");
7645   verifyFormat("int i = a<1> >> 1;");
7646   FormatStyle Style = getLLVMStyle();
7647   Style.SpaceBeforeAssignmentOperators = false;
7648   verifyFormat("bool b= a<1> == 1;", Style);
7649   verifyFormat("a<int> = 1;", Style);
7650   verifyFormat("a<int> >>= 1;", Style);
7651 
7652   verifyFormat("test >> a >> b;");
7653   verifyFormat("test << a >> b;");
7654 
7655   verifyFormat("f<int>();");
7656   verifyFormat("template <typename T> void f() {}");
7657   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
7658   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
7659                "sizeof(char)>::type>;");
7660   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
7661   verifyFormat("f(a.operator()<A>());");
7662   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7663                "      .template operator()<A>());",
7664                getLLVMStyleWithColumns(35));
7665 
7666   // Not template parameters.
7667   verifyFormat("return a < b && c > d;");
7668   verifyFormat("void f() {\n"
7669                "  while (a < b && c > d) {\n"
7670                "  }\n"
7671                "}");
7672   verifyFormat("template <typename... Types>\n"
7673                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
7674 
7675   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7676                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
7677                getLLVMStyleWithColumns(60));
7678   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
7679   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
7680   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
7681   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
7682 }
7683 
7684 TEST_F(FormatTest, UnderstandsShiftOperators) {
7685   verifyFormat("if (i < x >> 1)");
7686   verifyFormat("while (i < x >> 1)");
7687   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
7688   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
7689   verifyFormat(
7690       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
7691   verifyFormat("Foo.call<Bar<Function>>()");
7692   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
7693   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
7694                "++i, v = v >> 1)");
7695   verifyFormat("if (w<u<v<x>>, 1>::t)");
7696 }
7697 
7698 TEST_F(FormatTest, BitshiftOperatorWidth) {
7699   EXPECT_EQ("int a = 1 << 2; /* foo\n"
7700             "                   bar */",
7701             format("int    a=1<<2;  /* foo\n"
7702                    "                   bar */"));
7703 
7704   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
7705             "                     bar */",
7706             format("int  b  =256>>1 ;  /* foo\n"
7707                    "                      bar */"));
7708 }
7709 
7710 TEST_F(FormatTest, UnderstandsBinaryOperators) {
7711   verifyFormat("COMPARE(a, ==, b);");
7712   verifyFormat("auto s = sizeof...(Ts) - 1;");
7713 }
7714 
7715 TEST_F(FormatTest, UnderstandsPointersToMembers) {
7716   verifyFormat("int A::*x;");
7717   verifyFormat("int (S::*func)(void *);");
7718   verifyFormat("void f() { int (S::*func)(void *); }");
7719   verifyFormat("typedef bool *(Class::*Member)() const;");
7720   verifyFormat("void f() {\n"
7721                "  (a->*f)();\n"
7722                "  a->*x;\n"
7723                "  (a.*f)();\n"
7724                "  ((*a).*f)();\n"
7725                "  a.*x;\n"
7726                "}");
7727   verifyFormat("void f() {\n"
7728                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
7729                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
7730                "}");
7731   verifyFormat(
7732       "(aaaaaaaaaa->*bbbbbbb)(\n"
7733       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7734   FormatStyle Style = getLLVMStyle();
7735   Style.PointerAlignment = FormatStyle::PAS_Left;
7736   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
7737 }
7738 
7739 TEST_F(FormatTest, UnderstandsUnaryOperators) {
7740   verifyFormat("int a = -2;");
7741   verifyFormat("f(-1, -2, -3);");
7742   verifyFormat("a[-1] = 5;");
7743   verifyFormat("int a = 5 + -2;");
7744   verifyFormat("if (i == -1) {\n}");
7745   verifyFormat("if (i != -1) {\n}");
7746   verifyFormat("if (i > -1) {\n}");
7747   verifyFormat("if (i < -1) {\n}");
7748   verifyFormat("++(a->f());");
7749   verifyFormat("--(a->f());");
7750   verifyFormat("(a->f())++;");
7751   verifyFormat("a[42]++;");
7752   verifyFormat("if (!(a->f())) {\n}");
7753   verifyFormat("if (!+i) {\n}");
7754   verifyFormat("~&a;");
7755 
7756   verifyFormat("a-- > b;");
7757   verifyFormat("b ? -a : c;");
7758   verifyFormat("n * sizeof char16;");
7759   verifyFormat("n * alignof char16;", getGoogleStyle());
7760   verifyFormat("sizeof(char);");
7761   verifyFormat("alignof(char);", getGoogleStyle());
7762 
7763   verifyFormat("return -1;");
7764   verifyFormat("throw -1;");
7765   verifyFormat("switch (a) {\n"
7766                "case -1:\n"
7767                "  break;\n"
7768                "}");
7769   verifyFormat("#define X -1");
7770   verifyFormat("#define X -kConstant");
7771 
7772   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
7773   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
7774 
7775   verifyFormat("int a = /* confusing comment */ -1;");
7776   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
7777   verifyFormat("int a = i /* confusing comment */++;");
7778 
7779   verifyFormat("co_yield -1;");
7780   verifyFormat("co_return -1;");
7781 
7782   // Check that * is not treated as a binary operator when we set
7783   // PointerAlignment as PAS_Left after a keyword and not a declaration.
7784   FormatStyle PASLeftStyle = getLLVMStyle();
7785   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
7786   verifyFormat("co_return *a;", PASLeftStyle);
7787   verifyFormat("co_await *a;", PASLeftStyle);
7788   verifyFormat("co_yield *a", PASLeftStyle);
7789   verifyFormat("return *a;", PASLeftStyle);
7790 }
7791 
7792 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
7793   verifyFormat("if (!aaaaaaaaaa( // break\n"
7794                "        aaaaa)) {\n"
7795                "}");
7796   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
7797                "    aaaaa));");
7798   verifyFormat("*aaa = aaaaaaa( // break\n"
7799                "    bbbbbb);");
7800 }
7801 
7802 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
7803   verifyFormat("bool operator<();");
7804   verifyFormat("bool operator>();");
7805   verifyFormat("bool operator=();");
7806   verifyFormat("bool operator==();");
7807   verifyFormat("bool operator!=();");
7808   verifyFormat("int operator+();");
7809   verifyFormat("int operator++();");
7810   verifyFormat("int operator++(int) volatile noexcept;");
7811   verifyFormat("bool operator,();");
7812   verifyFormat("bool operator();");
7813   verifyFormat("bool operator()();");
7814   verifyFormat("bool operator[]();");
7815   verifyFormat("operator bool();");
7816   verifyFormat("operator int();");
7817   verifyFormat("operator void *();");
7818   verifyFormat("operator SomeType<int>();");
7819   verifyFormat("operator SomeType<int, int>();");
7820   verifyFormat("operator SomeType<SomeType<int>>();");
7821   verifyFormat("void *operator new(std::size_t size);");
7822   verifyFormat("void *operator new[](std::size_t size);");
7823   verifyFormat("void operator delete(void *ptr);");
7824   verifyFormat("void operator delete[](void *ptr);");
7825   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
7826                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
7827   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
7828                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
7829 
7830   verifyFormat(
7831       "ostream &operator<<(ostream &OutputStream,\n"
7832       "                    SomeReallyLongType WithSomeReallyLongValue);");
7833   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
7834                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
7835                "  return left.group < right.group;\n"
7836                "}");
7837   verifyFormat("SomeType &operator=(const SomeType &S);");
7838   verifyFormat("f.template operator()<int>();");
7839 
7840   verifyGoogleFormat("operator void*();");
7841   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
7842   verifyGoogleFormat("operator ::A();");
7843 
7844   verifyFormat("using A::operator+;");
7845   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
7846                "int i;");
7847 }
7848 
7849 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
7850   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
7851   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
7852   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
7853   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
7854   verifyFormat("Deleted &operator=(const Deleted &) &;");
7855   verifyFormat("Deleted &operator=(const Deleted &) &&;");
7856   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
7857   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
7858   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
7859   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
7860   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
7861   verifyFormat("void Fn(T const &) const &;");
7862   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
7863   verifyFormat("template <typename T>\n"
7864                "void F(T) && = delete;",
7865                getGoogleStyle());
7866 
7867   FormatStyle AlignLeft = getLLVMStyle();
7868   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
7869   verifyFormat("void A::b() && {}", AlignLeft);
7870   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
7871   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
7872                AlignLeft);
7873   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
7874   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
7875   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
7876   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
7877   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
7878   verifyFormat("auto Function(T) & -> void;", AlignLeft);
7879   verifyFormat("void Fn(T const&) const&;", AlignLeft);
7880   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
7881 
7882   FormatStyle Spaces = getLLVMStyle();
7883   Spaces.SpacesInCStyleCastParentheses = true;
7884   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
7885   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
7886   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
7887   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
7888 
7889   Spaces.SpacesInCStyleCastParentheses = false;
7890   Spaces.SpacesInParentheses = true;
7891   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
7892   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
7893                Spaces);
7894   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
7895   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
7896 
7897   FormatStyle BreakTemplate = getLLVMStyle();
7898   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7899 
7900   verifyFormat("struct f {\n"
7901                "  template <class T>\n"
7902                "  int &foo(const std::string &str) &noexcept {}\n"
7903                "};",
7904                BreakTemplate);
7905 
7906   verifyFormat("struct f {\n"
7907                "  template <class T>\n"
7908                "  int &foo(const std::string &str) &&noexcept {}\n"
7909                "};",
7910                BreakTemplate);
7911 
7912   verifyFormat("struct f {\n"
7913                "  template <class T>\n"
7914                "  int &foo(const std::string &str) const &noexcept {}\n"
7915                "};",
7916                BreakTemplate);
7917 
7918   verifyFormat("struct f {\n"
7919                "  template <class T>\n"
7920                "  int &foo(const std::string &str) const &noexcept {}\n"
7921                "};",
7922                BreakTemplate);
7923 
7924   verifyFormat("struct f {\n"
7925                "  template <class T>\n"
7926                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
7927                "};",
7928                BreakTemplate);
7929 
7930   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
7931   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
7932       FormatStyle::BTDS_Yes;
7933   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
7934 
7935   verifyFormat("struct f {\n"
7936                "  template <class T>\n"
7937                "  int& foo(const std::string& str) & noexcept {}\n"
7938                "};",
7939                AlignLeftBreakTemplate);
7940 
7941   verifyFormat("struct f {\n"
7942                "  template <class T>\n"
7943                "  int& foo(const std::string& str) && noexcept {}\n"
7944                "};",
7945                AlignLeftBreakTemplate);
7946 
7947   verifyFormat("struct f {\n"
7948                "  template <class T>\n"
7949                "  int& foo(const std::string& str) const& noexcept {}\n"
7950                "};",
7951                AlignLeftBreakTemplate);
7952 
7953   verifyFormat("struct f {\n"
7954                "  template <class T>\n"
7955                "  int& foo(const std::string& str) const&& noexcept {}\n"
7956                "};",
7957                AlignLeftBreakTemplate);
7958 
7959   verifyFormat("struct f {\n"
7960                "  template <class T>\n"
7961                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
7962                "};",
7963                AlignLeftBreakTemplate);
7964 
7965   // The `&` in `Type&` should not be confused with a trailing `&` of
7966   // DEPRECATED(reason) member function.
7967   verifyFormat("struct f {\n"
7968                "  template <class T>\n"
7969                "  DEPRECATED(reason)\n"
7970                "  Type &foo(arguments) {}\n"
7971                "};",
7972                BreakTemplate);
7973 
7974   verifyFormat("struct f {\n"
7975                "  template <class T>\n"
7976                "  DEPRECATED(reason)\n"
7977                "  Type& foo(arguments) {}\n"
7978                "};",
7979                AlignLeftBreakTemplate);
7980 
7981   verifyFormat("void (*foopt)(int) = &func;");
7982 }
7983 
7984 TEST_F(FormatTest, UnderstandsNewAndDelete) {
7985   verifyFormat("void f() {\n"
7986                "  A *a = new A;\n"
7987                "  A *a = new (placement) A;\n"
7988                "  delete a;\n"
7989                "  delete (A *)a;\n"
7990                "}");
7991   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
7992                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
7993   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7994                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
7995                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
7996   verifyFormat("delete[] h->p;");
7997 }
7998 
7999 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
8000   verifyFormat("int *f(int *a) {}");
8001   verifyFormat("int main(int argc, char **argv) {}");
8002   verifyFormat("Test::Test(int b) : a(b * b) {}");
8003   verifyIndependentOfContext("f(a, *a);");
8004   verifyFormat("void g() { f(*a); }");
8005   verifyIndependentOfContext("int a = b * 10;");
8006   verifyIndependentOfContext("int a = 10 * b;");
8007   verifyIndependentOfContext("int a = b * c;");
8008   verifyIndependentOfContext("int a += b * c;");
8009   verifyIndependentOfContext("int a -= b * c;");
8010   verifyIndependentOfContext("int a *= b * c;");
8011   verifyIndependentOfContext("int a /= b * c;");
8012   verifyIndependentOfContext("int a = *b;");
8013   verifyIndependentOfContext("int a = *b * c;");
8014   verifyIndependentOfContext("int a = b * *c;");
8015   verifyIndependentOfContext("int a = b * (10);");
8016   verifyIndependentOfContext("S << b * (10);");
8017   verifyIndependentOfContext("return 10 * b;");
8018   verifyIndependentOfContext("return *b * *c;");
8019   verifyIndependentOfContext("return a & ~b;");
8020   verifyIndependentOfContext("f(b ? *c : *d);");
8021   verifyIndependentOfContext("int a = b ? *c : *d;");
8022   verifyIndependentOfContext("*b = a;");
8023   verifyIndependentOfContext("a * ~b;");
8024   verifyIndependentOfContext("a * !b;");
8025   verifyIndependentOfContext("a * +b;");
8026   verifyIndependentOfContext("a * -b;");
8027   verifyIndependentOfContext("a * ++b;");
8028   verifyIndependentOfContext("a * --b;");
8029   verifyIndependentOfContext("a[4] * b;");
8030   verifyIndependentOfContext("a[a * a] = 1;");
8031   verifyIndependentOfContext("f() * b;");
8032   verifyIndependentOfContext("a * [self dostuff];");
8033   verifyIndependentOfContext("int x = a * (a + b);");
8034   verifyIndependentOfContext("(a *)(a + b);");
8035   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
8036   verifyIndependentOfContext("int *pa = (int *)&a;");
8037   verifyIndependentOfContext("return sizeof(int **);");
8038   verifyIndependentOfContext("return sizeof(int ******);");
8039   verifyIndependentOfContext("return (int **&)a;");
8040   verifyIndependentOfContext("f((*PointerToArray)[10]);");
8041   verifyFormat("void f(Type (*parameter)[10]) {}");
8042   verifyFormat("void f(Type (&parameter)[10]) {}");
8043   verifyGoogleFormat("return sizeof(int**);");
8044   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
8045   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
8046   verifyFormat("auto a = [](int **&, int ***) {};");
8047   verifyFormat("auto PointerBinding = [](const char *S) {};");
8048   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
8049   verifyFormat("[](const decltype(*a) &value) {}");
8050   verifyFormat("[](const typeof(*a) &value) {}");
8051   verifyFormat("[](const _Atomic(a *) &value) {}");
8052   verifyFormat("[](const __underlying_type(a) &value) {}");
8053   verifyFormat("decltype(a * b) F();");
8054   verifyFormat("typeof(a * b) F();");
8055   verifyFormat("#define MACRO() [](A *a) { return 1; }");
8056   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
8057   verifyIndependentOfContext("typedef void (*f)(int *a);");
8058   verifyIndependentOfContext("int i{a * b};");
8059   verifyIndependentOfContext("aaa && aaa->f();");
8060   verifyIndependentOfContext("int x = ~*p;");
8061   verifyFormat("Constructor() : a(a), area(width * height) {}");
8062   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
8063   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
8064   verifyFormat("void f() { f(a, c * d); }");
8065   verifyFormat("void f() { f(new a(), c * d); }");
8066   verifyFormat("void f(const MyOverride &override);");
8067   verifyFormat("void f(const MyFinal &final);");
8068   verifyIndependentOfContext("bool a = f() && override.f();");
8069   verifyIndependentOfContext("bool a = f() && final.f();");
8070 
8071   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
8072 
8073   verifyIndependentOfContext("A<int *> a;");
8074   verifyIndependentOfContext("A<int **> a;");
8075   verifyIndependentOfContext("A<int *, int *> a;");
8076   verifyIndependentOfContext("A<int *[]> a;");
8077   verifyIndependentOfContext(
8078       "const char *const p = reinterpret_cast<const char *const>(q);");
8079   verifyIndependentOfContext("A<int **, int **> a;");
8080   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
8081   verifyFormat("for (char **a = b; *a; ++a) {\n}");
8082   verifyFormat("for (; a && b;) {\n}");
8083   verifyFormat("bool foo = true && [] { return false; }();");
8084 
8085   verifyFormat(
8086       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8087       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8088 
8089   verifyGoogleFormat("int const* a = &b;");
8090   verifyGoogleFormat("**outparam = 1;");
8091   verifyGoogleFormat("*outparam = a * b;");
8092   verifyGoogleFormat("int main(int argc, char** argv) {}");
8093   verifyGoogleFormat("A<int*> a;");
8094   verifyGoogleFormat("A<int**> a;");
8095   verifyGoogleFormat("A<int*, int*> a;");
8096   verifyGoogleFormat("A<int**, int**> a;");
8097   verifyGoogleFormat("f(b ? *c : *d);");
8098   verifyGoogleFormat("int a = b ? *c : *d;");
8099   verifyGoogleFormat("Type* t = **x;");
8100   verifyGoogleFormat("Type* t = *++*x;");
8101   verifyGoogleFormat("*++*x;");
8102   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
8103   verifyGoogleFormat("Type* t = x++ * y;");
8104   verifyGoogleFormat(
8105       "const char* const p = reinterpret_cast<const char* const>(q);");
8106   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
8107   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
8108   verifyGoogleFormat("template <typename T>\n"
8109                      "void f(int i = 0, SomeType** temps = NULL);");
8110 
8111   FormatStyle Left = getLLVMStyle();
8112   Left.PointerAlignment = FormatStyle::PAS_Left;
8113   verifyFormat("x = *a(x) = *a(y);", Left);
8114   verifyFormat("for (;; *a = b) {\n}", Left);
8115   verifyFormat("return *this += 1;", Left);
8116   verifyFormat("throw *x;", Left);
8117   verifyFormat("delete *x;", Left);
8118   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
8119   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
8120   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
8121   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
8122   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
8123   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
8124   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
8125   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
8126   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
8127 
8128   verifyIndependentOfContext("a = *(x + y);");
8129   verifyIndependentOfContext("a = &(x + y);");
8130   verifyIndependentOfContext("*(x + y).call();");
8131   verifyIndependentOfContext("&(x + y)->call();");
8132   verifyFormat("void f() { &(*I).first; }");
8133 
8134   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
8135   verifyFormat(
8136       "int *MyValues = {\n"
8137       "    *A, // Operator detection might be confused by the '{'\n"
8138       "    *BB // Operator detection might be confused by previous comment\n"
8139       "};");
8140 
8141   verifyIndependentOfContext("if (int *a = &b)");
8142   verifyIndependentOfContext("if (int &a = *b)");
8143   verifyIndependentOfContext("if (a & b[i])");
8144   verifyIndependentOfContext("if constexpr (a & b[i])");
8145   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
8146   verifyIndependentOfContext("if (a * (b * c))");
8147   verifyIndependentOfContext("if constexpr (a * (b * c))");
8148   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
8149   verifyIndependentOfContext("if (a::b::c::d & b[i])");
8150   verifyIndependentOfContext("if (*b[i])");
8151   verifyIndependentOfContext("if (int *a = (&b))");
8152   verifyIndependentOfContext("while (int *a = &b)");
8153   verifyIndependentOfContext("while (a * (b * c))");
8154   verifyIndependentOfContext("size = sizeof *a;");
8155   verifyIndependentOfContext("if (a && (b = c))");
8156   verifyFormat("void f() {\n"
8157                "  for (const int &v : Values) {\n"
8158                "  }\n"
8159                "}");
8160   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
8161   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
8162   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
8163 
8164   verifyFormat("#define A (!a * b)");
8165   verifyFormat("#define MACRO     \\\n"
8166                "  int *i = a * b; \\\n"
8167                "  void f(a *b);",
8168                getLLVMStyleWithColumns(19));
8169 
8170   verifyIndependentOfContext("A = new SomeType *[Length];");
8171   verifyIndependentOfContext("A = new SomeType *[Length]();");
8172   verifyIndependentOfContext("T **t = new T *;");
8173   verifyIndependentOfContext("T **t = new T *();");
8174   verifyGoogleFormat("A = new SomeType*[Length]();");
8175   verifyGoogleFormat("A = new SomeType*[Length];");
8176   verifyGoogleFormat("T** t = new T*;");
8177   verifyGoogleFormat("T** t = new T*();");
8178 
8179   verifyFormat("STATIC_ASSERT((a & b) == 0);");
8180   verifyFormat("STATIC_ASSERT(0 == (a & b));");
8181   verifyFormat("template <bool a, bool b> "
8182                "typename t::if<x && y>::type f() {}");
8183   verifyFormat("template <int *y> f() {}");
8184   verifyFormat("vector<int *> v;");
8185   verifyFormat("vector<int *const> v;");
8186   verifyFormat("vector<int *const **const *> v;");
8187   verifyFormat("vector<int *volatile> v;");
8188   verifyFormat("vector<a *_Nonnull> v;");
8189   verifyFormat("vector<a *_Nullable> v;");
8190   verifyFormat("vector<a *_Null_unspecified> v;");
8191   verifyFormat("vector<a *__ptr32> v;");
8192   verifyFormat("vector<a *__ptr64> v;");
8193   verifyFormat("vector<a *__capability> v;");
8194   FormatStyle TypeMacros = getLLVMStyle();
8195   TypeMacros.TypenameMacros = {"LIST"};
8196   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
8197   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
8198   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
8199   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
8200   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
8201 
8202   FormatStyle CustomQualifier = getLLVMStyle();
8203   // Add indentifers that should not be parsed as a qualifier by default.
8204   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
8205   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
8206   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
8207   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
8208   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
8209   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
8210   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
8211   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
8212   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
8213   verifyFormat("vector<a * _NotAQualifier> v;");
8214   verifyFormat("vector<a * __not_a_qualifier> v;");
8215   verifyFormat("vector<a * b> v;");
8216   verifyFormat("foo<b && false>();");
8217   verifyFormat("foo<b & 1>();");
8218   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
8219   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
8220   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
8221   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
8222   verifyFormat(
8223       "template <class T, class = typename std::enable_if<\n"
8224       "                       std::is_integral<T>::value &&\n"
8225       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
8226       "void F();",
8227       getLLVMStyleWithColumns(70));
8228   verifyFormat("template <class T,\n"
8229                "          class = typename std::enable_if<\n"
8230                "              std::is_integral<T>::value &&\n"
8231                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
8232                "          class U>\n"
8233                "void F();",
8234                getLLVMStyleWithColumns(70));
8235   verifyFormat(
8236       "template <class T,\n"
8237       "          class = typename ::std::enable_if<\n"
8238       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
8239       "void F();",
8240       getGoogleStyleWithColumns(68));
8241 
8242   verifyIndependentOfContext("MACRO(int *i);");
8243   verifyIndependentOfContext("MACRO(auto *a);");
8244   verifyIndependentOfContext("MACRO(const A *a);");
8245   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
8246   verifyIndependentOfContext("MACRO(decltype(A) *a);");
8247   verifyIndependentOfContext("MACRO(typeof(A) *a);");
8248   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
8249   verifyIndependentOfContext("MACRO(A *const a);");
8250   verifyIndependentOfContext("MACRO(A *restrict a);");
8251   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
8252   verifyIndependentOfContext("MACRO(A *__restrict a);");
8253   verifyIndependentOfContext("MACRO(A *volatile a);");
8254   verifyIndependentOfContext("MACRO(A *__volatile a);");
8255   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
8256   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
8257   verifyIndependentOfContext("MACRO(A *_Nullable a);");
8258   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
8259   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
8260   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
8261   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
8262   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
8263   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
8264   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
8265   verifyIndependentOfContext("MACRO(A *__capability);");
8266   verifyIndependentOfContext("MACRO(A &__capability);");
8267   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
8268   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
8269   // If we add __my_qualifier to AttributeMacros it should always be parsed as
8270   // a type declaration:
8271   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
8272   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
8273   // Also check that TypenameMacros prevents parsing it as multiplication:
8274   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
8275   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
8276 
8277   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
8278   verifyFormat("void f() { f(float{1}, a * a); }");
8279   // FIXME: Is there a way to make this work?
8280   // verifyIndependentOfContext("MACRO(A *a);");
8281   verifyFormat("MACRO(A &B);");
8282   verifyFormat("MACRO(A *B);");
8283   verifyFormat("void f() { MACRO(A * B); }");
8284   verifyFormat("void f() { MACRO(A & B); }");
8285 
8286   // This lambda was mis-formatted after D88956 (treating it as a binop):
8287   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
8288   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
8289   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
8290   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
8291 
8292   verifyFormat("DatumHandle const *operator->() const { return input_; }");
8293   verifyFormat("return options != nullptr && operator==(*options);");
8294 
8295   EXPECT_EQ("#define OP(x)                                    \\\n"
8296             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
8297             "    return s << a.DebugString();                 \\\n"
8298             "  }",
8299             format("#define OP(x) \\\n"
8300                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
8301                    "    return s << a.DebugString(); \\\n"
8302                    "  }",
8303                    getLLVMStyleWithColumns(50)));
8304 
8305   // FIXME: We cannot handle this case yet; we might be able to figure out that
8306   // foo<x> d > v; doesn't make sense.
8307   verifyFormat("foo<a<b && c> d> v;");
8308 
8309   FormatStyle PointerMiddle = getLLVMStyle();
8310   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
8311   verifyFormat("delete *x;", PointerMiddle);
8312   verifyFormat("int * x;", PointerMiddle);
8313   verifyFormat("int *[] x;", PointerMiddle);
8314   verifyFormat("template <int * y> f() {}", PointerMiddle);
8315   verifyFormat("int * f(int * a) {}", PointerMiddle);
8316   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
8317   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
8318   verifyFormat("A<int *> a;", PointerMiddle);
8319   verifyFormat("A<int **> a;", PointerMiddle);
8320   verifyFormat("A<int *, int *> a;", PointerMiddle);
8321   verifyFormat("A<int *[]> a;", PointerMiddle);
8322   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
8323   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
8324   verifyFormat("T ** t = new T *;", PointerMiddle);
8325 
8326   // Member function reference qualifiers aren't binary operators.
8327   verifyFormat("string // break\n"
8328                "operator()() & {}");
8329   verifyFormat("string // break\n"
8330                "operator()() && {}");
8331   verifyGoogleFormat("template <typename T>\n"
8332                      "auto x() & -> int {}");
8333 }
8334 
8335 TEST_F(FormatTest, UnderstandsAttributes) {
8336   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
8337   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
8338                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
8339   FormatStyle AfterType = getLLVMStyle();
8340   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8341   verifyFormat("__attribute__((nodebug)) void\n"
8342                "foo() {}\n",
8343                AfterType);
8344   verifyFormat("__unused void\n"
8345                "foo() {}",
8346                AfterType);
8347 
8348   FormatStyle CustomAttrs = getLLVMStyle();
8349   CustomAttrs.AttributeMacros.push_back("__unused");
8350   CustomAttrs.AttributeMacros.push_back("__attr1");
8351   CustomAttrs.AttributeMacros.push_back("__attr2");
8352   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
8353   verifyFormat("vector<SomeType *__attribute((foo))> v;");
8354   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
8355   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
8356   // Check that it is parsed as a multiplication without AttributeMacros and
8357   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
8358   verifyFormat("vector<SomeType * __attr1> v;");
8359   verifyFormat("vector<SomeType __attr1 *> v;");
8360   verifyFormat("vector<SomeType __attr1 *const> v;");
8361   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
8362   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
8363   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
8364   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
8365   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
8366   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
8367   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
8368   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
8369 
8370   // Check that these are not parsed as function declarations:
8371   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8372   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
8373   verifyFormat("SomeType s(InitValue);", CustomAttrs);
8374   verifyFormat("SomeType s{InitValue};", CustomAttrs);
8375   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
8376   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
8377   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
8378   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
8379   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
8380   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
8381 }
8382 
8383 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
8384   // Check that qualifiers on pointers don't break parsing of casts.
8385   verifyFormat("x = (foo *const)*v;");
8386   verifyFormat("x = (foo *volatile)*v;");
8387   verifyFormat("x = (foo *restrict)*v;");
8388   verifyFormat("x = (foo *__attribute__((foo)))*v;");
8389   verifyFormat("x = (foo *_Nonnull)*v;");
8390   verifyFormat("x = (foo *_Nullable)*v;");
8391   verifyFormat("x = (foo *_Null_unspecified)*v;");
8392   verifyFormat("x = (foo *_Nonnull)*v;");
8393   verifyFormat("x = (foo *[[clang::attr]])*v;");
8394   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
8395   verifyFormat("x = (foo *__ptr32)*v;");
8396   verifyFormat("x = (foo *__ptr64)*v;");
8397   verifyFormat("x = (foo *__capability)*v;");
8398 
8399   // Check that we handle multiple trailing qualifiers and skip them all to
8400   // determine that the expression is a cast to a pointer type.
8401   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
8402   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
8403   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
8404   StringRef AllQualifiers =
8405       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
8406       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
8407   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
8408   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
8409 
8410   // Also check that address-of is not parsed as a binary bitwise-and:
8411   verifyFormat("x = (foo *const)&v;");
8412   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
8413   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
8414 
8415   // Check custom qualifiers:
8416   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
8417   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
8418   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
8419   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
8420   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
8421                CustomQualifier);
8422   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
8423                CustomQualifier);
8424 
8425   // Check that unknown identifiers result in binary operator parsing:
8426   verifyFormat("x = (foo * __unknown_qualifier) * v;");
8427   verifyFormat("x = (foo * __unknown_qualifier) & v;");
8428 }
8429 
8430 TEST_F(FormatTest, UnderstandsSquareAttributes) {
8431   verifyFormat("SomeType s [[unused]] (InitValue);");
8432   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
8433   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
8434   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
8435   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
8436   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8437                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
8438   verifyFormat("[[nodiscard]] bool f() { return false; }");
8439   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
8440   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
8441   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
8442 
8443   // Make sure we do not mistake attributes for array subscripts.
8444   verifyFormat("int a() {}\n"
8445                "[[unused]] int b() {}\n");
8446   verifyFormat("NSArray *arr;\n"
8447                "arr[[Foo() bar]];");
8448 
8449   // On the other hand, we still need to correctly find array subscripts.
8450   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
8451 
8452   // Make sure that we do not mistake Objective-C method inside array literals
8453   // as attributes, even if those method names are also keywords.
8454   verifyFormat("@[ [foo bar] ];");
8455   verifyFormat("@[ [NSArray class] ];");
8456   verifyFormat("@[ [foo enum] ];");
8457 
8458   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
8459 
8460   // Make sure we do not parse attributes as lambda introducers.
8461   FormatStyle MultiLineFunctions = getLLVMStyle();
8462   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8463   verifyFormat("[[unused]] int b() {\n"
8464                "  return 42;\n"
8465                "}\n",
8466                MultiLineFunctions);
8467 }
8468 
8469 TEST_F(FormatTest, AttributeClass) {
8470   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
8471   verifyFormat("class S {\n"
8472                "  S(S&&) = default;\n"
8473                "};",
8474                Style);
8475   verifyFormat("class [[nodiscard]] S {\n"
8476                "  S(S&&) = default;\n"
8477                "};",
8478                Style);
8479   verifyFormat("class __attribute((maybeunused)) S {\n"
8480                "  S(S&&) = default;\n"
8481                "};",
8482                Style);
8483   verifyFormat("struct S {\n"
8484                "  S(S&&) = default;\n"
8485                "};",
8486                Style);
8487   verifyFormat("struct [[nodiscard]] S {\n"
8488                "  S(S&&) = default;\n"
8489                "};",
8490                Style);
8491 }
8492 
8493 TEST_F(FormatTest, AttributesAfterMacro) {
8494   FormatStyle Style = getLLVMStyle();
8495   verifyFormat("MACRO;\n"
8496                "__attribute__((maybe_unused)) int foo() {\n"
8497                "  //...\n"
8498                "}");
8499 
8500   verifyFormat("MACRO;\n"
8501                "[[nodiscard]] int foo() {\n"
8502                "  //...\n"
8503                "}");
8504 
8505   EXPECT_EQ("MACRO\n\n"
8506             "__attribute__((maybe_unused)) int foo() {\n"
8507             "  //...\n"
8508             "}",
8509             format("MACRO\n\n"
8510                    "__attribute__((maybe_unused)) int foo() {\n"
8511                    "  //...\n"
8512                    "}"));
8513 
8514   EXPECT_EQ("MACRO\n\n"
8515             "[[nodiscard]] int foo() {\n"
8516             "  //...\n"
8517             "}",
8518             format("MACRO\n\n"
8519                    "[[nodiscard]] int foo() {\n"
8520                    "  //...\n"
8521                    "}"));
8522 }
8523 
8524 TEST_F(FormatTest, AttributePenaltyBreaking) {
8525   FormatStyle Style = getLLVMStyle();
8526   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
8527                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
8528                Style);
8529   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
8530                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
8531                Style);
8532   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
8533                "shared_ptr<ALongTypeName> &C d) {\n}",
8534                Style);
8535 }
8536 
8537 TEST_F(FormatTest, UnderstandsEllipsis) {
8538   FormatStyle Style = getLLVMStyle();
8539   verifyFormat("int printf(const char *fmt, ...);");
8540   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
8541   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
8542 
8543   verifyFormat("template <int *...PP> a;", Style);
8544 
8545   Style.PointerAlignment = FormatStyle::PAS_Left;
8546   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
8547 
8548   verifyFormat("template <int*... PP> a;", Style);
8549 
8550   Style.PointerAlignment = FormatStyle::PAS_Middle;
8551   verifyFormat("template <int *... PP> a;", Style);
8552 }
8553 
8554 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
8555   EXPECT_EQ("int *a;\n"
8556             "int *a;\n"
8557             "int *a;",
8558             format("int *a;\n"
8559                    "int* a;\n"
8560                    "int *a;",
8561                    getGoogleStyle()));
8562   EXPECT_EQ("int* a;\n"
8563             "int* a;\n"
8564             "int* a;",
8565             format("int* a;\n"
8566                    "int* a;\n"
8567                    "int *a;",
8568                    getGoogleStyle()));
8569   EXPECT_EQ("int *a;\n"
8570             "int *a;\n"
8571             "int *a;",
8572             format("int *a;\n"
8573                    "int * a;\n"
8574                    "int *  a;",
8575                    getGoogleStyle()));
8576   EXPECT_EQ("auto x = [] {\n"
8577             "  int *a;\n"
8578             "  int *a;\n"
8579             "  int *a;\n"
8580             "};",
8581             format("auto x=[]{int *a;\n"
8582                    "int * a;\n"
8583                    "int *  a;};",
8584                    getGoogleStyle()));
8585 }
8586 
8587 TEST_F(FormatTest, UnderstandsRvalueReferences) {
8588   verifyFormat("int f(int &&a) {}");
8589   verifyFormat("int f(int a, char &&b) {}");
8590   verifyFormat("void f() { int &&a = b; }");
8591   verifyGoogleFormat("int f(int a, char&& b) {}");
8592   verifyGoogleFormat("void f() { int&& a = b; }");
8593 
8594   verifyIndependentOfContext("A<int &&> a;");
8595   verifyIndependentOfContext("A<int &&, int &&> a;");
8596   verifyGoogleFormat("A<int&&> a;");
8597   verifyGoogleFormat("A<int&&, int&&> a;");
8598 
8599   // Not rvalue references:
8600   verifyFormat("template <bool B, bool C> class A {\n"
8601                "  static_assert(B && C, \"Something is wrong\");\n"
8602                "};");
8603   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
8604   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
8605   verifyFormat("#define A(a, b) (a && b)");
8606 }
8607 
8608 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
8609   verifyFormat("void f() {\n"
8610                "  x[aaaaaaaaa -\n"
8611                "    b] = 23;\n"
8612                "}",
8613                getLLVMStyleWithColumns(15));
8614 }
8615 
8616 TEST_F(FormatTest, FormatsCasts) {
8617   verifyFormat("Type *A = static_cast<Type *>(P);");
8618   verifyFormat("Type *A = (Type *)P;");
8619   verifyFormat("Type *A = (vector<Type *, int *>)P;");
8620   verifyFormat("int a = (int)(2.0f);");
8621   verifyFormat("int a = (int)2.0f;");
8622   verifyFormat("x[(int32)y];");
8623   verifyFormat("x = (int32)y;");
8624   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
8625   verifyFormat("int a = (int)*b;");
8626   verifyFormat("int a = (int)2.0f;");
8627   verifyFormat("int a = (int)~0;");
8628   verifyFormat("int a = (int)++a;");
8629   verifyFormat("int a = (int)sizeof(int);");
8630   verifyFormat("int a = (int)+2;");
8631   verifyFormat("my_int a = (my_int)2.0f;");
8632   verifyFormat("my_int a = (my_int)sizeof(int);");
8633   verifyFormat("return (my_int)aaa;");
8634   verifyFormat("#define x ((int)-1)");
8635   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
8636   verifyFormat("#define p(q) ((int *)&q)");
8637   verifyFormat("fn(a)(b) + 1;");
8638 
8639   verifyFormat("void f() { my_int a = (my_int)*b; }");
8640   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
8641   verifyFormat("my_int a = (my_int)~0;");
8642   verifyFormat("my_int a = (my_int)++a;");
8643   verifyFormat("my_int a = (my_int)-2;");
8644   verifyFormat("my_int a = (my_int)1;");
8645   verifyFormat("my_int a = (my_int *)1;");
8646   verifyFormat("my_int a = (const my_int)-1;");
8647   verifyFormat("my_int a = (const my_int *)-1;");
8648   verifyFormat("my_int a = (my_int)(my_int)-1;");
8649   verifyFormat("my_int a = (ns::my_int)-2;");
8650   verifyFormat("case (my_int)ONE:");
8651   verifyFormat("auto x = (X)this;");
8652   // Casts in Obj-C style calls used to not be recognized as such.
8653   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
8654 
8655   // FIXME: single value wrapped with paren will be treated as cast.
8656   verifyFormat("void f(int i = (kValue)*kMask) {}");
8657 
8658   verifyFormat("{ (void)F; }");
8659 
8660   // Don't break after a cast's
8661   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8662                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
8663                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
8664 
8665   // These are not casts.
8666   verifyFormat("void f(int *) {}");
8667   verifyFormat("f(foo)->b;");
8668   verifyFormat("f(foo).b;");
8669   verifyFormat("f(foo)(b);");
8670   verifyFormat("f(foo)[b];");
8671   verifyFormat("[](foo) { return 4; }(bar);");
8672   verifyFormat("(*funptr)(foo)[4];");
8673   verifyFormat("funptrs[4](foo)[4];");
8674   verifyFormat("void f(int *);");
8675   verifyFormat("void f(int *) = 0;");
8676   verifyFormat("void f(SmallVector<int>) {}");
8677   verifyFormat("void f(SmallVector<int>);");
8678   verifyFormat("void f(SmallVector<int>) = 0;");
8679   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
8680   verifyFormat("int a = sizeof(int) * b;");
8681   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
8682   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
8683   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
8684   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
8685 
8686   // These are not casts, but at some point were confused with casts.
8687   verifyFormat("virtual void foo(int *) override;");
8688   verifyFormat("virtual void foo(char &) const;");
8689   verifyFormat("virtual void foo(int *a, char *) const;");
8690   verifyFormat("int a = sizeof(int *) + b;");
8691   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
8692   verifyFormat("bool b = f(g<int>) && c;");
8693   verifyFormat("typedef void (*f)(int i) func;");
8694   verifyFormat("void operator++(int) noexcept;");
8695   verifyFormat("void operator++(int &) noexcept;");
8696   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
8697                "&) noexcept;");
8698   verifyFormat(
8699       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
8700   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
8701   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
8702   verifyFormat("void operator delete(nothrow_t &) noexcept;");
8703   verifyFormat("void operator delete(foo &) noexcept;");
8704   verifyFormat("void operator delete(foo) noexcept;");
8705   verifyFormat("void operator delete(int) noexcept;");
8706   verifyFormat("void operator delete(int &) noexcept;");
8707   verifyFormat("void operator delete(int &) volatile noexcept;");
8708   verifyFormat("void operator delete(int &) const");
8709   verifyFormat("void operator delete(int &) = default");
8710   verifyFormat("void operator delete(int &) = delete");
8711   verifyFormat("void operator delete(int &) [[noreturn]]");
8712   verifyFormat("void operator delete(int &) throw();");
8713   verifyFormat("void operator delete(int &) throw(int);");
8714   verifyFormat("auto operator delete(int &) -> int;");
8715   verifyFormat("auto operator delete(int &) override");
8716   verifyFormat("auto operator delete(int &) final");
8717 
8718   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
8719                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8720   // FIXME: The indentation here is not ideal.
8721   verifyFormat(
8722       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8723       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
8724       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
8725 }
8726 
8727 TEST_F(FormatTest, FormatsFunctionTypes) {
8728   verifyFormat("A<bool()> a;");
8729   verifyFormat("A<SomeType()> a;");
8730   verifyFormat("A<void (*)(int, std::string)> a;");
8731   verifyFormat("A<void *(int)>;");
8732   verifyFormat("void *(*a)(int *, SomeType *);");
8733   verifyFormat("int (*func)(void *);");
8734   verifyFormat("void f() { int (*func)(void *); }");
8735   verifyFormat("template <class CallbackClass>\n"
8736                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
8737 
8738   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
8739   verifyGoogleFormat("void* (*a)(int);");
8740   verifyGoogleFormat(
8741       "template <class CallbackClass>\n"
8742       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
8743 
8744   // Other constructs can look somewhat like function types:
8745   verifyFormat("A<sizeof(*x)> a;");
8746   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
8747   verifyFormat("some_var = function(*some_pointer_var)[0];");
8748   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
8749   verifyFormat("int x = f(&h)();");
8750   verifyFormat("returnsFunction(&param1, &param2)(param);");
8751   verifyFormat("std::function<\n"
8752                "    LooooooooooongTemplatedType<\n"
8753                "        SomeType>*(\n"
8754                "        LooooooooooooooooongType type)>\n"
8755                "    function;",
8756                getGoogleStyleWithColumns(40));
8757 }
8758 
8759 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
8760   verifyFormat("A (*foo_)[6];");
8761   verifyFormat("vector<int> (*foo_)[6];");
8762 }
8763 
8764 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
8765   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8766                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
8767   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
8768                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
8769   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8770                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
8771 
8772   // Different ways of ()-initializiation.
8773   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8774                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
8775   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8776                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
8777   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8778                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
8779   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8780                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
8781 
8782   // Lambdas should not confuse the variable declaration heuristic.
8783   verifyFormat("LooooooooooooooooongType\n"
8784                "    variable(nullptr, [](A *a) {});",
8785                getLLVMStyleWithColumns(40));
8786 }
8787 
8788 TEST_F(FormatTest, BreaksLongDeclarations) {
8789   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
8790                "    AnotherNameForTheLongType;");
8791   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
8792                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8793   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8794                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
8795   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
8796                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
8797   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8798                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8799   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
8800                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8801   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
8802                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8803   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
8804                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8805   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
8806                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8807   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
8808                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8809   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
8810                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8811   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8812                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
8813   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8814                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
8815   FormatStyle Indented = getLLVMStyle();
8816   Indented.IndentWrappedFunctionNames = true;
8817   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8818                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
8819                Indented);
8820   verifyFormat(
8821       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8822       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8823       Indented);
8824   verifyFormat(
8825       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
8826       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8827       Indented);
8828   verifyFormat(
8829       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
8830       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8831       Indented);
8832 
8833   // FIXME: Without the comment, this breaks after "(".
8834   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
8835                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
8836                getGoogleStyle());
8837 
8838   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
8839                "                  int LoooooooooooooooooooongParam2) {}");
8840   verifyFormat(
8841       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
8842       "                                   SourceLocation L, IdentifierIn *II,\n"
8843       "                                   Type *T) {}");
8844   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
8845                "ReallyReaaallyLongFunctionName(\n"
8846                "    const std::string &SomeParameter,\n"
8847                "    const SomeType<string, SomeOtherTemplateParameter>\n"
8848                "        &ReallyReallyLongParameterName,\n"
8849                "    const SomeType<string, SomeOtherTemplateParameter>\n"
8850                "        &AnotherLongParameterName) {}");
8851   verifyFormat("template <typename A>\n"
8852                "SomeLoooooooooooooooooooooongType<\n"
8853                "    typename some_namespace::SomeOtherType<A>::Type>\n"
8854                "Function() {}");
8855 
8856   verifyGoogleFormat(
8857       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
8858       "    aaaaaaaaaaaaaaaaaaaaaaa;");
8859   verifyGoogleFormat(
8860       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
8861       "                                   SourceLocation L) {}");
8862   verifyGoogleFormat(
8863       "some_namespace::LongReturnType\n"
8864       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
8865       "    int first_long_parameter, int second_parameter) {}");
8866 
8867   verifyGoogleFormat("template <typename T>\n"
8868                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
8869                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
8870   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8871                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
8872 
8873   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
8874                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8875                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8876   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8877                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
8878                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
8879   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8880                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
8881                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
8882                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8883 
8884   verifyFormat("template <typename T> // Templates on own line.\n"
8885                "static int            // Some comment.\n"
8886                "MyFunction(int a);",
8887                getLLVMStyle());
8888 }
8889 
8890 TEST_F(FormatTest, FormatsAccessModifiers) {
8891   FormatStyle Style = getLLVMStyle();
8892   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
8893             FormatStyle::ELBAMS_LogicalBlock);
8894   verifyFormat("struct foo {\n"
8895                "private:\n"
8896                "  void f() {}\n"
8897                "\n"
8898                "private:\n"
8899                "  int i;\n"
8900                "\n"
8901                "protected:\n"
8902                "  int j;\n"
8903                "};\n",
8904                Style);
8905   verifyFormat("struct foo {\n"
8906                "private:\n"
8907                "  void f() {}\n"
8908                "\n"
8909                "private:\n"
8910                "  int i;\n"
8911                "\n"
8912                "protected:\n"
8913                "  int j;\n"
8914                "};\n",
8915                "struct foo {\n"
8916                "private:\n"
8917                "  void f() {}\n"
8918                "private:\n"
8919                "  int i;\n"
8920                "protected:\n"
8921                "  int j;\n"
8922                "};\n",
8923                Style);
8924   verifyFormat("struct foo { /* comment */\n"
8925                "private:\n"
8926                "  int i;\n"
8927                "  // comment\n"
8928                "private:\n"
8929                "  int j;\n"
8930                "};\n",
8931                Style);
8932   verifyFormat("struct foo {\n"
8933                "#ifdef FOO\n"
8934                "#endif\n"
8935                "private:\n"
8936                "  int i;\n"
8937                "#ifdef FOO\n"
8938                "private:\n"
8939                "#endif\n"
8940                "  int j;\n"
8941                "};\n",
8942                Style);
8943   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
8944   verifyFormat("struct foo {\n"
8945                "private:\n"
8946                "  void f() {}\n"
8947                "private:\n"
8948                "  int i;\n"
8949                "protected:\n"
8950                "  int j;\n"
8951                "};\n",
8952                Style);
8953   verifyFormat("struct foo {\n"
8954                "private:\n"
8955                "  void f() {}\n"
8956                "private:\n"
8957                "  int i;\n"
8958                "protected:\n"
8959                "  int j;\n"
8960                "};\n",
8961                "struct foo {\n"
8962                "\n"
8963                "private:\n"
8964                "  void f() {}\n"
8965                "\n"
8966                "private:\n"
8967                "  int i;\n"
8968                "\n"
8969                "protected:\n"
8970                "  int j;\n"
8971                "};\n",
8972                Style);
8973   verifyFormat("struct foo { /* comment */\n"
8974                "private:\n"
8975                "  int i;\n"
8976                "  // comment\n"
8977                "private:\n"
8978                "  int j;\n"
8979                "};\n",
8980                "struct foo { /* comment */\n"
8981                "\n"
8982                "private:\n"
8983                "  int i;\n"
8984                "  // comment\n"
8985                "\n"
8986                "private:\n"
8987                "  int j;\n"
8988                "};\n",
8989                Style);
8990   verifyFormat("struct foo {\n"
8991                "#ifdef FOO\n"
8992                "#endif\n"
8993                "private:\n"
8994                "  int i;\n"
8995                "#ifdef FOO\n"
8996                "private:\n"
8997                "#endif\n"
8998                "  int j;\n"
8999                "};\n",
9000                "struct foo {\n"
9001                "#ifdef FOO\n"
9002                "#endif\n"
9003                "\n"
9004                "private:\n"
9005                "  int i;\n"
9006                "#ifdef FOO\n"
9007                "\n"
9008                "private:\n"
9009                "#endif\n"
9010                "  int j;\n"
9011                "};\n",
9012                Style);
9013   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9014   verifyFormat("struct foo {\n"
9015                "private:\n"
9016                "  void f() {}\n"
9017                "\n"
9018                "private:\n"
9019                "  int i;\n"
9020                "\n"
9021                "protected:\n"
9022                "  int j;\n"
9023                "};\n",
9024                Style);
9025   verifyFormat("struct foo {\n"
9026                "private:\n"
9027                "  void f() {}\n"
9028                "\n"
9029                "private:\n"
9030                "  int i;\n"
9031                "\n"
9032                "protected:\n"
9033                "  int j;\n"
9034                "};\n",
9035                "struct foo {\n"
9036                "private:\n"
9037                "  void f() {}\n"
9038                "private:\n"
9039                "  int i;\n"
9040                "protected:\n"
9041                "  int j;\n"
9042                "};\n",
9043                Style);
9044   verifyFormat("struct foo { /* comment */\n"
9045                "private:\n"
9046                "  int i;\n"
9047                "  // comment\n"
9048                "\n"
9049                "private:\n"
9050                "  int j;\n"
9051                "};\n",
9052                "struct foo { /* comment */\n"
9053                "private:\n"
9054                "  int i;\n"
9055                "  // comment\n"
9056                "\n"
9057                "private:\n"
9058                "  int j;\n"
9059                "};\n",
9060                Style);
9061   verifyFormat("struct foo {\n"
9062                "#ifdef FOO\n"
9063                "#endif\n"
9064                "\n"
9065                "private:\n"
9066                "  int i;\n"
9067                "#ifdef FOO\n"
9068                "\n"
9069                "private:\n"
9070                "#endif\n"
9071                "  int j;\n"
9072                "};\n",
9073                "struct foo {\n"
9074                "#ifdef FOO\n"
9075                "#endif\n"
9076                "private:\n"
9077                "  int i;\n"
9078                "#ifdef FOO\n"
9079                "private:\n"
9080                "#endif\n"
9081                "  int j;\n"
9082                "};\n",
9083                Style);
9084   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9085   EXPECT_EQ("struct foo {\n"
9086             "\n"
9087             "private:\n"
9088             "  void f() {}\n"
9089             "\n"
9090             "private:\n"
9091             "  int i;\n"
9092             "\n"
9093             "protected:\n"
9094             "  int j;\n"
9095             "};\n",
9096             format("struct foo {\n"
9097                    "\n"
9098                    "private:\n"
9099                    "  void f() {}\n"
9100                    "\n"
9101                    "private:\n"
9102                    "  int i;\n"
9103                    "\n"
9104                    "protected:\n"
9105                    "  int j;\n"
9106                    "};\n",
9107                    Style));
9108   verifyFormat("struct foo {\n"
9109                "private:\n"
9110                "  void f() {}\n"
9111                "private:\n"
9112                "  int i;\n"
9113                "protected:\n"
9114                "  int j;\n"
9115                "};\n",
9116                Style);
9117   EXPECT_EQ("struct foo { /* comment */\n"
9118             "\n"
9119             "private:\n"
9120             "  int i;\n"
9121             "  // comment\n"
9122             "\n"
9123             "private:\n"
9124             "  int j;\n"
9125             "};\n",
9126             format("struct foo { /* comment */\n"
9127                    "\n"
9128                    "private:\n"
9129                    "  int i;\n"
9130                    "  // comment\n"
9131                    "\n"
9132                    "private:\n"
9133                    "  int j;\n"
9134                    "};\n",
9135                    Style));
9136   verifyFormat("struct foo { /* comment */\n"
9137                "private:\n"
9138                "  int i;\n"
9139                "  // comment\n"
9140                "private:\n"
9141                "  int j;\n"
9142                "};\n",
9143                Style);
9144   EXPECT_EQ("struct foo {\n"
9145             "#ifdef FOO\n"
9146             "#endif\n"
9147             "\n"
9148             "private:\n"
9149             "  int i;\n"
9150             "#ifdef FOO\n"
9151             "\n"
9152             "private:\n"
9153             "#endif\n"
9154             "  int j;\n"
9155             "};\n",
9156             format("struct foo {\n"
9157                    "#ifdef FOO\n"
9158                    "#endif\n"
9159                    "\n"
9160                    "private:\n"
9161                    "  int i;\n"
9162                    "#ifdef FOO\n"
9163                    "\n"
9164                    "private:\n"
9165                    "#endif\n"
9166                    "  int j;\n"
9167                    "};\n",
9168                    Style));
9169   verifyFormat("struct foo {\n"
9170                "#ifdef FOO\n"
9171                "#endif\n"
9172                "private:\n"
9173                "  int i;\n"
9174                "#ifdef FOO\n"
9175                "private:\n"
9176                "#endif\n"
9177                "  int j;\n"
9178                "};\n",
9179                Style);
9180 }
9181 
9182 TEST_F(FormatTest, FormatsArrays) {
9183   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
9184                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
9185   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
9186                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
9187   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
9188                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
9189   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9190                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
9191   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9192                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
9193   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9194                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
9195                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
9196   verifyFormat(
9197       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
9198       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
9199       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
9200   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
9201                "    .aaaaaaaaaaaaaaaaaaaaaa();");
9202 
9203   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
9204                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
9205   verifyFormat(
9206       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
9207       "                                  .aaaaaaa[0]\n"
9208       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
9209   verifyFormat("a[::b::c];");
9210 
9211   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
9212 
9213   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
9214   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
9215 }
9216 
9217 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
9218   verifyFormat("(a)->b();");
9219   verifyFormat("--a;");
9220 }
9221 
9222 TEST_F(FormatTest, HandlesIncludeDirectives) {
9223   verifyFormat("#include <string>\n"
9224                "#include <a/b/c.h>\n"
9225                "#include \"a/b/string\"\n"
9226                "#include \"string.h\"\n"
9227                "#include \"string.h\"\n"
9228                "#include <a-a>\n"
9229                "#include < path with space >\n"
9230                "#include_next <test.h>"
9231                "#include \"abc.h\" // this is included for ABC\n"
9232                "#include \"some long include\" // with a comment\n"
9233                "#include \"some very long include path\"\n"
9234                "#include <some/very/long/include/path>\n",
9235                getLLVMStyleWithColumns(35));
9236   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
9237   EXPECT_EQ("#include <a>", format("#include<a>"));
9238 
9239   verifyFormat("#import <string>");
9240   verifyFormat("#import <a/b/c.h>");
9241   verifyFormat("#import \"a/b/string\"");
9242   verifyFormat("#import \"string.h\"");
9243   verifyFormat("#import \"string.h\"");
9244   verifyFormat("#if __has_include(<strstream>)\n"
9245                "#include <strstream>\n"
9246                "#endif");
9247 
9248   verifyFormat("#define MY_IMPORT <a/b>");
9249 
9250   verifyFormat("#if __has_include(<a/b>)");
9251   verifyFormat("#if __has_include_next(<a/b>)");
9252   verifyFormat("#define F __has_include(<a/b>)");
9253   verifyFormat("#define F __has_include_next(<a/b>)");
9254 
9255   // Protocol buffer definition or missing "#".
9256   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
9257                getLLVMStyleWithColumns(30));
9258 
9259   FormatStyle Style = getLLVMStyle();
9260   Style.AlwaysBreakBeforeMultilineStrings = true;
9261   Style.ColumnLimit = 0;
9262   verifyFormat("#import \"abc.h\"", Style);
9263 
9264   // But 'import' might also be a regular C++ namespace.
9265   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9266                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9267 }
9268 
9269 //===----------------------------------------------------------------------===//
9270 // Error recovery tests.
9271 //===----------------------------------------------------------------------===//
9272 
9273 TEST_F(FormatTest, IncompleteParameterLists) {
9274   FormatStyle NoBinPacking = getLLVMStyle();
9275   NoBinPacking.BinPackParameters = false;
9276   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
9277                "                        double *min_x,\n"
9278                "                        double *max_x,\n"
9279                "                        double *min_y,\n"
9280                "                        double *max_y,\n"
9281                "                        double *min_z,\n"
9282                "                        double *max_z, ) {}",
9283                NoBinPacking);
9284 }
9285 
9286 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
9287   verifyFormat("void f() { return; }\n42");
9288   verifyFormat("void f() {\n"
9289                "  if (0)\n"
9290                "    return;\n"
9291                "}\n"
9292                "42");
9293   verifyFormat("void f() { return }\n42");
9294   verifyFormat("void f() {\n"
9295                "  if (0)\n"
9296                "    return\n"
9297                "}\n"
9298                "42");
9299 }
9300 
9301 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
9302   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
9303   EXPECT_EQ("void f() {\n"
9304             "  if (a)\n"
9305             "    return\n"
9306             "}",
9307             format("void  f  (  )  {  if  ( a )  return  }"));
9308   EXPECT_EQ("namespace N {\n"
9309             "void f()\n"
9310             "}",
9311             format("namespace  N  {  void f()  }"));
9312   EXPECT_EQ("namespace N {\n"
9313             "void f() {}\n"
9314             "void g()\n"
9315             "} // namespace N",
9316             format("namespace N  { void f( ) { } void g( ) }"));
9317 }
9318 
9319 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
9320   verifyFormat("int aaaaaaaa =\n"
9321                "    // Overlylongcomment\n"
9322                "    b;",
9323                getLLVMStyleWithColumns(20));
9324   verifyFormat("function(\n"
9325                "    ShortArgument,\n"
9326                "    LoooooooooooongArgument);\n",
9327                getLLVMStyleWithColumns(20));
9328 }
9329 
9330 TEST_F(FormatTest, IncorrectAccessSpecifier) {
9331   verifyFormat("public:");
9332   verifyFormat("class A {\n"
9333                "public\n"
9334                "  void f() {}\n"
9335                "};");
9336   verifyFormat("public\n"
9337                "int qwerty;");
9338   verifyFormat("public\n"
9339                "B {}");
9340   verifyFormat("public\n"
9341                "{}");
9342   verifyFormat("public\n"
9343                "B { int x; }");
9344 }
9345 
9346 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
9347   verifyFormat("{");
9348   verifyFormat("#})");
9349   verifyNoCrash("(/**/[:!] ?[).");
9350 }
9351 
9352 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
9353   // Found by oss-fuzz:
9354   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
9355   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9356   Style.ColumnLimit = 60;
9357   verifyNoCrash(
9358       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
9359       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
9360       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
9361       Style);
9362 }
9363 
9364 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
9365   verifyFormat("do {\n}");
9366   verifyFormat("do {\n}\n"
9367                "f();");
9368   verifyFormat("do {\n}\n"
9369                "wheeee(fun);");
9370   verifyFormat("do {\n"
9371                "  f();\n"
9372                "}");
9373 }
9374 
9375 TEST_F(FormatTest, IncorrectCodeMissingParens) {
9376   verifyFormat("if {\n  foo;\n  foo();\n}");
9377   verifyFormat("switch {\n  foo;\n  foo();\n}");
9378   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
9379   verifyFormat("while {\n  foo;\n  foo();\n}");
9380   verifyFormat("do {\n  foo;\n  foo();\n} while;");
9381 }
9382 
9383 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
9384   verifyIncompleteFormat("namespace {\n"
9385                          "class Foo { Foo (\n"
9386                          "};\n"
9387                          "} // namespace");
9388 }
9389 
9390 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
9391   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
9392   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
9393   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
9394   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
9395 
9396   EXPECT_EQ("{\n"
9397             "  {\n"
9398             "    breakme(\n"
9399             "        qwe);\n"
9400             "  }\n",
9401             format("{\n"
9402                    "    {\n"
9403                    " breakme(qwe);\n"
9404                    "}\n",
9405                    getLLVMStyleWithColumns(10)));
9406 }
9407 
9408 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
9409   verifyFormat("int x = {\n"
9410                "    avariable,\n"
9411                "    b(alongervariable)};",
9412                getLLVMStyleWithColumns(25));
9413 }
9414 
9415 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
9416   verifyFormat("return (a)(b){1, 2, 3};");
9417 }
9418 
9419 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
9420   verifyFormat("vector<int> x{1, 2, 3, 4};");
9421   verifyFormat("vector<int> x{\n"
9422                "    1,\n"
9423                "    2,\n"
9424                "    3,\n"
9425                "    4,\n"
9426                "};");
9427   verifyFormat("vector<T> x{{}, {}, {}, {}};");
9428   verifyFormat("f({1, 2});");
9429   verifyFormat("auto v = Foo{-1};");
9430   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
9431   verifyFormat("Class::Class : member{1, 2, 3} {}");
9432   verifyFormat("new vector<int>{1, 2, 3};");
9433   verifyFormat("new int[3]{1, 2, 3};");
9434   verifyFormat("new int{1};");
9435   verifyFormat("return {arg1, arg2};");
9436   verifyFormat("return {arg1, SomeType{parameter}};");
9437   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
9438   verifyFormat("new T{arg1, arg2};");
9439   verifyFormat("f(MyMap[{composite, key}]);");
9440   verifyFormat("class Class {\n"
9441                "  T member = {arg1, arg2};\n"
9442                "};");
9443   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
9444   verifyFormat("const struct A a = {.a = 1, .b = 2};");
9445   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
9446   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
9447   verifyFormat("int a = std::is_integral<int>{} + 0;");
9448 
9449   verifyFormat("int foo(int i) { return fo1{}(i); }");
9450   verifyFormat("int foo(int i) { return fo1{}(i); }");
9451   verifyFormat("auto i = decltype(x){};");
9452   verifyFormat("auto i = typeof(x){};");
9453   verifyFormat("auto i = _Atomic(x){};");
9454   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
9455   verifyFormat("Node n{1, Node{1000}, //\n"
9456                "       2};");
9457   verifyFormat("Aaaa aaaaaaa{\n"
9458                "    {\n"
9459                "        aaaa,\n"
9460                "    },\n"
9461                "};");
9462   verifyFormat("class C : public D {\n"
9463                "  SomeClass SC{2};\n"
9464                "};");
9465   verifyFormat("class C : public A {\n"
9466                "  class D : public B {\n"
9467                "    void f() { int i{2}; }\n"
9468                "  };\n"
9469                "};");
9470   verifyFormat("#define A {a, a},");
9471 
9472   // Avoid breaking between equal sign and opening brace
9473   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
9474   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
9475   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
9476                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
9477                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
9478                "     {\"ccccccccccccccccccccc\", 2}};",
9479                AvoidBreakingFirstArgument);
9480 
9481   // Binpacking only if there is no trailing comma
9482   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
9483                "                      cccccccccc, dddddddddd};",
9484                getLLVMStyleWithColumns(50));
9485   verifyFormat("const Aaaaaa aaaaa = {\n"
9486                "    aaaaaaaaaaa,\n"
9487                "    bbbbbbbbbbb,\n"
9488                "    ccccccccccc,\n"
9489                "    ddddddddddd,\n"
9490                "};",
9491                getLLVMStyleWithColumns(50));
9492 
9493   // Cases where distinguising braced lists and blocks is hard.
9494   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
9495   verifyFormat("void f() {\n"
9496                "  return; // comment\n"
9497                "}\n"
9498                "SomeType t;");
9499   verifyFormat("void f() {\n"
9500                "  if (a) {\n"
9501                "    f();\n"
9502                "  }\n"
9503                "}\n"
9504                "SomeType t;");
9505 
9506   // In combination with BinPackArguments = false.
9507   FormatStyle NoBinPacking = getLLVMStyle();
9508   NoBinPacking.BinPackArguments = false;
9509   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
9510                "                      bbbbb,\n"
9511                "                      ccccc,\n"
9512                "                      ddddd,\n"
9513                "                      eeeee,\n"
9514                "                      ffffff,\n"
9515                "                      ggggg,\n"
9516                "                      hhhhhh,\n"
9517                "                      iiiiii,\n"
9518                "                      jjjjjj,\n"
9519                "                      kkkkkk};",
9520                NoBinPacking);
9521   verifyFormat("const Aaaaaa aaaaa = {\n"
9522                "    aaaaa,\n"
9523                "    bbbbb,\n"
9524                "    ccccc,\n"
9525                "    ddddd,\n"
9526                "    eeeee,\n"
9527                "    ffffff,\n"
9528                "    ggggg,\n"
9529                "    hhhhhh,\n"
9530                "    iiiiii,\n"
9531                "    jjjjjj,\n"
9532                "    kkkkkk,\n"
9533                "};",
9534                NoBinPacking);
9535   verifyFormat(
9536       "const Aaaaaa aaaaa = {\n"
9537       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
9538       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
9539       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
9540       "};",
9541       NoBinPacking);
9542 
9543   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9544   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
9545             "    CDDDP83848_BMCR_REGISTER,\n"
9546             "    CDDDP83848_BMSR_REGISTER,\n"
9547             "    CDDDP83848_RBR_REGISTER};",
9548             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
9549                    "                                CDDDP83848_BMSR_REGISTER,\n"
9550                    "                                CDDDP83848_RBR_REGISTER};",
9551                    NoBinPacking));
9552 
9553   // FIXME: The alignment of these trailing comments might be bad. Then again,
9554   // this might be utterly useless in real code.
9555   verifyFormat("Constructor::Constructor()\n"
9556                "    : some_value{         //\n"
9557                "                 aaaaaaa, //\n"
9558                "                 bbbbbbb} {}");
9559 
9560   // In braced lists, the first comment is always assumed to belong to the
9561   // first element. Thus, it can be moved to the next or previous line as
9562   // appropriate.
9563   EXPECT_EQ("function({// First element:\n"
9564             "          1,\n"
9565             "          // Second element:\n"
9566             "          2});",
9567             format("function({\n"
9568                    "    // First element:\n"
9569                    "    1,\n"
9570                    "    // Second element:\n"
9571                    "    2});"));
9572   EXPECT_EQ("std::vector<int> MyNumbers{\n"
9573             "    // First element:\n"
9574             "    1,\n"
9575             "    // Second element:\n"
9576             "    2};",
9577             format("std::vector<int> MyNumbers{// First element:\n"
9578                    "                           1,\n"
9579                    "                           // Second element:\n"
9580                    "                           2};",
9581                    getLLVMStyleWithColumns(30)));
9582   // A trailing comma should still lead to an enforced line break and no
9583   // binpacking.
9584   EXPECT_EQ("vector<int> SomeVector = {\n"
9585             "    // aaa\n"
9586             "    1,\n"
9587             "    2,\n"
9588             "};",
9589             format("vector<int> SomeVector = { // aaa\n"
9590                    "    1, 2, };"));
9591 
9592   // C++11 brace initializer list l-braces should not be treated any differently
9593   // when breaking before lambda bodies is enabled
9594   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
9595   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
9596   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
9597   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
9598   verifyFormat(
9599       "std::runtime_error{\n"
9600       "    \"Long string which will force a break onto the next line...\"};",
9601       BreakBeforeLambdaBody);
9602 
9603   FormatStyle ExtraSpaces = getLLVMStyle();
9604   ExtraSpaces.Cpp11BracedListStyle = false;
9605   ExtraSpaces.ColumnLimit = 75;
9606   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
9607   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
9608   verifyFormat("f({ 1, 2 });", ExtraSpaces);
9609   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
9610   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
9611   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
9612   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
9613   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
9614   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
9615   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
9616   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
9617   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
9618   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
9619   verifyFormat("class Class {\n"
9620                "  T member = { arg1, arg2 };\n"
9621                "};",
9622                ExtraSpaces);
9623   verifyFormat(
9624       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9625       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
9626       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
9627       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
9628       ExtraSpaces);
9629   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
9630   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
9631                ExtraSpaces);
9632   verifyFormat(
9633       "someFunction(OtherParam,\n"
9634       "             BracedList{ // comment 1 (Forcing interesting break)\n"
9635       "                         param1, param2,\n"
9636       "                         // comment 2\n"
9637       "                         param3, param4 });",
9638       ExtraSpaces);
9639   verifyFormat(
9640       "std::this_thread::sleep_for(\n"
9641       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
9642       ExtraSpaces);
9643   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
9644                "    aaaaaaa,\n"
9645                "    aaaaaaaaaa,\n"
9646                "    aaaaa,\n"
9647                "    aaaaaaaaaaaaaaa,\n"
9648                "    aaa,\n"
9649                "    aaaaaaaaaa,\n"
9650                "    a,\n"
9651                "    aaaaaaaaaaaaaaaaaaaaa,\n"
9652                "    aaaaaaaaaaaa,\n"
9653                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
9654                "    aaaaaaa,\n"
9655                "    a};");
9656   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
9657   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
9658   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
9659 
9660   // Avoid breaking between initializer/equal sign and opening brace
9661   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
9662   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
9663                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
9664                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
9665                "  { \"ccccccccccccccccccccc\", 2 }\n"
9666                "};",
9667                ExtraSpaces);
9668   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
9669                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
9670                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
9671                "  { \"ccccccccccccccccccccc\", 2 }\n"
9672                "};",
9673                ExtraSpaces);
9674 
9675   FormatStyle SpaceBeforeBrace = getLLVMStyle();
9676   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
9677   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
9678   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
9679 
9680   FormatStyle SpaceBetweenBraces = getLLVMStyle();
9681   SpaceBetweenBraces.SpacesInAngles = true;
9682   SpaceBetweenBraces.SpacesInParentheses = true;
9683   SpaceBetweenBraces.SpacesInSquareBrackets = true;
9684   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
9685   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
9686   verifyFormat("vector< int > x{ // comment 1\n"
9687                "                 1, 2, 3, 4 };",
9688                SpaceBetweenBraces);
9689   SpaceBetweenBraces.ColumnLimit = 20;
9690   EXPECT_EQ("vector< int > x{\n"
9691             "    1, 2, 3, 4 };",
9692             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
9693   SpaceBetweenBraces.ColumnLimit = 24;
9694   EXPECT_EQ("vector< int > x{ 1, 2,\n"
9695             "                 3, 4 };",
9696             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
9697   EXPECT_EQ("vector< int > x{\n"
9698             "    1,\n"
9699             "    2,\n"
9700             "    3,\n"
9701             "    4,\n"
9702             "};",
9703             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
9704   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
9705   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
9706   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
9707 }
9708 
9709 TEST_F(FormatTest, FormatSpacesInAngles) {
9710   FormatStyle SpaceInAngles = getLLVMStyle();
9711   SpaceInAngles.SpacesInAngles = true;
9712   verifyFormat("vector< ::std::string > x1;", SpaceInAngles);
9713   verifyFormat("Foo< int, Bar > x2;", SpaceInAngles);
9714   verifyFormat("Foo< ::int, ::Bar > x3;", SpaceInAngles);
9715 
9716   SpaceInAngles.SpacesInAngles = false;
9717   verifyFormat("vector<::std::string> x4;", SpaceInAngles);
9718   verifyFormat("vector<int> x5;", SpaceInAngles);
9719   verifyFormat("Foo<int, Bar> x6;", SpaceInAngles);
9720   verifyFormat("Foo<::int, ::Bar> x7;", SpaceInAngles);
9721 }
9722 
9723 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
9724   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9725                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9726                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9727                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9728                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9729                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
9730   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
9731                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9732                "                 1, 22, 333, 4444, 55555, //\n"
9733                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9734                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
9735   verifyFormat(
9736       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
9737       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
9738       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
9739       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
9740       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
9741       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
9742       "                 7777777};");
9743   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
9744                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
9745                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
9746   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
9747                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
9748                "    // Separating comment.\n"
9749                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
9750   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
9751                "    // Leading comment\n"
9752                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
9753                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
9754   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
9755                "                 1, 1, 1, 1};",
9756                getLLVMStyleWithColumns(39));
9757   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
9758                "                 1, 1, 1, 1};",
9759                getLLVMStyleWithColumns(38));
9760   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
9761                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
9762                getLLVMStyleWithColumns(43));
9763   verifyFormat(
9764       "static unsigned SomeValues[10][3] = {\n"
9765       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
9766       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
9767   verifyFormat("static auto fields = new vector<string>{\n"
9768                "    \"aaaaaaaaaaaaa\",\n"
9769                "    \"aaaaaaaaaaaaa\",\n"
9770                "    \"aaaaaaaaaaaa\",\n"
9771                "    \"aaaaaaaaaaaaaa\",\n"
9772                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
9773                "    \"aaaaaaaaaaaa\",\n"
9774                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
9775                "};");
9776   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
9777   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
9778                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
9779                "                 3, cccccccccccccccccccccc};",
9780                getLLVMStyleWithColumns(60));
9781 
9782   // Trailing commas.
9783   verifyFormat("vector<int> x = {\n"
9784                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
9785                "};",
9786                getLLVMStyleWithColumns(39));
9787   verifyFormat("vector<int> x = {\n"
9788                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
9789                "};",
9790                getLLVMStyleWithColumns(39));
9791   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
9792                "                 1, 1, 1, 1,\n"
9793                "                 /**/ /**/};",
9794                getLLVMStyleWithColumns(39));
9795 
9796   // Trailing comment in the first line.
9797   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
9798                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
9799                "    111111111,  222222222,  3333333333,  444444444,  //\n"
9800                "    11111111,   22222222,   333333333,   44444444};");
9801   // Trailing comment in the last line.
9802   verifyFormat("int aaaaa[] = {\n"
9803                "    1, 2, 3, // comment\n"
9804                "    4, 5, 6  // comment\n"
9805                "};");
9806 
9807   // With nested lists, we should either format one item per line or all nested
9808   // lists one on line.
9809   // FIXME: For some nested lists, we can do better.
9810   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
9811                "        {aaaaaaaaaaaaaaaaaaa},\n"
9812                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
9813                "        {aaaaaaaaaaaaaaaaa}};",
9814                getLLVMStyleWithColumns(60));
9815   verifyFormat(
9816       "SomeStruct my_struct_array = {\n"
9817       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
9818       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
9819       "    {aaa, aaa},\n"
9820       "    {aaa, aaa},\n"
9821       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
9822       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
9823       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
9824 
9825   // No column layout should be used here.
9826   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
9827                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
9828 
9829   verifyNoCrash("a<,");
9830 
9831   // No braced initializer here.
9832   verifyFormat("void f() {\n"
9833                "  struct Dummy {};\n"
9834                "  f(v);\n"
9835                "}");
9836 
9837   // Long lists should be formatted in columns even if they are nested.
9838   verifyFormat(
9839       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9840       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9841       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9842       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9843       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
9844       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
9845 
9846   // Allow "single-column" layout even if that violates the column limit. There
9847   // isn't going to be a better way.
9848   verifyFormat("std::vector<int> a = {\n"
9849                "    aaaaaaaa,\n"
9850                "    aaaaaaaa,\n"
9851                "    aaaaaaaa,\n"
9852                "    aaaaaaaa,\n"
9853                "    aaaaaaaaaa,\n"
9854                "    aaaaaaaa,\n"
9855                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
9856                getLLVMStyleWithColumns(30));
9857   verifyFormat("vector<int> aaaa = {\n"
9858                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9859                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9860                "    aaaaaa.aaaaaaa,\n"
9861                "    aaaaaa.aaaaaaa,\n"
9862                "    aaaaaa.aaaaaaa,\n"
9863                "    aaaaaa.aaaaaaa,\n"
9864                "};");
9865 
9866   // Don't create hanging lists.
9867   verifyFormat("someFunction(Param, {List1, List2,\n"
9868                "                     List3});",
9869                getLLVMStyleWithColumns(35));
9870   verifyFormat("someFunction(Param, Param,\n"
9871                "             {List1, List2,\n"
9872                "              List3});",
9873                getLLVMStyleWithColumns(35));
9874   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
9875                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
9876 }
9877 
9878 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
9879   FormatStyle DoNotMerge = getLLVMStyle();
9880   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
9881 
9882   verifyFormat("void f() { return 42; }");
9883   verifyFormat("void f() {\n"
9884                "  return 42;\n"
9885                "}",
9886                DoNotMerge);
9887   verifyFormat("void f() {\n"
9888                "  // Comment\n"
9889                "}");
9890   verifyFormat("{\n"
9891                "#error {\n"
9892                "  int a;\n"
9893                "}");
9894   verifyFormat("{\n"
9895                "  int a;\n"
9896                "#error {\n"
9897                "}");
9898   verifyFormat("void f() {} // comment");
9899   verifyFormat("void f() { int a; } // comment");
9900   verifyFormat("void f() {\n"
9901                "} // comment",
9902                DoNotMerge);
9903   verifyFormat("void f() {\n"
9904                "  int a;\n"
9905                "} // comment",
9906                DoNotMerge);
9907   verifyFormat("void f() {\n"
9908                "} // comment",
9909                getLLVMStyleWithColumns(15));
9910 
9911   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
9912   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
9913 
9914   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
9915   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
9916   verifyFormat("class C {\n"
9917                "  C()\n"
9918                "      : iiiiiiii(nullptr),\n"
9919                "        kkkkkkk(nullptr),\n"
9920                "        mmmmmmm(nullptr),\n"
9921                "        nnnnnnn(nullptr) {}\n"
9922                "};",
9923                getGoogleStyle());
9924 
9925   FormatStyle NoColumnLimit = getLLVMStyle();
9926   NoColumnLimit.ColumnLimit = 0;
9927   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
9928   EXPECT_EQ("class C {\n"
9929             "  A() : b(0) {}\n"
9930             "};",
9931             format("class C{A():b(0){}};", NoColumnLimit));
9932   EXPECT_EQ("A()\n"
9933             "    : b(0) {\n"
9934             "}",
9935             format("A()\n:b(0)\n{\n}", NoColumnLimit));
9936 
9937   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
9938   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
9939       FormatStyle::SFS_None;
9940   EXPECT_EQ("A()\n"
9941             "    : b(0) {\n"
9942             "}",
9943             format("A():b(0){}", DoNotMergeNoColumnLimit));
9944   EXPECT_EQ("A()\n"
9945             "    : b(0) {\n"
9946             "}",
9947             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
9948 
9949   verifyFormat("#define A          \\\n"
9950                "  void f() {       \\\n"
9951                "    int i;         \\\n"
9952                "  }",
9953                getLLVMStyleWithColumns(20));
9954   verifyFormat("#define A           \\\n"
9955                "  void f() { int i; }",
9956                getLLVMStyleWithColumns(21));
9957   verifyFormat("#define A            \\\n"
9958                "  void f() {         \\\n"
9959                "    int i;           \\\n"
9960                "  }                  \\\n"
9961                "  int j;",
9962                getLLVMStyleWithColumns(22));
9963   verifyFormat("#define A             \\\n"
9964                "  void f() { int i; } \\\n"
9965                "  int j;",
9966                getLLVMStyleWithColumns(23));
9967 }
9968 
9969 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
9970   FormatStyle MergeEmptyOnly = getLLVMStyle();
9971   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
9972   verifyFormat("class C {\n"
9973                "  int f() {}\n"
9974                "};",
9975                MergeEmptyOnly);
9976   verifyFormat("class C {\n"
9977                "  int f() {\n"
9978                "    return 42;\n"
9979                "  }\n"
9980                "};",
9981                MergeEmptyOnly);
9982   verifyFormat("int f() {}", MergeEmptyOnly);
9983   verifyFormat("int f() {\n"
9984                "  return 42;\n"
9985                "}",
9986                MergeEmptyOnly);
9987 
9988   // Also verify behavior when BraceWrapping.AfterFunction = true
9989   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
9990   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
9991   verifyFormat("int f() {}", MergeEmptyOnly);
9992   verifyFormat("class C {\n"
9993                "  int f() {}\n"
9994                "};",
9995                MergeEmptyOnly);
9996 }
9997 
9998 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
9999   FormatStyle MergeInlineOnly = getLLVMStyle();
10000   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
10001   verifyFormat("class C {\n"
10002                "  int f() { return 42; }\n"
10003                "};",
10004                MergeInlineOnly);
10005   verifyFormat("int f() {\n"
10006                "  return 42;\n"
10007                "}",
10008                MergeInlineOnly);
10009 
10010   // SFS_Inline implies SFS_Empty
10011   verifyFormat("class C {\n"
10012                "  int f() {}\n"
10013                "};",
10014                MergeInlineOnly);
10015   verifyFormat("int f() {}", MergeInlineOnly);
10016 
10017   // Also verify behavior when BraceWrapping.AfterFunction = true
10018   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
10019   MergeInlineOnly.BraceWrapping.AfterFunction = true;
10020   verifyFormat("class C {\n"
10021                "  int f() { return 42; }\n"
10022                "};",
10023                MergeInlineOnly);
10024   verifyFormat("int f()\n"
10025                "{\n"
10026                "  return 42;\n"
10027                "}",
10028                MergeInlineOnly);
10029 
10030   // SFS_Inline implies SFS_Empty
10031   verifyFormat("int f() {}", MergeInlineOnly);
10032   verifyFormat("class C {\n"
10033                "  int f() {}\n"
10034                "};",
10035                MergeInlineOnly);
10036 }
10037 
10038 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
10039   FormatStyle MergeInlineOnly = getLLVMStyle();
10040   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
10041       FormatStyle::SFS_InlineOnly;
10042   verifyFormat("class C {\n"
10043                "  int f() { return 42; }\n"
10044                "};",
10045                MergeInlineOnly);
10046   verifyFormat("int f() {\n"
10047                "  return 42;\n"
10048                "}",
10049                MergeInlineOnly);
10050 
10051   // SFS_InlineOnly does not imply SFS_Empty
10052   verifyFormat("class C {\n"
10053                "  int f() {}\n"
10054                "};",
10055                MergeInlineOnly);
10056   verifyFormat("int f() {\n"
10057                "}",
10058                MergeInlineOnly);
10059 
10060   // Also verify behavior when BraceWrapping.AfterFunction = true
10061   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
10062   MergeInlineOnly.BraceWrapping.AfterFunction = true;
10063   verifyFormat("class C {\n"
10064                "  int f() { return 42; }\n"
10065                "};",
10066                MergeInlineOnly);
10067   verifyFormat("int f()\n"
10068                "{\n"
10069                "  return 42;\n"
10070                "}",
10071                MergeInlineOnly);
10072 
10073   // SFS_InlineOnly does not imply SFS_Empty
10074   verifyFormat("int f()\n"
10075                "{\n"
10076                "}",
10077                MergeInlineOnly);
10078   verifyFormat("class C {\n"
10079                "  int f() {}\n"
10080                "};",
10081                MergeInlineOnly);
10082 }
10083 
10084 TEST_F(FormatTest, SplitEmptyFunction) {
10085   FormatStyle Style = getLLVMStyle();
10086   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10087   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10088   Style.BraceWrapping.AfterFunction = true;
10089   Style.BraceWrapping.SplitEmptyFunction = false;
10090   Style.ColumnLimit = 40;
10091 
10092   verifyFormat("int f()\n"
10093                "{}",
10094                Style);
10095   verifyFormat("int f()\n"
10096                "{\n"
10097                "  return 42;\n"
10098                "}",
10099                Style);
10100   verifyFormat("int f()\n"
10101                "{\n"
10102                "  // some comment\n"
10103                "}",
10104                Style);
10105 
10106   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
10107   verifyFormat("int f() {}", Style);
10108   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10109                "{}",
10110                Style);
10111   verifyFormat("int f()\n"
10112                "{\n"
10113                "  return 0;\n"
10114                "}",
10115                Style);
10116 
10117   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
10118   verifyFormat("class Foo {\n"
10119                "  int f() {}\n"
10120                "};\n",
10121                Style);
10122   verifyFormat("class Foo {\n"
10123                "  int f() { return 0; }\n"
10124                "};\n",
10125                Style);
10126   verifyFormat("class Foo {\n"
10127                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10128                "  {}\n"
10129                "};\n",
10130                Style);
10131   verifyFormat("class Foo {\n"
10132                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10133                "  {\n"
10134                "    return 0;\n"
10135                "  }\n"
10136                "};\n",
10137                Style);
10138 
10139   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
10140   verifyFormat("int f() {}", Style);
10141   verifyFormat("int f() { return 0; }", Style);
10142   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10143                "{}",
10144                Style);
10145   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10146                "{\n"
10147                "  return 0;\n"
10148                "}",
10149                Style);
10150 }
10151 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
10152   FormatStyle Style = getLLVMStyle();
10153   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
10154   verifyFormat("#ifdef A\n"
10155                "int f() {}\n"
10156                "#else\n"
10157                "int g() {}\n"
10158                "#endif",
10159                Style);
10160 }
10161 
10162 TEST_F(FormatTest, SplitEmptyClass) {
10163   FormatStyle Style = getLLVMStyle();
10164   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10165   Style.BraceWrapping.AfterClass = true;
10166   Style.BraceWrapping.SplitEmptyRecord = false;
10167 
10168   verifyFormat("class Foo\n"
10169                "{};",
10170                Style);
10171   verifyFormat("/* something */ class Foo\n"
10172                "{};",
10173                Style);
10174   verifyFormat("template <typename X> class Foo\n"
10175                "{};",
10176                Style);
10177   verifyFormat("class Foo\n"
10178                "{\n"
10179                "  Foo();\n"
10180                "};",
10181                Style);
10182   verifyFormat("typedef class Foo\n"
10183                "{\n"
10184                "} Foo_t;",
10185                Style);
10186 
10187   Style.BraceWrapping.SplitEmptyRecord = true;
10188   Style.BraceWrapping.AfterStruct = true;
10189   verifyFormat("class rep\n"
10190                "{\n"
10191                "};",
10192                Style);
10193   verifyFormat("struct rep\n"
10194                "{\n"
10195                "};",
10196                Style);
10197   verifyFormat("template <typename T> class rep\n"
10198                "{\n"
10199                "};",
10200                Style);
10201   verifyFormat("template <typename T> struct rep\n"
10202                "{\n"
10203                "};",
10204                Style);
10205   verifyFormat("class rep\n"
10206                "{\n"
10207                "  int x;\n"
10208                "};",
10209                Style);
10210   verifyFormat("struct rep\n"
10211                "{\n"
10212                "  int x;\n"
10213                "};",
10214                Style);
10215   verifyFormat("template <typename T> class rep\n"
10216                "{\n"
10217                "  int x;\n"
10218                "};",
10219                Style);
10220   verifyFormat("template <typename T> struct rep\n"
10221                "{\n"
10222                "  int x;\n"
10223                "};",
10224                Style);
10225   verifyFormat("template <typename T> class rep // Foo\n"
10226                "{\n"
10227                "  int x;\n"
10228                "};",
10229                Style);
10230   verifyFormat("template <typename T> struct rep // Bar\n"
10231                "{\n"
10232                "  int x;\n"
10233                "};",
10234                Style);
10235 
10236   verifyFormat("template <typename T> class rep<T>\n"
10237                "{\n"
10238                "  int x;\n"
10239                "};",
10240                Style);
10241 
10242   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
10243                "{\n"
10244                "  int x;\n"
10245                "};",
10246                Style);
10247   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
10248                "{\n"
10249                "};",
10250                Style);
10251 }
10252 
10253 TEST_F(FormatTest, SplitEmptyStruct) {
10254   FormatStyle Style = getLLVMStyle();
10255   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10256   Style.BraceWrapping.AfterStruct = true;
10257   Style.BraceWrapping.SplitEmptyRecord = false;
10258 
10259   verifyFormat("struct Foo\n"
10260                "{};",
10261                Style);
10262   verifyFormat("/* something */ struct Foo\n"
10263                "{};",
10264                Style);
10265   verifyFormat("template <typename X> struct Foo\n"
10266                "{};",
10267                Style);
10268   verifyFormat("struct Foo\n"
10269                "{\n"
10270                "  Foo();\n"
10271                "};",
10272                Style);
10273   verifyFormat("typedef struct Foo\n"
10274                "{\n"
10275                "} Foo_t;",
10276                Style);
10277   // typedef struct Bar {} Bar_t;
10278 }
10279 
10280 TEST_F(FormatTest, SplitEmptyUnion) {
10281   FormatStyle Style = getLLVMStyle();
10282   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10283   Style.BraceWrapping.AfterUnion = true;
10284   Style.BraceWrapping.SplitEmptyRecord = false;
10285 
10286   verifyFormat("union Foo\n"
10287                "{};",
10288                Style);
10289   verifyFormat("/* something */ union Foo\n"
10290                "{};",
10291                Style);
10292   verifyFormat("union Foo\n"
10293                "{\n"
10294                "  A,\n"
10295                "};",
10296                Style);
10297   verifyFormat("typedef union Foo\n"
10298                "{\n"
10299                "} Foo_t;",
10300                Style);
10301 }
10302 
10303 TEST_F(FormatTest, SplitEmptyNamespace) {
10304   FormatStyle Style = getLLVMStyle();
10305   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10306   Style.BraceWrapping.AfterNamespace = true;
10307   Style.BraceWrapping.SplitEmptyNamespace = false;
10308 
10309   verifyFormat("namespace Foo\n"
10310                "{};",
10311                Style);
10312   verifyFormat("/* something */ namespace Foo\n"
10313                "{};",
10314                Style);
10315   verifyFormat("inline namespace Foo\n"
10316                "{};",
10317                Style);
10318   verifyFormat("/* something */ inline namespace Foo\n"
10319                "{};",
10320                Style);
10321   verifyFormat("export namespace Foo\n"
10322                "{};",
10323                Style);
10324   verifyFormat("namespace Foo\n"
10325                "{\n"
10326                "void Bar();\n"
10327                "};",
10328                Style);
10329 }
10330 
10331 TEST_F(FormatTest, NeverMergeShortRecords) {
10332   FormatStyle Style = getLLVMStyle();
10333 
10334   verifyFormat("class Foo {\n"
10335                "  Foo();\n"
10336                "};",
10337                Style);
10338   verifyFormat("typedef class Foo {\n"
10339                "  Foo();\n"
10340                "} Foo_t;",
10341                Style);
10342   verifyFormat("struct Foo {\n"
10343                "  Foo();\n"
10344                "};",
10345                Style);
10346   verifyFormat("typedef struct Foo {\n"
10347                "  Foo();\n"
10348                "} Foo_t;",
10349                Style);
10350   verifyFormat("union Foo {\n"
10351                "  A,\n"
10352                "};",
10353                Style);
10354   verifyFormat("typedef union Foo {\n"
10355                "  A,\n"
10356                "} Foo_t;",
10357                Style);
10358   verifyFormat("namespace Foo {\n"
10359                "void Bar();\n"
10360                "};",
10361                Style);
10362 
10363   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10364   Style.BraceWrapping.AfterClass = true;
10365   Style.BraceWrapping.AfterStruct = true;
10366   Style.BraceWrapping.AfterUnion = true;
10367   Style.BraceWrapping.AfterNamespace = true;
10368   verifyFormat("class Foo\n"
10369                "{\n"
10370                "  Foo();\n"
10371                "};",
10372                Style);
10373   verifyFormat("typedef class Foo\n"
10374                "{\n"
10375                "  Foo();\n"
10376                "} Foo_t;",
10377                Style);
10378   verifyFormat("struct Foo\n"
10379                "{\n"
10380                "  Foo();\n"
10381                "};",
10382                Style);
10383   verifyFormat("typedef struct Foo\n"
10384                "{\n"
10385                "  Foo();\n"
10386                "} Foo_t;",
10387                Style);
10388   verifyFormat("union Foo\n"
10389                "{\n"
10390                "  A,\n"
10391                "};",
10392                Style);
10393   verifyFormat("typedef union Foo\n"
10394                "{\n"
10395                "  A,\n"
10396                "} Foo_t;",
10397                Style);
10398   verifyFormat("namespace Foo\n"
10399                "{\n"
10400                "void Bar();\n"
10401                "};",
10402                Style);
10403 }
10404 
10405 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
10406   // Elaborate type variable declarations.
10407   verifyFormat("struct foo a = {bar};\nint n;");
10408   verifyFormat("class foo a = {bar};\nint n;");
10409   verifyFormat("union foo a = {bar};\nint n;");
10410 
10411   // Elaborate types inside function definitions.
10412   verifyFormat("struct foo f() {}\nint n;");
10413   verifyFormat("class foo f() {}\nint n;");
10414   verifyFormat("union foo f() {}\nint n;");
10415 
10416   // Templates.
10417   verifyFormat("template <class X> void f() {}\nint n;");
10418   verifyFormat("template <struct X> void f() {}\nint n;");
10419   verifyFormat("template <union X> void f() {}\nint n;");
10420 
10421   // Actual definitions...
10422   verifyFormat("struct {\n} n;");
10423   verifyFormat(
10424       "template <template <class T, class Y>, class Z> class X {\n} n;");
10425   verifyFormat("union Z {\n  int n;\n} x;");
10426   verifyFormat("class MACRO Z {\n} n;");
10427   verifyFormat("class MACRO(X) Z {\n} n;");
10428   verifyFormat("class __attribute__(X) Z {\n} n;");
10429   verifyFormat("class __declspec(X) Z {\n} n;");
10430   verifyFormat("class A##B##C {\n} n;");
10431   verifyFormat("class alignas(16) Z {\n} n;");
10432   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
10433   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
10434 
10435   // Redefinition from nested context:
10436   verifyFormat("class A::B::C {\n} n;");
10437 
10438   // Template definitions.
10439   verifyFormat(
10440       "template <typename F>\n"
10441       "Matcher(const Matcher<F> &Other,\n"
10442       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
10443       "                             !is_same<F, T>::value>::type * = 0)\n"
10444       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
10445 
10446   // FIXME: This is still incorrectly handled at the formatter side.
10447   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
10448   verifyFormat("int i = SomeFunction(a<b, a> b);");
10449 
10450   // FIXME:
10451   // This now gets parsed incorrectly as class definition.
10452   // verifyFormat("class A<int> f() {\n}\nint n;");
10453 
10454   // Elaborate types where incorrectly parsing the structural element would
10455   // break the indent.
10456   verifyFormat("if (true)\n"
10457                "  class X x;\n"
10458                "else\n"
10459                "  f();\n");
10460 
10461   // This is simply incomplete. Formatting is not important, but must not crash.
10462   verifyFormat("class A:");
10463 }
10464 
10465 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
10466   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
10467             format("#error Leave     all         white!!!!! space* alone!\n"));
10468   EXPECT_EQ(
10469       "#warning Leave     all         white!!!!! space* alone!\n",
10470       format("#warning Leave     all         white!!!!! space* alone!\n"));
10471   EXPECT_EQ("#error 1", format("  #  error   1"));
10472   EXPECT_EQ("#warning 1", format("  #  warning 1"));
10473 }
10474 
10475 TEST_F(FormatTest, FormatHashIfExpressions) {
10476   verifyFormat("#if AAAA && BBBB");
10477   verifyFormat("#if (AAAA && BBBB)");
10478   verifyFormat("#elif (AAAA && BBBB)");
10479   // FIXME: Come up with a better indentation for #elif.
10480   verifyFormat(
10481       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
10482       "    defined(BBBBBBBB)\n"
10483       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
10484       "    defined(BBBBBBBB)\n"
10485       "#endif",
10486       getLLVMStyleWithColumns(65));
10487 }
10488 
10489 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
10490   FormatStyle AllowsMergedIf = getGoogleStyle();
10491   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
10492       FormatStyle::SIS_WithoutElse;
10493   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
10494   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
10495   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
10496   EXPECT_EQ("if (true) return 42;",
10497             format("if (true)\nreturn 42;", AllowsMergedIf));
10498   FormatStyle ShortMergedIf = AllowsMergedIf;
10499   ShortMergedIf.ColumnLimit = 25;
10500   verifyFormat("#define A \\\n"
10501                "  if (true) return 42;",
10502                ShortMergedIf);
10503   verifyFormat("#define A \\\n"
10504                "  f();    \\\n"
10505                "  if (true)\n"
10506                "#define B",
10507                ShortMergedIf);
10508   verifyFormat("#define A \\\n"
10509                "  f();    \\\n"
10510                "  if (true)\n"
10511                "g();",
10512                ShortMergedIf);
10513   verifyFormat("{\n"
10514                "#ifdef A\n"
10515                "  // Comment\n"
10516                "  if (true) continue;\n"
10517                "#endif\n"
10518                "  // Comment\n"
10519                "  if (true) continue;\n"
10520                "}",
10521                ShortMergedIf);
10522   ShortMergedIf.ColumnLimit = 33;
10523   verifyFormat("#define A \\\n"
10524                "  if constexpr (true) return 42;",
10525                ShortMergedIf);
10526   verifyFormat("#define A \\\n"
10527                "  if CONSTEXPR (true) return 42;",
10528                ShortMergedIf);
10529   ShortMergedIf.ColumnLimit = 29;
10530   verifyFormat("#define A                   \\\n"
10531                "  if (aaaaaaaaaa) return 1; \\\n"
10532                "  return 2;",
10533                ShortMergedIf);
10534   ShortMergedIf.ColumnLimit = 28;
10535   verifyFormat("#define A         \\\n"
10536                "  if (aaaaaaaaaa) \\\n"
10537                "    return 1;     \\\n"
10538                "  return 2;",
10539                ShortMergedIf);
10540   verifyFormat("#define A                \\\n"
10541                "  if constexpr (aaaaaaa) \\\n"
10542                "    return 1;            \\\n"
10543                "  return 2;",
10544                ShortMergedIf);
10545   verifyFormat("#define A                \\\n"
10546                "  if CONSTEXPR (aaaaaaa) \\\n"
10547                "    return 1;            \\\n"
10548                "  return 2;",
10549                ShortMergedIf);
10550 }
10551 
10552 TEST_F(FormatTest, FormatStarDependingOnContext) {
10553   verifyFormat("void f(int *a);");
10554   verifyFormat("void f() { f(fint * b); }");
10555   verifyFormat("class A {\n  void f(int *a);\n};");
10556   verifyFormat("class A {\n  int *a;\n};");
10557   verifyFormat("namespace a {\n"
10558                "namespace b {\n"
10559                "class A {\n"
10560                "  void f() {}\n"
10561                "  int *a;\n"
10562                "};\n"
10563                "} // namespace b\n"
10564                "} // namespace a");
10565 }
10566 
10567 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
10568   verifyFormat("while");
10569   verifyFormat("operator");
10570 }
10571 
10572 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
10573   // This code would be painfully slow to format if we didn't skip it.
10574   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
10575                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
10576                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
10577                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
10578                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
10579                    "A(1, 1)\n"
10580                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
10581                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10582                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10583                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10584                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10585                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10586                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10587                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10588                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
10589                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
10590   // Deeply nested part is untouched, rest is formatted.
10591   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
10592             format(std::string("int    i;\n") + Code + "int    j;\n",
10593                    getLLVMStyle(), SC_ExpectIncomplete));
10594 }
10595 
10596 //===----------------------------------------------------------------------===//
10597 // Objective-C tests.
10598 //===----------------------------------------------------------------------===//
10599 
10600 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
10601   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
10602   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
10603             format("-(NSUInteger)indexOfObject:(id)anObject;"));
10604   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
10605   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
10606   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
10607             format("-(NSInteger)Method3:(id)anObject;"));
10608   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
10609             format("-(NSInteger)Method4:(id)anObject;"));
10610   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
10611             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
10612   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
10613             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
10614   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
10615             "forAllCells:(BOOL)flag;",
10616             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
10617                    "forAllCells:(BOOL)flag;"));
10618 
10619   // Very long objectiveC method declaration.
10620   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
10621                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
10622   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
10623                "                    inRange:(NSRange)range\n"
10624                "                   outRange:(NSRange)out_range\n"
10625                "                  outRange1:(NSRange)out_range1\n"
10626                "                  outRange2:(NSRange)out_range2\n"
10627                "                  outRange3:(NSRange)out_range3\n"
10628                "                  outRange4:(NSRange)out_range4\n"
10629                "                  outRange5:(NSRange)out_range5\n"
10630                "                  outRange6:(NSRange)out_range6\n"
10631                "                  outRange7:(NSRange)out_range7\n"
10632                "                  outRange8:(NSRange)out_range8\n"
10633                "                  outRange9:(NSRange)out_range9;");
10634 
10635   // When the function name has to be wrapped.
10636   FormatStyle Style = getLLVMStyle();
10637   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
10638   // and always indents instead.
10639   Style.IndentWrappedFunctionNames = false;
10640   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
10641                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
10642                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
10643                "}",
10644                Style);
10645   Style.IndentWrappedFunctionNames = true;
10646   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
10647                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
10648                "               anotherName:(NSString)dddddddddddddd {\n"
10649                "}",
10650                Style);
10651 
10652   verifyFormat("- (int)sum:(vector<int>)numbers;");
10653   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
10654   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
10655   // protocol lists (but not for template classes):
10656   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
10657 
10658   verifyFormat("- (int (*)())foo:(int (*)())f;");
10659   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
10660 
10661   // If there's no return type (very rare in practice!), LLVM and Google style
10662   // agree.
10663   verifyFormat("- foo;");
10664   verifyFormat("- foo:(int)f;");
10665   verifyGoogleFormat("- foo:(int)foo;");
10666 }
10667 
10668 TEST_F(FormatTest, BreaksStringLiterals) {
10669   EXPECT_EQ("\"some text \"\n"
10670             "\"other\";",
10671             format("\"some text other\";", getLLVMStyleWithColumns(12)));
10672   EXPECT_EQ("\"some text \"\n"
10673             "\"other\";",
10674             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
10675   EXPECT_EQ(
10676       "#define A  \\\n"
10677       "  \"some \"  \\\n"
10678       "  \"text \"  \\\n"
10679       "  \"other\";",
10680       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
10681   EXPECT_EQ(
10682       "#define A  \\\n"
10683       "  \"so \"    \\\n"
10684       "  \"text \"  \\\n"
10685       "  \"other\";",
10686       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
10687 
10688   EXPECT_EQ("\"some text\"",
10689             format("\"some text\"", getLLVMStyleWithColumns(1)));
10690   EXPECT_EQ("\"some text\"",
10691             format("\"some text\"", getLLVMStyleWithColumns(11)));
10692   EXPECT_EQ("\"some \"\n"
10693             "\"text\"",
10694             format("\"some text\"", getLLVMStyleWithColumns(10)));
10695   EXPECT_EQ("\"some \"\n"
10696             "\"text\"",
10697             format("\"some text\"", getLLVMStyleWithColumns(7)));
10698   EXPECT_EQ("\"some\"\n"
10699             "\" tex\"\n"
10700             "\"t\"",
10701             format("\"some text\"", getLLVMStyleWithColumns(6)));
10702   EXPECT_EQ("\"some\"\n"
10703             "\" tex\"\n"
10704             "\" and\"",
10705             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
10706   EXPECT_EQ("\"some\"\n"
10707             "\"/tex\"\n"
10708             "\"/and\"",
10709             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
10710 
10711   EXPECT_EQ("variable =\n"
10712             "    \"long string \"\n"
10713             "    \"literal\";",
10714             format("variable = \"long string literal\";",
10715                    getLLVMStyleWithColumns(20)));
10716 
10717   EXPECT_EQ("variable = f(\n"
10718             "    \"long string \"\n"
10719             "    \"literal\",\n"
10720             "    short,\n"
10721             "    loooooooooooooooooooong);",
10722             format("variable = f(\"long string literal\", short, "
10723                    "loooooooooooooooooooong);",
10724                    getLLVMStyleWithColumns(20)));
10725 
10726   EXPECT_EQ(
10727       "f(g(\"long string \"\n"
10728       "    \"literal\"),\n"
10729       "  b);",
10730       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
10731   EXPECT_EQ("f(g(\"long string \"\n"
10732             "    \"literal\",\n"
10733             "    a),\n"
10734             "  b);",
10735             format("f(g(\"long string literal\", a), b);",
10736                    getLLVMStyleWithColumns(20)));
10737   EXPECT_EQ(
10738       "f(\"one two\".split(\n"
10739       "    variable));",
10740       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
10741   EXPECT_EQ("f(\"one two three four five six \"\n"
10742             "  \"seven\".split(\n"
10743             "      really_looooong_variable));",
10744             format("f(\"one two three four five six seven\"."
10745                    "split(really_looooong_variable));",
10746                    getLLVMStyleWithColumns(33)));
10747 
10748   EXPECT_EQ("f(\"some \"\n"
10749             "  \"text\",\n"
10750             "  other);",
10751             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
10752 
10753   // Only break as a last resort.
10754   verifyFormat(
10755       "aaaaaaaaaaaaaaaaaaaa(\n"
10756       "    aaaaaaaaaaaaaaaaaaaa,\n"
10757       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
10758 
10759   EXPECT_EQ("\"splitmea\"\n"
10760             "\"trandomp\"\n"
10761             "\"oint\"",
10762             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
10763 
10764   EXPECT_EQ("\"split/\"\n"
10765             "\"pathat/\"\n"
10766             "\"slashes\"",
10767             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
10768 
10769   EXPECT_EQ("\"split/\"\n"
10770             "\"pathat/\"\n"
10771             "\"slashes\"",
10772             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
10773   EXPECT_EQ("\"split at \"\n"
10774             "\"spaces/at/\"\n"
10775             "\"slashes.at.any$\"\n"
10776             "\"non-alphanumeric%\"\n"
10777             "\"1111111111characte\"\n"
10778             "\"rs\"",
10779             format("\"split at "
10780                    "spaces/at/"
10781                    "slashes.at."
10782                    "any$non-"
10783                    "alphanumeric%"
10784                    "1111111111characte"
10785                    "rs\"",
10786                    getLLVMStyleWithColumns(20)));
10787 
10788   // Verify that splitting the strings understands
10789   // Style::AlwaysBreakBeforeMultilineStrings.
10790   EXPECT_EQ("aaaaaaaaaaaa(\n"
10791             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
10792             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
10793             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
10794                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
10795                    "aaaaaaaaaaaaaaaaaaaaaa\");",
10796                    getGoogleStyle()));
10797   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
10798             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
10799             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
10800                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
10801                    "aaaaaaaaaaaaaaaaaaaaaa\";",
10802                    getGoogleStyle()));
10803   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
10804             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
10805             format("llvm::outs() << "
10806                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
10807                    "aaaaaaaaaaaaaaaaaaa\";"));
10808   EXPECT_EQ("ffff(\n"
10809             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
10810             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
10811             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
10812                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
10813                    getGoogleStyle()));
10814 
10815   FormatStyle Style = getLLVMStyleWithColumns(12);
10816   Style.BreakStringLiterals = false;
10817   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
10818 
10819   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
10820   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
10821   EXPECT_EQ("#define A \\\n"
10822             "  \"some \" \\\n"
10823             "  \"text \" \\\n"
10824             "  \"other\";",
10825             format("#define A \"some text other\";", AlignLeft));
10826 }
10827 
10828 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
10829   EXPECT_EQ("C a = \"some more \"\n"
10830             "      \"text\";",
10831             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
10832 }
10833 
10834 TEST_F(FormatTest, FullyRemoveEmptyLines) {
10835   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
10836   NoEmptyLines.MaxEmptyLinesToKeep = 0;
10837   EXPECT_EQ("int i = a(b());",
10838             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
10839 }
10840 
10841 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
10842   EXPECT_EQ(
10843       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
10844       "(\n"
10845       "    \"x\t\");",
10846       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
10847              "aaaaaaa("
10848              "\"x\t\");"));
10849 }
10850 
10851 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
10852   EXPECT_EQ(
10853       "u8\"utf8 string \"\n"
10854       "u8\"literal\";",
10855       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
10856   EXPECT_EQ(
10857       "u\"utf16 string \"\n"
10858       "u\"literal\";",
10859       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
10860   EXPECT_EQ(
10861       "U\"utf32 string \"\n"
10862       "U\"literal\";",
10863       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
10864   EXPECT_EQ("L\"wide string \"\n"
10865             "L\"literal\";",
10866             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
10867   EXPECT_EQ("@\"NSString \"\n"
10868             "@\"literal\";",
10869             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
10870   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
10871 
10872   // This input makes clang-format try to split the incomplete unicode escape
10873   // sequence, which used to lead to a crasher.
10874   verifyNoCrash(
10875       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
10876       getLLVMStyleWithColumns(60));
10877 }
10878 
10879 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
10880   FormatStyle Style = getGoogleStyleWithColumns(15);
10881   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
10882   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
10883   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
10884   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
10885   EXPECT_EQ("u8R\"x(raw literal)x\";",
10886             format("u8R\"x(raw literal)x\";", Style));
10887 }
10888 
10889 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
10890   FormatStyle Style = getLLVMStyleWithColumns(20);
10891   EXPECT_EQ(
10892       "_T(\"aaaaaaaaaaaaaa\")\n"
10893       "_T(\"aaaaaaaaaaaaaa\")\n"
10894       "_T(\"aaaaaaaaaaaa\")",
10895       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
10896   EXPECT_EQ("f(x,\n"
10897             "  _T(\"aaaaaaaaaaaa\")\n"
10898             "  _T(\"aaa\"),\n"
10899             "  z);",
10900             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
10901 
10902   // FIXME: Handle embedded spaces in one iteration.
10903   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
10904   //            "_T(\"aaaaaaaaaaaaa\")\n"
10905   //            "_T(\"aaaaaaaaaaaaa\")\n"
10906   //            "_T(\"a\")",
10907   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
10908   //                   getLLVMStyleWithColumns(20)));
10909   EXPECT_EQ(
10910       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
10911       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
10912   EXPECT_EQ("f(\n"
10913             "#if !TEST\n"
10914             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
10915             "#endif\n"
10916             ");",
10917             format("f(\n"
10918                    "#if !TEST\n"
10919                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
10920                    "#endif\n"
10921                    ");"));
10922   EXPECT_EQ("f(\n"
10923             "\n"
10924             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
10925             format("f(\n"
10926                    "\n"
10927                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
10928 }
10929 
10930 TEST_F(FormatTest, BreaksStringLiteralOperands) {
10931   // In a function call with two operands, the second can be broken with no line
10932   // break before it.
10933   EXPECT_EQ(
10934       "func(a, \"long long \"\n"
10935       "        \"long long\");",
10936       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
10937   // In a function call with three operands, the second must be broken with a
10938   // line break before it.
10939   EXPECT_EQ("func(a,\n"
10940             "     \"long long long \"\n"
10941             "     \"long\",\n"
10942             "     c);",
10943             format("func(a, \"long long long long\", c);",
10944                    getLLVMStyleWithColumns(24)));
10945   // In a function call with three operands, the third must be broken with a
10946   // line break before it.
10947   EXPECT_EQ("func(a, b,\n"
10948             "     \"long long long \"\n"
10949             "     \"long\");",
10950             format("func(a, b, \"long long long long\");",
10951                    getLLVMStyleWithColumns(24)));
10952   // In a function call with three operands, both the second and the third must
10953   // be broken with a line break before them.
10954   EXPECT_EQ("func(a,\n"
10955             "     \"long long long \"\n"
10956             "     \"long\",\n"
10957             "     \"long long long \"\n"
10958             "     \"long\");",
10959             format("func(a, \"long long long long\", \"long long long long\");",
10960                    getLLVMStyleWithColumns(24)));
10961   // In a chain of << with two operands, the second can be broken with no line
10962   // break before it.
10963   EXPECT_EQ("a << \"line line \"\n"
10964             "     \"line\";",
10965             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
10966   // In a chain of << with three operands, the second can be broken with no line
10967   // break before it.
10968   EXPECT_EQ(
10969       "abcde << \"line \"\n"
10970       "         \"line line\"\n"
10971       "      << c;",
10972       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
10973   // In a chain of << with three operands, the third must be broken with a line
10974   // break before it.
10975   EXPECT_EQ(
10976       "a << b\n"
10977       "  << \"line line \"\n"
10978       "     \"line\";",
10979       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
10980   // In a chain of << with three operands, the second can be broken with no line
10981   // break before it and the third must be broken with a line break before it.
10982   EXPECT_EQ("abcd << \"line line \"\n"
10983             "        \"line\"\n"
10984             "     << \"line line \"\n"
10985             "        \"line\";",
10986             format("abcd << \"line line line\" << \"line line line\";",
10987                    getLLVMStyleWithColumns(20)));
10988   // In a chain of binary operators with two operands, the second can be broken
10989   // with no line break before it.
10990   EXPECT_EQ(
10991       "abcd + \"line line \"\n"
10992       "       \"line line\";",
10993       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
10994   // In a chain of binary operators with three operands, the second must be
10995   // broken with a line break before it.
10996   EXPECT_EQ("abcd +\n"
10997             "    \"line line \"\n"
10998             "    \"line line\" +\n"
10999             "    e;",
11000             format("abcd + \"line line line line\" + e;",
11001                    getLLVMStyleWithColumns(20)));
11002   // In a function call with two operands, with AlignAfterOpenBracket enabled,
11003   // the first must be broken with a line break before it.
11004   FormatStyle Style = getLLVMStyleWithColumns(25);
11005   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
11006   EXPECT_EQ("someFunction(\n"
11007             "    \"long long long \"\n"
11008             "    \"long\",\n"
11009             "    a);",
11010             format("someFunction(\"long long long long\", a);", Style));
11011 }
11012 
11013 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
11014   EXPECT_EQ(
11015       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11016       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11017       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
11018       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11019              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11020              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
11021 }
11022 
11023 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
11024   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
11025             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
11026   EXPECT_EQ("fffffffffff(g(R\"x(\n"
11027             "multiline raw string literal xxxxxxxxxxxxxx\n"
11028             ")x\",\n"
11029             "              a),\n"
11030             "            b);",
11031             format("fffffffffff(g(R\"x(\n"
11032                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11033                    ")x\", a), b);",
11034                    getGoogleStyleWithColumns(20)));
11035   EXPECT_EQ("fffffffffff(\n"
11036             "    g(R\"x(qqq\n"
11037             "multiline raw string literal xxxxxxxxxxxxxx\n"
11038             ")x\",\n"
11039             "      a),\n"
11040             "    b);",
11041             format("fffffffffff(g(R\"x(qqq\n"
11042                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11043                    ")x\", a), b);",
11044                    getGoogleStyleWithColumns(20)));
11045 
11046   EXPECT_EQ("fffffffffff(R\"x(\n"
11047             "multiline raw string literal xxxxxxxxxxxxxx\n"
11048             ")x\");",
11049             format("fffffffffff(R\"x(\n"
11050                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11051                    ")x\");",
11052                    getGoogleStyleWithColumns(20)));
11053   EXPECT_EQ("fffffffffff(R\"x(\n"
11054             "multiline raw string literal xxxxxxxxxxxxxx\n"
11055             ")x\" + bbbbbb);",
11056             format("fffffffffff(R\"x(\n"
11057                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11058                    ")x\" +   bbbbbb);",
11059                    getGoogleStyleWithColumns(20)));
11060   EXPECT_EQ("fffffffffff(\n"
11061             "    R\"x(\n"
11062             "multiline raw string literal xxxxxxxxxxxxxx\n"
11063             ")x\" +\n"
11064             "    bbbbbb);",
11065             format("fffffffffff(\n"
11066                    " R\"x(\n"
11067                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11068                    ")x\" + bbbbbb);",
11069                    getGoogleStyleWithColumns(20)));
11070   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
11071             format("fffffffffff(\n"
11072                    " R\"(single line raw string)\" + bbbbbb);"));
11073 }
11074 
11075 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
11076   verifyFormat("string a = \"unterminated;");
11077   EXPECT_EQ("function(\"unterminated,\n"
11078             "         OtherParameter);",
11079             format("function(  \"unterminated,\n"
11080                    "    OtherParameter);"));
11081 }
11082 
11083 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
11084   FormatStyle Style = getLLVMStyle();
11085   Style.Standard = FormatStyle::LS_Cpp03;
11086   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
11087             format("#define x(_a) printf(\"foo\"_a);", Style));
11088 }
11089 
11090 TEST_F(FormatTest, CppLexVersion) {
11091   FormatStyle Style = getLLVMStyle();
11092   // Formatting of x * y differs if x is a type.
11093   verifyFormat("void foo() { MACRO(a * b); }", Style);
11094   verifyFormat("void foo() { MACRO(int *b); }", Style);
11095 
11096   // LLVM style uses latest lexer.
11097   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
11098   Style.Standard = FormatStyle::LS_Cpp17;
11099   // But in c++17, char8_t isn't a keyword.
11100   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
11101 }
11102 
11103 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
11104 
11105 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
11106   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
11107             "             \"ddeeefff\");",
11108             format("someFunction(\"aaabbbcccdddeeefff\");",
11109                    getLLVMStyleWithColumns(25)));
11110   EXPECT_EQ("someFunction1234567890(\n"
11111             "    \"aaabbbcccdddeeefff\");",
11112             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
11113                    getLLVMStyleWithColumns(26)));
11114   EXPECT_EQ("someFunction1234567890(\n"
11115             "    \"aaabbbcccdddeeeff\"\n"
11116             "    \"f\");",
11117             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
11118                    getLLVMStyleWithColumns(25)));
11119   EXPECT_EQ("someFunction1234567890(\n"
11120             "    \"aaabbbcccdddeeeff\"\n"
11121             "    \"f\");",
11122             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
11123                    getLLVMStyleWithColumns(24)));
11124   EXPECT_EQ("someFunction(\n"
11125             "    \"aaabbbcc ddde \"\n"
11126             "    \"efff\");",
11127             format("someFunction(\"aaabbbcc ddde efff\");",
11128                    getLLVMStyleWithColumns(25)));
11129   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
11130             "             \"ddeeefff\");",
11131             format("someFunction(\"aaabbbccc ddeeefff\");",
11132                    getLLVMStyleWithColumns(25)));
11133   EXPECT_EQ("someFunction1234567890(\n"
11134             "    \"aaabb \"\n"
11135             "    \"cccdddeeefff\");",
11136             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
11137                    getLLVMStyleWithColumns(25)));
11138   EXPECT_EQ("#define A          \\\n"
11139             "  string s =       \\\n"
11140             "      \"123456789\"  \\\n"
11141             "      \"0\";         \\\n"
11142             "  int i;",
11143             format("#define A string s = \"1234567890\"; int i;",
11144                    getLLVMStyleWithColumns(20)));
11145   EXPECT_EQ("someFunction(\n"
11146             "    \"aaabbbcc \"\n"
11147             "    \"dddeeefff\");",
11148             format("someFunction(\"aaabbbcc dddeeefff\");",
11149                    getLLVMStyleWithColumns(25)));
11150 }
11151 
11152 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
11153   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
11154   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
11155   EXPECT_EQ("\"test\"\n"
11156             "\"\\n\"",
11157             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
11158   EXPECT_EQ("\"tes\\\\\"\n"
11159             "\"n\"",
11160             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
11161   EXPECT_EQ("\"\\\\\\\\\"\n"
11162             "\"\\n\"",
11163             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
11164   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
11165   EXPECT_EQ("\"\\uff01\"\n"
11166             "\"test\"",
11167             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
11168   EXPECT_EQ("\"\\Uff01ff02\"",
11169             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
11170   EXPECT_EQ("\"\\x000000000001\"\n"
11171             "\"next\"",
11172             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
11173   EXPECT_EQ("\"\\x000000000001next\"",
11174             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
11175   EXPECT_EQ("\"\\x000000000001\"",
11176             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
11177   EXPECT_EQ("\"test\"\n"
11178             "\"\\000000\"\n"
11179             "\"000001\"",
11180             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
11181   EXPECT_EQ("\"test\\000\"\n"
11182             "\"00000000\"\n"
11183             "\"1\"",
11184             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
11185 }
11186 
11187 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
11188   verifyFormat("void f() {\n"
11189                "  return g() {}\n"
11190                "  void h() {}");
11191   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
11192                "g();\n"
11193                "}");
11194 }
11195 
11196 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
11197   verifyFormat(
11198       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
11199 }
11200 
11201 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
11202   verifyFormat("class X {\n"
11203                "  void f() {\n"
11204                "  }\n"
11205                "};",
11206                getLLVMStyleWithColumns(12));
11207 }
11208 
11209 TEST_F(FormatTest, ConfigurableIndentWidth) {
11210   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
11211   EightIndent.IndentWidth = 8;
11212   EightIndent.ContinuationIndentWidth = 8;
11213   verifyFormat("void f() {\n"
11214                "        someFunction();\n"
11215                "        if (true) {\n"
11216                "                f();\n"
11217                "        }\n"
11218                "}",
11219                EightIndent);
11220   verifyFormat("class X {\n"
11221                "        void f() {\n"
11222                "        }\n"
11223                "};",
11224                EightIndent);
11225   verifyFormat("int x[] = {\n"
11226                "        call(),\n"
11227                "        call()};",
11228                EightIndent);
11229 }
11230 
11231 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
11232   verifyFormat("double\n"
11233                "f();",
11234                getLLVMStyleWithColumns(8));
11235 }
11236 
11237 TEST_F(FormatTest, ConfigurableUseOfTab) {
11238   FormatStyle Tab = getLLVMStyleWithColumns(42);
11239   Tab.IndentWidth = 8;
11240   Tab.UseTab = FormatStyle::UT_Always;
11241   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
11242 
11243   EXPECT_EQ("if (aaaaaaaa && // q\n"
11244             "    bb)\t\t// w\n"
11245             "\t;",
11246             format("if (aaaaaaaa &&// q\n"
11247                    "bb)// w\n"
11248                    ";",
11249                    Tab));
11250   EXPECT_EQ("if (aaa && bbb) // w\n"
11251             "\t;",
11252             format("if(aaa&&bbb)// w\n"
11253                    ";",
11254                    Tab));
11255 
11256   verifyFormat("class X {\n"
11257                "\tvoid f() {\n"
11258                "\t\tsomeFunction(parameter1,\n"
11259                "\t\t\t     parameter2);\n"
11260                "\t}\n"
11261                "};",
11262                Tab);
11263   verifyFormat("#define A                        \\\n"
11264                "\tvoid f() {               \\\n"
11265                "\t\tsomeFunction(    \\\n"
11266                "\t\t    parameter1,  \\\n"
11267                "\t\t    parameter2); \\\n"
11268                "\t}",
11269                Tab);
11270   verifyFormat("int a;\t      // x\n"
11271                "int bbbbbbbb; // x\n",
11272                Tab);
11273 
11274   Tab.TabWidth = 4;
11275   Tab.IndentWidth = 8;
11276   verifyFormat("class TabWidth4Indent8 {\n"
11277                "\t\tvoid f() {\n"
11278                "\t\t\t\tsomeFunction(parameter1,\n"
11279                "\t\t\t\t\t\t\t parameter2);\n"
11280                "\t\t}\n"
11281                "};",
11282                Tab);
11283 
11284   Tab.TabWidth = 4;
11285   Tab.IndentWidth = 4;
11286   verifyFormat("class TabWidth4Indent4 {\n"
11287                "\tvoid f() {\n"
11288                "\t\tsomeFunction(parameter1,\n"
11289                "\t\t\t\t\t parameter2);\n"
11290                "\t}\n"
11291                "};",
11292                Tab);
11293 
11294   Tab.TabWidth = 8;
11295   Tab.IndentWidth = 4;
11296   verifyFormat("class TabWidth8Indent4 {\n"
11297                "    void f() {\n"
11298                "\tsomeFunction(parameter1,\n"
11299                "\t\t     parameter2);\n"
11300                "    }\n"
11301                "};",
11302                Tab);
11303 
11304   Tab.TabWidth = 8;
11305   Tab.IndentWidth = 8;
11306   EXPECT_EQ("/*\n"
11307             "\t      a\t\tcomment\n"
11308             "\t      in multiple lines\n"
11309             "       */",
11310             format("   /*\t \t \n"
11311                    " \t \t a\t\tcomment\t \t\n"
11312                    " \t \t in multiple lines\t\n"
11313                    " \t  */",
11314                    Tab));
11315 
11316   Tab.UseTab = FormatStyle::UT_ForIndentation;
11317   verifyFormat("{\n"
11318                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11319                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11320                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11321                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11322                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11323                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11324                "};",
11325                Tab);
11326   verifyFormat("enum AA {\n"
11327                "\ta1, // Force multiple lines\n"
11328                "\ta2,\n"
11329                "\ta3\n"
11330                "};",
11331                Tab);
11332   EXPECT_EQ("if (aaaaaaaa && // q\n"
11333             "    bb)         // w\n"
11334             "\t;",
11335             format("if (aaaaaaaa &&// q\n"
11336                    "bb)// w\n"
11337                    ";",
11338                    Tab));
11339   verifyFormat("class X {\n"
11340                "\tvoid f() {\n"
11341                "\t\tsomeFunction(parameter1,\n"
11342                "\t\t             parameter2);\n"
11343                "\t}\n"
11344                "};",
11345                Tab);
11346   verifyFormat("{\n"
11347                "\tQ(\n"
11348                "\t    {\n"
11349                "\t\t    int a;\n"
11350                "\t\t    someFunction(aaaaaaaa,\n"
11351                "\t\t                 bbbbbbb);\n"
11352                "\t    },\n"
11353                "\t    p);\n"
11354                "}",
11355                Tab);
11356   EXPECT_EQ("{\n"
11357             "\t/* aaaa\n"
11358             "\t   bbbb */\n"
11359             "}",
11360             format("{\n"
11361                    "/* aaaa\n"
11362                    "   bbbb */\n"
11363                    "}",
11364                    Tab));
11365   EXPECT_EQ("{\n"
11366             "\t/*\n"
11367             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11368             "\t  bbbbbbbbbbbbb\n"
11369             "\t*/\n"
11370             "}",
11371             format("{\n"
11372                    "/*\n"
11373                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11374                    "*/\n"
11375                    "}",
11376                    Tab));
11377   EXPECT_EQ("{\n"
11378             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11379             "\t// bbbbbbbbbbbbb\n"
11380             "}",
11381             format("{\n"
11382                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11383                    "}",
11384                    Tab));
11385   EXPECT_EQ("{\n"
11386             "\t/*\n"
11387             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11388             "\t  bbbbbbbbbbbbb\n"
11389             "\t*/\n"
11390             "}",
11391             format("{\n"
11392                    "\t/*\n"
11393                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11394                    "\t*/\n"
11395                    "}",
11396                    Tab));
11397   EXPECT_EQ("{\n"
11398             "\t/*\n"
11399             "\n"
11400             "\t*/\n"
11401             "}",
11402             format("{\n"
11403                    "\t/*\n"
11404                    "\n"
11405                    "\t*/\n"
11406                    "}",
11407                    Tab));
11408   EXPECT_EQ("{\n"
11409             "\t/*\n"
11410             " asdf\n"
11411             "\t*/\n"
11412             "}",
11413             format("{\n"
11414                    "\t/*\n"
11415                    " asdf\n"
11416                    "\t*/\n"
11417                    "}",
11418                    Tab));
11419 
11420   Tab.UseTab = FormatStyle::UT_Never;
11421   EXPECT_EQ("/*\n"
11422             "              a\t\tcomment\n"
11423             "              in multiple lines\n"
11424             "       */",
11425             format("   /*\t \t \n"
11426                    " \t \t a\t\tcomment\t \t\n"
11427                    " \t \t in multiple lines\t\n"
11428                    " \t  */",
11429                    Tab));
11430   EXPECT_EQ("/* some\n"
11431             "   comment */",
11432             format(" \t \t /* some\n"
11433                    " \t \t    comment */",
11434                    Tab));
11435   EXPECT_EQ("int a; /* some\n"
11436             "   comment */",
11437             format(" \t \t int a; /* some\n"
11438                    " \t \t    comment */",
11439                    Tab));
11440 
11441   EXPECT_EQ("int a; /* some\n"
11442             "comment */",
11443             format(" \t \t int\ta; /* some\n"
11444                    " \t \t    comment */",
11445                    Tab));
11446   EXPECT_EQ("f(\"\t\t\"); /* some\n"
11447             "    comment */",
11448             format(" \t \t f(\"\t\t\"); /* some\n"
11449                    " \t \t    comment */",
11450                    Tab));
11451   EXPECT_EQ("{\n"
11452             "        /*\n"
11453             "         * Comment\n"
11454             "         */\n"
11455             "        int i;\n"
11456             "}",
11457             format("{\n"
11458                    "\t/*\n"
11459                    "\t * Comment\n"
11460                    "\t */\n"
11461                    "\t int i;\n"
11462                    "}",
11463                    Tab));
11464 
11465   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
11466   Tab.TabWidth = 8;
11467   Tab.IndentWidth = 8;
11468   EXPECT_EQ("if (aaaaaaaa && // q\n"
11469             "    bb)         // w\n"
11470             "\t;",
11471             format("if (aaaaaaaa &&// q\n"
11472                    "bb)// w\n"
11473                    ";",
11474                    Tab));
11475   EXPECT_EQ("if (aaa && bbb) // w\n"
11476             "\t;",
11477             format("if(aaa&&bbb)// w\n"
11478                    ";",
11479                    Tab));
11480   verifyFormat("class X {\n"
11481                "\tvoid f() {\n"
11482                "\t\tsomeFunction(parameter1,\n"
11483                "\t\t\t     parameter2);\n"
11484                "\t}\n"
11485                "};",
11486                Tab);
11487   verifyFormat("#define A                        \\\n"
11488                "\tvoid f() {               \\\n"
11489                "\t\tsomeFunction(    \\\n"
11490                "\t\t    parameter1,  \\\n"
11491                "\t\t    parameter2); \\\n"
11492                "\t}",
11493                Tab);
11494   Tab.TabWidth = 4;
11495   Tab.IndentWidth = 8;
11496   verifyFormat("class TabWidth4Indent8 {\n"
11497                "\t\tvoid f() {\n"
11498                "\t\t\t\tsomeFunction(parameter1,\n"
11499                "\t\t\t\t\t\t\t parameter2);\n"
11500                "\t\t}\n"
11501                "};",
11502                Tab);
11503   Tab.TabWidth = 4;
11504   Tab.IndentWidth = 4;
11505   verifyFormat("class TabWidth4Indent4 {\n"
11506                "\tvoid f() {\n"
11507                "\t\tsomeFunction(parameter1,\n"
11508                "\t\t\t\t\t parameter2);\n"
11509                "\t}\n"
11510                "};",
11511                Tab);
11512   Tab.TabWidth = 8;
11513   Tab.IndentWidth = 4;
11514   verifyFormat("class TabWidth8Indent4 {\n"
11515                "    void f() {\n"
11516                "\tsomeFunction(parameter1,\n"
11517                "\t\t     parameter2);\n"
11518                "    }\n"
11519                "};",
11520                Tab);
11521   Tab.TabWidth = 8;
11522   Tab.IndentWidth = 8;
11523   EXPECT_EQ("/*\n"
11524             "\t      a\t\tcomment\n"
11525             "\t      in multiple lines\n"
11526             "       */",
11527             format("   /*\t \t \n"
11528                    " \t \t a\t\tcomment\t \t\n"
11529                    " \t \t in multiple lines\t\n"
11530                    " \t  */",
11531                    Tab));
11532   verifyFormat("{\n"
11533                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11534                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11535                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11536                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11537                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11538                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11539                "};",
11540                Tab);
11541   verifyFormat("enum AA {\n"
11542                "\ta1, // Force multiple lines\n"
11543                "\ta2,\n"
11544                "\ta3\n"
11545                "};",
11546                Tab);
11547   EXPECT_EQ("if (aaaaaaaa && // q\n"
11548             "    bb)         // w\n"
11549             "\t;",
11550             format("if (aaaaaaaa &&// q\n"
11551                    "bb)// w\n"
11552                    ";",
11553                    Tab));
11554   verifyFormat("class X {\n"
11555                "\tvoid f() {\n"
11556                "\t\tsomeFunction(parameter1,\n"
11557                "\t\t\t     parameter2);\n"
11558                "\t}\n"
11559                "};",
11560                Tab);
11561   verifyFormat("{\n"
11562                "\tQ(\n"
11563                "\t    {\n"
11564                "\t\t    int a;\n"
11565                "\t\t    someFunction(aaaaaaaa,\n"
11566                "\t\t\t\t bbbbbbb);\n"
11567                "\t    },\n"
11568                "\t    p);\n"
11569                "}",
11570                Tab);
11571   EXPECT_EQ("{\n"
11572             "\t/* aaaa\n"
11573             "\t   bbbb */\n"
11574             "}",
11575             format("{\n"
11576                    "/* aaaa\n"
11577                    "   bbbb */\n"
11578                    "}",
11579                    Tab));
11580   EXPECT_EQ("{\n"
11581             "\t/*\n"
11582             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11583             "\t  bbbbbbbbbbbbb\n"
11584             "\t*/\n"
11585             "}",
11586             format("{\n"
11587                    "/*\n"
11588                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11589                    "*/\n"
11590                    "}",
11591                    Tab));
11592   EXPECT_EQ("{\n"
11593             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11594             "\t// bbbbbbbbbbbbb\n"
11595             "}",
11596             format("{\n"
11597                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11598                    "}",
11599                    Tab));
11600   EXPECT_EQ("{\n"
11601             "\t/*\n"
11602             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11603             "\t  bbbbbbbbbbbbb\n"
11604             "\t*/\n"
11605             "}",
11606             format("{\n"
11607                    "\t/*\n"
11608                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11609                    "\t*/\n"
11610                    "}",
11611                    Tab));
11612   EXPECT_EQ("{\n"
11613             "\t/*\n"
11614             "\n"
11615             "\t*/\n"
11616             "}",
11617             format("{\n"
11618                    "\t/*\n"
11619                    "\n"
11620                    "\t*/\n"
11621                    "}",
11622                    Tab));
11623   EXPECT_EQ("{\n"
11624             "\t/*\n"
11625             " asdf\n"
11626             "\t*/\n"
11627             "}",
11628             format("{\n"
11629                    "\t/*\n"
11630                    " asdf\n"
11631                    "\t*/\n"
11632                    "}",
11633                    Tab));
11634   EXPECT_EQ("/* some\n"
11635             "   comment */",
11636             format(" \t \t /* some\n"
11637                    " \t \t    comment */",
11638                    Tab));
11639   EXPECT_EQ("int a; /* some\n"
11640             "   comment */",
11641             format(" \t \t int a; /* some\n"
11642                    " \t \t    comment */",
11643                    Tab));
11644   EXPECT_EQ("int a; /* some\n"
11645             "comment */",
11646             format(" \t \t int\ta; /* some\n"
11647                    " \t \t    comment */",
11648                    Tab));
11649   EXPECT_EQ("f(\"\t\t\"); /* some\n"
11650             "    comment */",
11651             format(" \t \t f(\"\t\t\"); /* some\n"
11652                    " \t \t    comment */",
11653                    Tab));
11654   EXPECT_EQ("{\n"
11655             "\t/*\n"
11656             "\t * Comment\n"
11657             "\t */\n"
11658             "\tint i;\n"
11659             "}",
11660             format("{\n"
11661                    "\t/*\n"
11662                    "\t * Comment\n"
11663                    "\t */\n"
11664                    "\t int i;\n"
11665                    "}",
11666                    Tab));
11667   Tab.TabWidth = 2;
11668   Tab.IndentWidth = 2;
11669   EXPECT_EQ("{\n"
11670             "\t/* aaaa\n"
11671             "\t\t bbbb */\n"
11672             "}",
11673             format("{\n"
11674                    "/* aaaa\n"
11675                    "\t bbbb */\n"
11676                    "}",
11677                    Tab));
11678   EXPECT_EQ("{\n"
11679             "\t/*\n"
11680             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11681             "\t\tbbbbbbbbbbbbb\n"
11682             "\t*/\n"
11683             "}",
11684             format("{\n"
11685                    "/*\n"
11686                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11687                    "*/\n"
11688                    "}",
11689                    Tab));
11690   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
11691   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
11692   Tab.TabWidth = 4;
11693   Tab.IndentWidth = 4;
11694   verifyFormat("class Assign {\n"
11695                "\tvoid f() {\n"
11696                "\t\tint         x      = 123;\n"
11697                "\t\tint         random = 4;\n"
11698                "\t\tstd::string alphabet =\n"
11699                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
11700                "\t}\n"
11701                "};",
11702                Tab);
11703 
11704   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
11705   Tab.TabWidth = 8;
11706   Tab.IndentWidth = 8;
11707   EXPECT_EQ("if (aaaaaaaa && // q\n"
11708             "    bb)         // w\n"
11709             "\t;",
11710             format("if (aaaaaaaa &&// q\n"
11711                    "bb)// w\n"
11712                    ";",
11713                    Tab));
11714   EXPECT_EQ("if (aaa && bbb) // w\n"
11715             "\t;",
11716             format("if(aaa&&bbb)// w\n"
11717                    ";",
11718                    Tab));
11719   verifyFormat("class X {\n"
11720                "\tvoid f() {\n"
11721                "\t\tsomeFunction(parameter1,\n"
11722                "\t\t             parameter2);\n"
11723                "\t}\n"
11724                "};",
11725                Tab);
11726   verifyFormat("#define A                        \\\n"
11727                "\tvoid f() {               \\\n"
11728                "\t\tsomeFunction(    \\\n"
11729                "\t\t    parameter1,  \\\n"
11730                "\t\t    parameter2); \\\n"
11731                "\t}",
11732                Tab);
11733   Tab.TabWidth = 4;
11734   Tab.IndentWidth = 8;
11735   verifyFormat("class TabWidth4Indent8 {\n"
11736                "\t\tvoid f() {\n"
11737                "\t\t\t\tsomeFunction(parameter1,\n"
11738                "\t\t\t\t             parameter2);\n"
11739                "\t\t}\n"
11740                "};",
11741                Tab);
11742   Tab.TabWidth = 4;
11743   Tab.IndentWidth = 4;
11744   verifyFormat("class TabWidth4Indent4 {\n"
11745                "\tvoid f() {\n"
11746                "\t\tsomeFunction(parameter1,\n"
11747                "\t\t             parameter2);\n"
11748                "\t}\n"
11749                "};",
11750                Tab);
11751   Tab.TabWidth = 8;
11752   Tab.IndentWidth = 4;
11753   verifyFormat("class TabWidth8Indent4 {\n"
11754                "    void f() {\n"
11755                "\tsomeFunction(parameter1,\n"
11756                "\t             parameter2);\n"
11757                "    }\n"
11758                "};",
11759                Tab);
11760   Tab.TabWidth = 8;
11761   Tab.IndentWidth = 8;
11762   EXPECT_EQ("/*\n"
11763             "              a\t\tcomment\n"
11764             "              in multiple lines\n"
11765             "       */",
11766             format("   /*\t \t \n"
11767                    " \t \t a\t\tcomment\t \t\n"
11768                    " \t \t in multiple lines\t\n"
11769                    " \t  */",
11770                    Tab));
11771   verifyFormat("{\n"
11772                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11773                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11774                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11775                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11776                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11777                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11778                "};",
11779                Tab);
11780   verifyFormat("enum AA {\n"
11781                "\ta1, // Force multiple lines\n"
11782                "\ta2,\n"
11783                "\ta3\n"
11784                "};",
11785                Tab);
11786   EXPECT_EQ("if (aaaaaaaa && // q\n"
11787             "    bb)         // w\n"
11788             "\t;",
11789             format("if (aaaaaaaa &&// q\n"
11790                    "bb)// w\n"
11791                    ";",
11792                    Tab));
11793   verifyFormat("class X {\n"
11794                "\tvoid f() {\n"
11795                "\t\tsomeFunction(parameter1,\n"
11796                "\t\t             parameter2);\n"
11797                "\t}\n"
11798                "};",
11799                Tab);
11800   verifyFormat("{\n"
11801                "\tQ(\n"
11802                "\t    {\n"
11803                "\t\t    int a;\n"
11804                "\t\t    someFunction(aaaaaaaa,\n"
11805                "\t\t                 bbbbbbb);\n"
11806                "\t    },\n"
11807                "\t    p);\n"
11808                "}",
11809                Tab);
11810   EXPECT_EQ("{\n"
11811             "\t/* aaaa\n"
11812             "\t   bbbb */\n"
11813             "}",
11814             format("{\n"
11815                    "/* aaaa\n"
11816                    "   bbbb */\n"
11817                    "}",
11818                    Tab));
11819   EXPECT_EQ("{\n"
11820             "\t/*\n"
11821             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11822             "\t  bbbbbbbbbbbbb\n"
11823             "\t*/\n"
11824             "}",
11825             format("{\n"
11826                    "/*\n"
11827                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11828                    "*/\n"
11829                    "}",
11830                    Tab));
11831   EXPECT_EQ("{\n"
11832             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11833             "\t// bbbbbbbbbbbbb\n"
11834             "}",
11835             format("{\n"
11836                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11837                    "}",
11838                    Tab));
11839   EXPECT_EQ("{\n"
11840             "\t/*\n"
11841             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11842             "\t  bbbbbbbbbbbbb\n"
11843             "\t*/\n"
11844             "}",
11845             format("{\n"
11846                    "\t/*\n"
11847                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11848                    "\t*/\n"
11849                    "}",
11850                    Tab));
11851   EXPECT_EQ("{\n"
11852             "\t/*\n"
11853             "\n"
11854             "\t*/\n"
11855             "}",
11856             format("{\n"
11857                    "\t/*\n"
11858                    "\n"
11859                    "\t*/\n"
11860                    "}",
11861                    Tab));
11862   EXPECT_EQ("{\n"
11863             "\t/*\n"
11864             " asdf\n"
11865             "\t*/\n"
11866             "}",
11867             format("{\n"
11868                    "\t/*\n"
11869                    " asdf\n"
11870                    "\t*/\n"
11871                    "}",
11872                    Tab));
11873   EXPECT_EQ("/* some\n"
11874             "   comment */",
11875             format(" \t \t /* some\n"
11876                    " \t \t    comment */",
11877                    Tab));
11878   EXPECT_EQ("int a; /* some\n"
11879             "   comment */",
11880             format(" \t \t int a; /* some\n"
11881                    " \t \t    comment */",
11882                    Tab));
11883   EXPECT_EQ("int a; /* some\n"
11884             "comment */",
11885             format(" \t \t int\ta; /* some\n"
11886                    " \t \t    comment */",
11887                    Tab));
11888   EXPECT_EQ("f(\"\t\t\"); /* some\n"
11889             "    comment */",
11890             format(" \t \t f(\"\t\t\"); /* some\n"
11891                    " \t \t    comment */",
11892                    Tab));
11893   EXPECT_EQ("{\n"
11894             "\t/*\n"
11895             "\t * Comment\n"
11896             "\t */\n"
11897             "\tint i;\n"
11898             "}",
11899             format("{\n"
11900                    "\t/*\n"
11901                    "\t * Comment\n"
11902                    "\t */\n"
11903                    "\t int i;\n"
11904                    "}",
11905                    Tab));
11906   Tab.TabWidth = 2;
11907   Tab.IndentWidth = 2;
11908   EXPECT_EQ("{\n"
11909             "\t/* aaaa\n"
11910             "\t   bbbb */\n"
11911             "}",
11912             format("{\n"
11913                    "/* aaaa\n"
11914                    "   bbbb */\n"
11915                    "}",
11916                    Tab));
11917   EXPECT_EQ("{\n"
11918             "\t/*\n"
11919             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11920             "\t  bbbbbbbbbbbbb\n"
11921             "\t*/\n"
11922             "}",
11923             format("{\n"
11924                    "/*\n"
11925                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11926                    "*/\n"
11927                    "}",
11928                    Tab));
11929   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
11930   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
11931   Tab.TabWidth = 4;
11932   Tab.IndentWidth = 4;
11933   verifyFormat("class Assign {\n"
11934                "\tvoid f() {\n"
11935                "\t\tint         x      = 123;\n"
11936                "\t\tint         random = 4;\n"
11937                "\t\tstd::string alphabet =\n"
11938                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
11939                "\t}\n"
11940                "};",
11941                Tab);
11942   Tab.AlignOperands = FormatStyle::OAS_Align;
11943   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
11944                "                 cccccccccccccccccccc;",
11945                Tab);
11946   // no alignment
11947   verifyFormat("int aaaaaaaaaa =\n"
11948                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
11949                Tab);
11950   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
11951                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
11952                "                        : 333333333333333;",
11953                Tab);
11954   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
11955   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
11956   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
11957                "               + cccccccccccccccccccc;",
11958                Tab);
11959 }
11960 
11961 TEST_F(FormatTest, ZeroTabWidth) {
11962   FormatStyle Tab = getLLVMStyleWithColumns(42);
11963   Tab.IndentWidth = 8;
11964   Tab.UseTab = FormatStyle::UT_Never;
11965   Tab.TabWidth = 0;
11966   EXPECT_EQ("void a(){\n"
11967             "    // line starts with '\t'\n"
11968             "};",
11969             format("void a(){\n"
11970                    "\t// line starts with '\t'\n"
11971                    "};",
11972                    Tab));
11973 
11974   EXPECT_EQ("void a(){\n"
11975             "    // line starts with '\t'\n"
11976             "};",
11977             format("void a(){\n"
11978                    "\t\t// line starts with '\t'\n"
11979                    "};",
11980                    Tab));
11981 
11982   Tab.UseTab = FormatStyle::UT_ForIndentation;
11983   EXPECT_EQ("void a(){\n"
11984             "    // line starts with '\t'\n"
11985             "};",
11986             format("void a(){\n"
11987                    "\t// line starts with '\t'\n"
11988                    "};",
11989                    Tab));
11990 
11991   EXPECT_EQ("void a(){\n"
11992             "    // line starts with '\t'\n"
11993             "};",
11994             format("void a(){\n"
11995                    "\t\t// line starts with '\t'\n"
11996                    "};",
11997                    Tab));
11998 
11999   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
12000   EXPECT_EQ("void a(){\n"
12001             "    // line starts with '\t'\n"
12002             "};",
12003             format("void a(){\n"
12004                    "\t// line starts with '\t'\n"
12005                    "};",
12006                    Tab));
12007 
12008   EXPECT_EQ("void a(){\n"
12009             "    // line starts with '\t'\n"
12010             "};",
12011             format("void a(){\n"
12012                    "\t\t// line starts with '\t'\n"
12013                    "};",
12014                    Tab));
12015 
12016   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
12017   EXPECT_EQ("void a(){\n"
12018             "    // line starts with '\t'\n"
12019             "};",
12020             format("void a(){\n"
12021                    "\t// line starts with '\t'\n"
12022                    "};",
12023                    Tab));
12024 
12025   EXPECT_EQ("void a(){\n"
12026             "    // line starts with '\t'\n"
12027             "};",
12028             format("void a(){\n"
12029                    "\t\t// line starts with '\t'\n"
12030                    "};",
12031                    Tab));
12032 
12033   Tab.UseTab = FormatStyle::UT_Always;
12034   EXPECT_EQ("void a(){\n"
12035             "// line starts with '\t'\n"
12036             "};",
12037             format("void a(){\n"
12038                    "\t// line starts with '\t'\n"
12039                    "};",
12040                    Tab));
12041 
12042   EXPECT_EQ("void a(){\n"
12043             "// line starts with '\t'\n"
12044             "};",
12045             format("void a(){\n"
12046                    "\t\t// line starts with '\t'\n"
12047                    "};",
12048                    Tab));
12049 }
12050 
12051 TEST_F(FormatTest, CalculatesOriginalColumn) {
12052   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12053             "q\"; /* some\n"
12054             "       comment */",
12055             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12056                    "q\"; /* some\n"
12057                    "       comment */",
12058                    getLLVMStyle()));
12059   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
12060             "/* some\n"
12061             "   comment */",
12062             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
12063                    " /* some\n"
12064                    "    comment */",
12065                    getLLVMStyle()));
12066   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12067             "qqq\n"
12068             "/* some\n"
12069             "   comment */",
12070             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12071                    "qqq\n"
12072                    " /* some\n"
12073                    "    comment */",
12074                    getLLVMStyle()));
12075   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12076             "wwww; /* some\n"
12077             "         comment */",
12078             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12079                    "wwww; /* some\n"
12080                    "         comment */",
12081                    getLLVMStyle()));
12082 }
12083 
12084 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
12085   FormatStyle NoSpace = getLLVMStyle();
12086   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
12087 
12088   verifyFormat("while(true)\n"
12089                "  continue;",
12090                NoSpace);
12091   verifyFormat("for(;;)\n"
12092                "  continue;",
12093                NoSpace);
12094   verifyFormat("if(true)\n"
12095                "  f();\n"
12096                "else if(true)\n"
12097                "  f();",
12098                NoSpace);
12099   verifyFormat("do {\n"
12100                "  do_something();\n"
12101                "} while(something());",
12102                NoSpace);
12103   verifyFormat("switch(x) {\n"
12104                "default:\n"
12105                "  break;\n"
12106                "}",
12107                NoSpace);
12108   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
12109   verifyFormat("size_t x = sizeof(x);", NoSpace);
12110   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
12111   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
12112   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
12113   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
12114   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
12115   verifyFormat("alignas(128) char a[128];", NoSpace);
12116   verifyFormat("size_t x = alignof(MyType);", NoSpace);
12117   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
12118   verifyFormat("int f() throw(Deprecated);", NoSpace);
12119   verifyFormat("typedef void (*cb)(int);", NoSpace);
12120   verifyFormat("T A::operator()();", NoSpace);
12121   verifyFormat("X A::operator++(T);", NoSpace);
12122   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
12123 
12124   FormatStyle Space = getLLVMStyle();
12125   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
12126 
12127   verifyFormat("int f ();", Space);
12128   verifyFormat("void f (int a, T b) {\n"
12129                "  while (true)\n"
12130                "    continue;\n"
12131                "}",
12132                Space);
12133   verifyFormat("if (true)\n"
12134                "  f ();\n"
12135                "else if (true)\n"
12136                "  f ();",
12137                Space);
12138   verifyFormat("do {\n"
12139                "  do_something ();\n"
12140                "} while (something ());",
12141                Space);
12142   verifyFormat("switch (x) {\n"
12143                "default:\n"
12144                "  break;\n"
12145                "}",
12146                Space);
12147   verifyFormat("A::A () : a (1) {}", Space);
12148   verifyFormat("void f () __attribute__ ((asdf));", Space);
12149   verifyFormat("*(&a + 1);\n"
12150                "&((&a)[1]);\n"
12151                "a[(b + c) * d];\n"
12152                "(((a + 1) * 2) + 3) * 4;",
12153                Space);
12154   verifyFormat("#define A(x) x", Space);
12155   verifyFormat("#define A (x) x", Space);
12156   verifyFormat("#if defined(x)\n"
12157                "#endif",
12158                Space);
12159   verifyFormat("auto i = std::make_unique<int> (5);", Space);
12160   verifyFormat("size_t x = sizeof (x);", Space);
12161   verifyFormat("auto f (int x) -> decltype (x);", Space);
12162   verifyFormat("auto f (int x) -> typeof (x);", Space);
12163   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
12164   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
12165   verifyFormat("int f (T x) noexcept (x.create ());", Space);
12166   verifyFormat("alignas (128) char a[128];", Space);
12167   verifyFormat("size_t x = alignof (MyType);", Space);
12168   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
12169   verifyFormat("int f () throw (Deprecated);", Space);
12170   verifyFormat("typedef void (*cb) (int);", Space);
12171   verifyFormat("T A::operator() ();", Space);
12172   verifyFormat("X A::operator++ (T);", Space);
12173   verifyFormat("auto lambda = [] () { return 0; };", Space);
12174   verifyFormat("int x = int (y);", Space);
12175 
12176   FormatStyle SomeSpace = getLLVMStyle();
12177   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
12178 
12179   verifyFormat("[]() -> float {}", SomeSpace);
12180   verifyFormat("[] (auto foo) {}", SomeSpace);
12181   verifyFormat("[foo]() -> int {}", SomeSpace);
12182   verifyFormat("int f();", SomeSpace);
12183   verifyFormat("void f (int a, T b) {\n"
12184                "  while (true)\n"
12185                "    continue;\n"
12186                "}",
12187                SomeSpace);
12188   verifyFormat("if (true)\n"
12189                "  f();\n"
12190                "else if (true)\n"
12191                "  f();",
12192                SomeSpace);
12193   verifyFormat("do {\n"
12194                "  do_something();\n"
12195                "} while (something());",
12196                SomeSpace);
12197   verifyFormat("switch (x) {\n"
12198                "default:\n"
12199                "  break;\n"
12200                "}",
12201                SomeSpace);
12202   verifyFormat("A::A() : a (1) {}", SomeSpace);
12203   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
12204   verifyFormat("*(&a + 1);\n"
12205                "&((&a)[1]);\n"
12206                "a[(b + c) * d];\n"
12207                "(((a + 1) * 2) + 3) * 4;",
12208                SomeSpace);
12209   verifyFormat("#define A(x) x", SomeSpace);
12210   verifyFormat("#define A (x) x", SomeSpace);
12211   verifyFormat("#if defined(x)\n"
12212                "#endif",
12213                SomeSpace);
12214   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
12215   verifyFormat("size_t x = sizeof (x);", SomeSpace);
12216   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
12217   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
12218   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
12219   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
12220   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
12221   verifyFormat("alignas (128) char a[128];", SomeSpace);
12222   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
12223   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
12224                SomeSpace);
12225   verifyFormat("int f() throw (Deprecated);", SomeSpace);
12226   verifyFormat("typedef void (*cb) (int);", SomeSpace);
12227   verifyFormat("T A::operator()();", SomeSpace);
12228   verifyFormat("X A::operator++ (T);", SomeSpace);
12229   verifyFormat("int x = int (y);", SomeSpace);
12230   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
12231 }
12232 
12233 TEST_F(FormatTest, SpaceAfterLogicalNot) {
12234   FormatStyle Spaces = getLLVMStyle();
12235   Spaces.SpaceAfterLogicalNot = true;
12236 
12237   verifyFormat("bool x = ! y", Spaces);
12238   verifyFormat("if (! isFailure())", Spaces);
12239   verifyFormat("if (! (a && b))", Spaces);
12240   verifyFormat("\"Error!\"", Spaces);
12241   verifyFormat("! ! x", Spaces);
12242 }
12243 
12244 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
12245   FormatStyle Spaces = getLLVMStyle();
12246 
12247   Spaces.SpacesInParentheses = true;
12248   verifyFormat("do_something( ::globalVar );", Spaces);
12249   verifyFormat("call( x, y, z );", Spaces);
12250   verifyFormat("call();", Spaces);
12251   verifyFormat("std::function<void( int, int )> callback;", Spaces);
12252   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
12253                Spaces);
12254   verifyFormat("while ( (bool)1 )\n"
12255                "  continue;",
12256                Spaces);
12257   verifyFormat("for ( ;; )\n"
12258                "  continue;",
12259                Spaces);
12260   verifyFormat("if ( true )\n"
12261                "  f();\n"
12262                "else if ( true )\n"
12263                "  f();",
12264                Spaces);
12265   verifyFormat("do {\n"
12266                "  do_something( (int)i );\n"
12267                "} while ( something() );",
12268                Spaces);
12269   verifyFormat("switch ( x ) {\n"
12270                "default:\n"
12271                "  break;\n"
12272                "}",
12273                Spaces);
12274 
12275   Spaces.SpacesInParentheses = false;
12276   Spaces.SpacesInCStyleCastParentheses = true;
12277   verifyFormat("Type *A = ( Type * )P;", Spaces);
12278   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
12279   verifyFormat("x = ( int32 )y;", Spaces);
12280   verifyFormat("int a = ( int )(2.0f);", Spaces);
12281   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
12282   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
12283   verifyFormat("#define x (( int )-1)", Spaces);
12284 
12285   // Run the first set of tests again with:
12286   Spaces.SpacesInParentheses = false;
12287   Spaces.SpaceInEmptyParentheses = true;
12288   Spaces.SpacesInCStyleCastParentheses = true;
12289   verifyFormat("call(x, y, z);", Spaces);
12290   verifyFormat("call( );", Spaces);
12291   verifyFormat("std::function<void(int, int)> callback;", Spaces);
12292   verifyFormat("while (( bool )1)\n"
12293                "  continue;",
12294                Spaces);
12295   verifyFormat("for (;;)\n"
12296                "  continue;",
12297                Spaces);
12298   verifyFormat("if (true)\n"
12299                "  f( );\n"
12300                "else if (true)\n"
12301                "  f( );",
12302                Spaces);
12303   verifyFormat("do {\n"
12304                "  do_something(( int )i);\n"
12305                "} while (something( ));",
12306                Spaces);
12307   verifyFormat("switch (x) {\n"
12308                "default:\n"
12309                "  break;\n"
12310                "}",
12311                Spaces);
12312 
12313   // Run the first set of tests again with:
12314   Spaces.SpaceAfterCStyleCast = true;
12315   verifyFormat("call(x, y, z);", Spaces);
12316   verifyFormat("call( );", Spaces);
12317   verifyFormat("std::function<void(int, int)> callback;", Spaces);
12318   verifyFormat("while (( bool ) 1)\n"
12319                "  continue;",
12320                Spaces);
12321   verifyFormat("for (;;)\n"
12322                "  continue;",
12323                Spaces);
12324   verifyFormat("if (true)\n"
12325                "  f( );\n"
12326                "else if (true)\n"
12327                "  f( );",
12328                Spaces);
12329   verifyFormat("do {\n"
12330                "  do_something(( int ) i);\n"
12331                "} while (something( ));",
12332                Spaces);
12333   verifyFormat("switch (x) {\n"
12334                "default:\n"
12335                "  break;\n"
12336                "}",
12337                Spaces);
12338 
12339   // Run subset of tests again with:
12340   Spaces.SpacesInCStyleCastParentheses = false;
12341   Spaces.SpaceAfterCStyleCast = true;
12342   verifyFormat("while ((bool) 1)\n"
12343                "  continue;",
12344                Spaces);
12345   verifyFormat("do {\n"
12346                "  do_something((int) i);\n"
12347                "} while (something( ));",
12348                Spaces);
12349 
12350   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
12351   verifyFormat("size_t idx = (size_t) a;", Spaces);
12352   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
12353   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
12354   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
12355   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
12356   Spaces.SpaceAfterCStyleCast = false;
12357   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
12358   verifyFormat("size_t idx = (size_t)a;", Spaces);
12359   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
12360   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
12361   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
12362   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
12363 }
12364 
12365 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
12366   verifyFormat("int a[5];");
12367   verifyFormat("a[3] += 42;");
12368 
12369   FormatStyle Spaces = getLLVMStyle();
12370   Spaces.SpacesInSquareBrackets = true;
12371   // Not lambdas.
12372   verifyFormat("int a[ 5 ];", Spaces);
12373   verifyFormat("a[ 3 ] += 42;", Spaces);
12374   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
12375   verifyFormat("double &operator[](int i) { return 0; }\n"
12376                "int i;",
12377                Spaces);
12378   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
12379   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
12380   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
12381   // Lambdas.
12382   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
12383   verifyFormat("return [ i, args... ] {};", Spaces);
12384   verifyFormat("int foo = [ &bar ]() {};", Spaces);
12385   verifyFormat("int foo = [ = ]() {};", Spaces);
12386   verifyFormat("int foo = [ & ]() {};", Spaces);
12387   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
12388   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
12389 }
12390 
12391 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
12392   FormatStyle NoSpaceStyle = getLLVMStyle();
12393   verifyFormat("int a[5];", NoSpaceStyle);
12394   verifyFormat("a[3] += 42;", NoSpaceStyle);
12395 
12396   verifyFormat("int a[1];", NoSpaceStyle);
12397   verifyFormat("int 1 [a];", NoSpaceStyle);
12398   verifyFormat("int a[1][2];", NoSpaceStyle);
12399   verifyFormat("a[7] = 5;", NoSpaceStyle);
12400   verifyFormat("int a = (f())[23];", NoSpaceStyle);
12401   verifyFormat("f([] {})", NoSpaceStyle);
12402 
12403   FormatStyle Space = getLLVMStyle();
12404   Space.SpaceBeforeSquareBrackets = true;
12405   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
12406   verifyFormat("return [i, args...] {};", Space);
12407 
12408   verifyFormat("int a [5];", Space);
12409   verifyFormat("a [3] += 42;", Space);
12410   verifyFormat("constexpr char hello []{\"hello\"};", Space);
12411   verifyFormat("double &operator[](int i) { return 0; }\n"
12412                "int i;",
12413                Space);
12414   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
12415   verifyFormat("int i = a [a][a]->f();", Space);
12416   verifyFormat("int i = (*b) [a]->f();", Space);
12417 
12418   verifyFormat("int a [1];", Space);
12419   verifyFormat("int 1 [a];", Space);
12420   verifyFormat("int a [1][2];", Space);
12421   verifyFormat("a [7] = 5;", Space);
12422   verifyFormat("int a = (f()) [23];", Space);
12423   verifyFormat("f([] {})", Space);
12424 }
12425 
12426 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
12427   verifyFormat("int a = 5;");
12428   verifyFormat("a += 42;");
12429   verifyFormat("a or_eq 8;");
12430 
12431   FormatStyle Spaces = getLLVMStyle();
12432   Spaces.SpaceBeforeAssignmentOperators = false;
12433   verifyFormat("int a= 5;", Spaces);
12434   verifyFormat("a+= 42;", Spaces);
12435   verifyFormat("a or_eq 8;", Spaces);
12436 }
12437 
12438 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
12439   verifyFormat("class Foo : public Bar {};");
12440   verifyFormat("Foo::Foo() : foo(1) {}");
12441   verifyFormat("for (auto a : b) {\n}");
12442   verifyFormat("int x = a ? b : c;");
12443   verifyFormat("{\n"
12444                "label0:\n"
12445                "  int x = 0;\n"
12446                "}");
12447   verifyFormat("switch (x) {\n"
12448                "case 1:\n"
12449                "default:\n"
12450                "}");
12451   verifyFormat("switch (allBraces) {\n"
12452                "case 1: {\n"
12453                "  break;\n"
12454                "}\n"
12455                "case 2: {\n"
12456                "  [[fallthrough]];\n"
12457                "}\n"
12458                "default: {\n"
12459                "  break;\n"
12460                "}\n"
12461                "}");
12462 
12463   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
12464   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
12465   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
12466   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
12467   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
12468   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
12469   verifyFormat("{\n"
12470                "label1:\n"
12471                "  int x = 0;\n"
12472                "}",
12473                CtorInitializerStyle);
12474   verifyFormat("switch (x) {\n"
12475                "case 1:\n"
12476                "default:\n"
12477                "}",
12478                CtorInitializerStyle);
12479   verifyFormat("switch (allBraces) {\n"
12480                "case 1: {\n"
12481                "  break;\n"
12482                "}\n"
12483                "case 2: {\n"
12484                "  [[fallthrough]];\n"
12485                "}\n"
12486                "default: {\n"
12487                "  break;\n"
12488                "}\n"
12489                "}",
12490                CtorInitializerStyle);
12491   CtorInitializerStyle.BreakConstructorInitializers =
12492       FormatStyle::BCIS_AfterColon;
12493   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
12494                "    aaaaaaaaaaaaaaaa(1),\n"
12495                "    bbbbbbbbbbbbbbbb(2) {}",
12496                CtorInitializerStyle);
12497   CtorInitializerStyle.BreakConstructorInitializers =
12498       FormatStyle::BCIS_BeforeComma;
12499   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
12500                "    : aaaaaaaaaaaaaaaa(1)\n"
12501                "    , bbbbbbbbbbbbbbbb(2) {}",
12502                CtorInitializerStyle);
12503   CtorInitializerStyle.BreakConstructorInitializers =
12504       FormatStyle::BCIS_BeforeColon;
12505   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
12506                "    : aaaaaaaaaaaaaaaa(1),\n"
12507                "      bbbbbbbbbbbbbbbb(2) {}",
12508                CtorInitializerStyle);
12509   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
12510   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
12511                ": aaaaaaaaaaaaaaaa(1),\n"
12512                "  bbbbbbbbbbbbbbbb(2) {}",
12513                CtorInitializerStyle);
12514 
12515   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
12516   InheritanceStyle.SpaceBeforeInheritanceColon = false;
12517   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
12518   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
12519   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
12520   verifyFormat("int x = a ? b : c;", InheritanceStyle);
12521   verifyFormat("{\n"
12522                "label2:\n"
12523                "  int x = 0;\n"
12524                "}",
12525                InheritanceStyle);
12526   verifyFormat("switch (x) {\n"
12527                "case 1:\n"
12528                "default:\n"
12529                "}",
12530                InheritanceStyle);
12531   verifyFormat("switch (allBraces) {\n"
12532                "case 1: {\n"
12533                "  break;\n"
12534                "}\n"
12535                "case 2: {\n"
12536                "  [[fallthrough]];\n"
12537                "}\n"
12538                "default: {\n"
12539                "  break;\n"
12540                "}\n"
12541                "}",
12542                InheritanceStyle);
12543   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
12544   verifyFormat("class Foooooooooooooooooooooo:\n"
12545                "    public aaaaaaaaaaaaaaaaaa,\n"
12546                "    public bbbbbbbbbbbbbbbbbb {\n"
12547                "}",
12548                InheritanceStyle);
12549   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
12550   verifyFormat("class Foooooooooooooooooooooo\n"
12551                "    : public aaaaaaaaaaaaaaaaaa\n"
12552                "    , public bbbbbbbbbbbbbbbbbb {\n"
12553                "}",
12554                InheritanceStyle);
12555   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
12556   verifyFormat("class Foooooooooooooooooooooo\n"
12557                "    : public aaaaaaaaaaaaaaaaaa,\n"
12558                "      public bbbbbbbbbbbbbbbbbb {\n"
12559                "}",
12560                InheritanceStyle);
12561   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
12562   verifyFormat("class Foooooooooooooooooooooo\n"
12563                ": public aaaaaaaaaaaaaaaaaa,\n"
12564                "  public bbbbbbbbbbbbbbbbbb {}",
12565                InheritanceStyle);
12566 
12567   FormatStyle ForLoopStyle = getLLVMStyle();
12568   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
12569   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
12570   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
12571   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
12572   verifyFormat("int x = a ? b : c;", ForLoopStyle);
12573   verifyFormat("{\n"
12574                "label2:\n"
12575                "  int x = 0;\n"
12576                "}",
12577                ForLoopStyle);
12578   verifyFormat("switch (x) {\n"
12579                "case 1:\n"
12580                "default:\n"
12581                "}",
12582                ForLoopStyle);
12583   verifyFormat("switch (allBraces) {\n"
12584                "case 1: {\n"
12585                "  break;\n"
12586                "}\n"
12587                "case 2: {\n"
12588                "  [[fallthrough]];\n"
12589                "}\n"
12590                "default: {\n"
12591                "  break;\n"
12592                "}\n"
12593                "}",
12594                ForLoopStyle);
12595 
12596   FormatStyle CaseStyle = getLLVMStyle();
12597   CaseStyle.SpaceBeforeCaseColon = true;
12598   verifyFormat("class Foo : public Bar {};", CaseStyle);
12599   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
12600   verifyFormat("for (auto a : b) {\n}", CaseStyle);
12601   verifyFormat("int x = a ? b : c;", CaseStyle);
12602   verifyFormat("switch (x) {\n"
12603                "case 1 :\n"
12604                "default :\n"
12605                "}",
12606                CaseStyle);
12607   verifyFormat("switch (allBraces) {\n"
12608                "case 1 : {\n"
12609                "  break;\n"
12610                "}\n"
12611                "case 2 : {\n"
12612                "  [[fallthrough]];\n"
12613                "}\n"
12614                "default : {\n"
12615                "  break;\n"
12616                "}\n"
12617                "}",
12618                CaseStyle);
12619 
12620   FormatStyle NoSpaceStyle = getLLVMStyle();
12621   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
12622   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
12623   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
12624   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
12625   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
12626   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
12627   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
12628   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
12629   verifyFormat("{\n"
12630                "label3:\n"
12631                "  int x = 0;\n"
12632                "}",
12633                NoSpaceStyle);
12634   verifyFormat("switch (x) {\n"
12635                "case 1:\n"
12636                "default:\n"
12637                "}",
12638                NoSpaceStyle);
12639   verifyFormat("switch (allBraces) {\n"
12640                "case 1: {\n"
12641                "  break;\n"
12642                "}\n"
12643                "case 2: {\n"
12644                "  [[fallthrough]];\n"
12645                "}\n"
12646                "default: {\n"
12647                "  break;\n"
12648                "}\n"
12649                "}",
12650                NoSpaceStyle);
12651 
12652   FormatStyle InvertedSpaceStyle = getLLVMStyle();
12653   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
12654   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
12655   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
12656   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
12657   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
12658   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
12659   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
12660   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
12661   verifyFormat("{\n"
12662                "label3:\n"
12663                "  int x = 0;\n"
12664                "}",
12665                InvertedSpaceStyle);
12666   verifyFormat("switch (x) {\n"
12667                "case 1 :\n"
12668                "case 2 : {\n"
12669                "  break;\n"
12670                "}\n"
12671                "default :\n"
12672                "  break;\n"
12673                "}",
12674                InvertedSpaceStyle);
12675   verifyFormat("switch (allBraces) {\n"
12676                "case 1 : {\n"
12677                "  break;\n"
12678                "}\n"
12679                "case 2 : {\n"
12680                "  [[fallthrough]];\n"
12681                "}\n"
12682                "default : {\n"
12683                "  break;\n"
12684                "}\n"
12685                "}",
12686                InvertedSpaceStyle);
12687 }
12688 
12689 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
12690   FormatStyle Style = getLLVMStyle();
12691 
12692   Style.PointerAlignment = FormatStyle::PAS_Left;
12693   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
12694   verifyFormat("void* const* x = NULL;", Style);
12695 
12696 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
12697   do {                                                                         \
12698     Style.PointerAlignment = FormatStyle::Pointers;                            \
12699     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
12700     verifyFormat(Code, Style);                                                 \
12701   } while (false)
12702 
12703   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
12704   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
12705   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
12706 
12707   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
12708   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
12709   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
12710 
12711   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
12712   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
12713   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
12714 
12715   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
12716   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
12717   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
12718 
12719 #undef verifyQualifierSpaces
12720 
12721   FormatStyle Spaces = getLLVMStyle();
12722   Spaces.AttributeMacros.push_back("qualified");
12723   Spaces.PointerAlignment = FormatStyle::PAS_Right;
12724   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
12725   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
12726   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
12727   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
12728   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
12729   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
12730   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
12731   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
12732   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
12733   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
12734   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
12735   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
12736 
12737   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
12738   Spaces.PointerAlignment = FormatStyle::PAS_Left;
12739   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
12740   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
12741   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
12742   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
12743   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
12744   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
12745   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
12746   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
12747   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
12748   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
12749   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
12750   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
12751   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
12752 
12753   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
12754   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
12755   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
12756   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
12757   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
12758   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
12759   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
12760   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
12761 }
12762 
12763 TEST_F(FormatTest, AlignConsecutiveMacros) {
12764   FormatStyle Style = getLLVMStyle();
12765   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
12766   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
12767   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
12768 
12769   verifyFormat("#define a 3\n"
12770                "#define bbbb 4\n"
12771                "#define ccc (5)",
12772                Style);
12773 
12774   verifyFormat("#define f(x) (x * x)\n"
12775                "#define fff(x, y, z) (x * y + z)\n"
12776                "#define ffff(x, y) (x - y)",
12777                Style);
12778 
12779   verifyFormat("#define foo(x, y) (x + y)\n"
12780                "#define bar (5, 6)(2 + 2)",
12781                Style);
12782 
12783   verifyFormat("#define a 3\n"
12784                "#define bbbb 4\n"
12785                "#define ccc (5)\n"
12786                "#define f(x) (x * x)\n"
12787                "#define fff(x, y, z) (x * y + z)\n"
12788                "#define ffff(x, y) (x - y)",
12789                Style);
12790 
12791   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
12792   verifyFormat("#define a    3\n"
12793                "#define bbbb 4\n"
12794                "#define ccc  (5)",
12795                Style);
12796 
12797   verifyFormat("#define f(x)         (x * x)\n"
12798                "#define fff(x, y, z) (x * y + z)\n"
12799                "#define ffff(x, y)   (x - y)",
12800                Style);
12801 
12802   verifyFormat("#define foo(x, y) (x + y)\n"
12803                "#define bar       (5, 6)(2 + 2)",
12804                Style);
12805 
12806   verifyFormat("#define a            3\n"
12807                "#define bbbb         4\n"
12808                "#define ccc          (5)\n"
12809                "#define f(x)         (x * x)\n"
12810                "#define fff(x, y, z) (x * y + z)\n"
12811                "#define ffff(x, y)   (x - y)",
12812                Style);
12813 
12814   verifyFormat("#define a         5\n"
12815                "#define foo(x, y) (x + y)\n"
12816                "#define CCC       (6)\n"
12817                "auto lambda = []() {\n"
12818                "  auto  ii = 0;\n"
12819                "  float j  = 0;\n"
12820                "  return 0;\n"
12821                "};\n"
12822                "int   i  = 0;\n"
12823                "float i2 = 0;\n"
12824                "auto  v  = type{\n"
12825                "    i = 1,   //\n"
12826                "    (i = 2), //\n"
12827                "    i = 3    //\n"
12828                "};",
12829                Style);
12830 
12831   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
12832   Style.ColumnLimit = 20;
12833 
12834   verifyFormat("#define a          \\\n"
12835                "  \"aabbbbbbbbbbbb\"\n"
12836                "#define D          \\\n"
12837                "  \"aabbbbbbbbbbbb\" \\\n"
12838                "  \"ccddeeeeeeeee\"\n"
12839                "#define B          \\\n"
12840                "  \"QQQQQQQQQQQQQ\"  \\\n"
12841                "  \"FFFFFFFFFFFFF\"  \\\n"
12842                "  \"LLLLLLLL\"\n",
12843                Style);
12844 
12845   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
12846   verifyFormat("#define a          \\\n"
12847                "  \"aabbbbbbbbbbbb\"\n"
12848                "#define D          \\\n"
12849                "  \"aabbbbbbbbbbbb\" \\\n"
12850                "  \"ccddeeeeeeeee\"\n"
12851                "#define B          \\\n"
12852                "  \"QQQQQQQQQQQQQ\"  \\\n"
12853                "  \"FFFFFFFFFFFFF\"  \\\n"
12854                "  \"LLLLLLLL\"\n",
12855                Style);
12856 
12857   // Test across comments
12858   Style.MaxEmptyLinesToKeep = 10;
12859   Style.ReflowComments = false;
12860   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
12861   EXPECT_EQ("#define a    3\n"
12862             "// line comment\n"
12863             "#define bbbb 4\n"
12864             "#define ccc  (5)",
12865             format("#define a 3\n"
12866                    "// line comment\n"
12867                    "#define bbbb 4\n"
12868                    "#define ccc (5)",
12869                    Style));
12870 
12871   EXPECT_EQ("#define a    3\n"
12872             "/* block comment */\n"
12873             "#define bbbb 4\n"
12874             "#define ccc  (5)",
12875             format("#define a  3\n"
12876                    "/* block comment */\n"
12877                    "#define bbbb 4\n"
12878                    "#define ccc (5)",
12879                    Style));
12880 
12881   EXPECT_EQ("#define a    3\n"
12882             "/* multi-line *\n"
12883             " * block comment */\n"
12884             "#define bbbb 4\n"
12885             "#define ccc  (5)",
12886             format("#define a 3\n"
12887                    "/* multi-line *\n"
12888                    " * block comment */\n"
12889                    "#define bbbb 4\n"
12890                    "#define ccc (5)",
12891                    Style));
12892 
12893   EXPECT_EQ("#define a    3\n"
12894             "// multi-line line comment\n"
12895             "//\n"
12896             "#define bbbb 4\n"
12897             "#define ccc  (5)",
12898             format("#define a  3\n"
12899                    "// multi-line line comment\n"
12900                    "//\n"
12901                    "#define bbbb 4\n"
12902                    "#define ccc (5)",
12903                    Style));
12904 
12905   EXPECT_EQ("#define a 3\n"
12906             "// empty lines still break.\n"
12907             "\n"
12908             "#define bbbb 4\n"
12909             "#define ccc  (5)",
12910             format("#define a     3\n"
12911                    "// empty lines still break.\n"
12912                    "\n"
12913                    "#define bbbb     4\n"
12914                    "#define ccc  (5)",
12915                    Style));
12916 
12917   // Test across empty lines
12918   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
12919   EXPECT_EQ("#define a    3\n"
12920             "\n"
12921             "#define bbbb 4\n"
12922             "#define ccc  (5)",
12923             format("#define a 3\n"
12924                    "\n"
12925                    "#define bbbb 4\n"
12926                    "#define ccc (5)",
12927                    Style));
12928 
12929   EXPECT_EQ("#define a    3\n"
12930             "\n"
12931             "\n"
12932             "\n"
12933             "#define bbbb 4\n"
12934             "#define ccc  (5)",
12935             format("#define a        3\n"
12936                    "\n"
12937                    "\n"
12938                    "\n"
12939                    "#define bbbb 4\n"
12940                    "#define ccc (5)",
12941                    Style));
12942 
12943   EXPECT_EQ("#define a 3\n"
12944             "// comments should break alignment\n"
12945             "//\n"
12946             "#define bbbb 4\n"
12947             "#define ccc  (5)",
12948             format("#define a        3\n"
12949                    "// comments should break alignment\n"
12950                    "//\n"
12951                    "#define bbbb 4\n"
12952                    "#define ccc (5)",
12953                    Style));
12954 
12955   // Test across empty lines and comments
12956   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
12957   verifyFormat("#define a    3\n"
12958                "\n"
12959                "// line comment\n"
12960                "#define bbbb 4\n"
12961                "#define ccc  (5)",
12962                Style);
12963 
12964   EXPECT_EQ("#define a    3\n"
12965             "\n"
12966             "\n"
12967             "/* multi-line *\n"
12968             " * block comment */\n"
12969             "\n"
12970             "\n"
12971             "#define bbbb 4\n"
12972             "#define ccc  (5)",
12973             format("#define a 3\n"
12974                    "\n"
12975                    "\n"
12976                    "/* multi-line *\n"
12977                    " * block comment */\n"
12978                    "\n"
12979                    "\n"
12980                    "#define bbbb 4\n"
12981                    "#define ccc (5)",
12982                    Style));
12983 
12984   EXPECT_EQ("#define a    3\n"
12985             "\n"
12986             "\n"
12987             "/* multi-line *\n"
12988             " * block comment */\n"
12989             "\n"
12990             "\n"
12991             "#define bbbb 4\n"
12992             "#define ccc  (5)",
12993             format("#define a 3\n"
12994                    "\n"
12995                    "\n"
12996                    "/* multi-line *\n"
12997                    " * block comment */\n"
12998                    "\n"
12999                    "\n"
13000                    "#define bbbb 4\n"
13001                    "#define ccc       (5)",
13002                    Style));
13003 }
13004 
13005 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
13006   FormatStyle Alignment = getLLVMStyle();
13007   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13008   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
13009 
13010   Alignment.MaxEmptyLinesToKeep = 10;
13011   /* Test alignment across empty lines */
13012   EXPECT_EQ("int a           = 5;\n"
13013             "\n"
13014             "int oneTwoThree = 123;",
13015             format("int a       = 5;\n"
13016                    "\n"
13017                    "int oneTwoThree= 123;",
13018                    Alignment));
13019   EXPECT_EQ("int a           = 5;\n"
13020             "int one         = 1;\n"
13021             "\n"
13022             "int oneTwoThree = 123;",
13023             format("int a = 5;\n"
13024                    "int one = 1;\n"
13025                    "\n"
13026                    "int oneTwoThree = 123;",
13027                    Alignment));
13028   EXPECT_EQ("int a           = 5;\n"
13029             "int one         = 1;\n"
13030             "\n"
13031             "int oneTwoThree = 123;\n"
13032             "int oneTwo      = 12;",
13033             format("int a = 5;\n"
13034                    "int one = 1;\n"
13035                    "\n"
13036                    "int oneTwoThree = 123;\n"
13037                    "int oneTwo = 12;",
13038                    Alignment));
13039 
13040   /* Test across comments */
13041   EXPECT_EQ("int a = 5;\n"
13042             "/* block comment */\n"
13043             "int oneTwoThree = 123;",
13044             format("int a = 5;\n"
13045                    "/* block comment */\n"
13046                    "int oneTwoThree=123;",
13047                    Alignment));
13048 
13049   EXPECT_EQ("int a = 5;\n"
13050             "// line comment\n"
13051             "int oneTwoThree = 123;",
13052             format("int a = 5;\n"
13053                    "// line comment\n"
13054                    "int oneTwoThree=123;",
13055                    Alignment));
13056 
13057   /* Test across comments and newlines */
13058   EXPECT_EQ("int a = 5;\n"
13059             "\n"
13060             "/* block comment */\n"
13061             "int oneTwoThree = 123;",
13062             format("int a = 5;\n"
13063                    "\n"
13064                    "/* block comment */\n"
13065                    "int oneTwoThree=123;",
13066                    Alignment));
13067 
13068   EXPECT_EQ("int a = 5;\n"
13069             "\n"
13070             "// line comment\n"
13071             "int oneTwoThree = 123;",
13072             format("int a = 5;\n"
13073                    "\n"
13074                    "// line comment\n"
13075                    "int oneTwoThree=123;",
13076                    Alignment));
13077 }
13078 
13079 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
13080   FormatStyle Alignment = getLLVMStyle();
13081   Alignment.AlignConsecutiveDeclarations =
13082       FormatStyle::ACS_AcrossEmptyLinesAndComments;
13083   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
13084 
13085   Alignment.MaxEmptyLinesToKeep = 10;
13086   /* Test alignment across empty lines */
13087   EXPECT_EQ("int         a = 5;\n"
13088             "\n"
13089             "float const oneTwoThree = 123;",
13090             format("int a = 5;\n"
13091                    "\n"
13092                    "float const oneTwoThree = 123;",
13093                    Alignment));
13094   EXPECT_EQ("int         a = 5;\n"
13095             "float const one = 1;\n"
13096             "\n"
13097             "int         oneTwoThree = 123;",
13098             format("int a = 5;\n"
13099                    "float const one = 1;\n"
13100                    "\n"
13101                    "int oneTwoThree = 123;",
13102                    Alignment));
13103 
13104   /* Test across comments */
13105   EXPECT_EQ("float const a = 5;\n"
13106             "/* block comment */\n"
13107             "int         oneTwoThree = 123;",
13108             format("float const a = 5;\n"
13109                    "/* block comment */\n"
13110                    "int oneTwoThree=123;",
13111                    Alignment));
13112 
13113   EXPECT_EQ("float const a = 5;\n"
13114             "// line comment\n"
13115             "int         oneTwoThree = 123;",
13116             format("float const a = 5;\n"
13117                    "// line comment\n"
13118                    "int oneTwoThree=123;",
13119                    Alignment));
13120 
13121   /* Test across comments and newlines */
13122   EXPECT_EQ("float const a = 5;\n"
13123             "\n"
13124             "/* block comment */\n"
13125             "int         oneTwoThree = 123;",
13126             format("float const a = 5;\n"
13127                    "\n"
13128                    "/* block comment */\n"
13129                    "int         oneTwoThree=123;",
13130                    Alignment));
13131 
13132   EXPECT_EQ("float const a = 5;\n"
13133             "\n"
13134             "// line comment\n"
13135             "int         oneTwoThree = 123;",
13136             format("float const a = 5;\n"
13137                    "\n"
13138                    "// line comment\n"
13139                    "int oneTwoThree=123;",
13140                    Alignment));
13141 }
13142 
13143 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
13144   FormatStyle Alignment = getLLVMStyle();
13145   Alignment.AlignConsecutiveBitFields =
13146       FormatStyle::ACS_AcrossEmptyLinesAndComments;
13147 
13148   Alignment.MaxEmptyLinesToKeep = 10;
13149   /* Test alignment across empty lines */
13150   EXPECT_EQ("int a            : 5;\n"
13151             "\n"
13152             "int longbitfield : 6;",
13153             format("int a : 5;\n"
13154                    "\n"
13155                    "int longbitfield : 6;",
13156                    Alignment));
13157   EXPECT_EQ("int a            : 5;\n"
13158             "int one          : 1;\n"
13159             "\n"
13160             "int longbitfield : 6;",
13161             format("int a : 5;\n"
13162                    "int one : 1;\n"
13163                    "\n"
13164                    "int longbitfield : 6;",
13165                    Alignment));
13166 
13167   /* Test across comments */
13168   EXPECT_EQ("int a            : 5;\n"
13169             "/* block comment */\n"
13170             "int longbitfield : 6;",
13171             format("int a : 5;\n"
13172                    "/* block comment */\n"
13173                    "int longbitfield : 6;",
13174                    Alignment));
13175   EXPECT_EQ("int a            : 5;\n"
13176             "int one          : 1;\n"
13177             "// line comment\n"
13178             "int longbitfield : 6;",
13179             format("int a : 5;\n"
13180                    "int one : 1;\n"
13181                    "// line comment\n"
13182                    "int longbitfield : 6;",
13183                    Alignment));
13184 
13185   /* Test across comments and newlines */
13186   EXPECT_EQ("int a            : 5;\n"
13187             "/* block comment */\n"
13188             "\n"
13189             "int longbitfield : 6;",
13190             format("int a : 5;\n"
13191                    "/* block comment */\n"
13192                    "\n"
13193                    "int longbitfield : 6;",
13194                    Alignment));
13195   EXPECT_EQ("int a            : 5;\n"
13196             "int one          : 1;\n"
13197             "\n"
13198             "// line comment\n"
13199             "\n"
13200             "int longbitfield : 6;",
13201             format("int a : 5;\n"
13202                    "int one : 1;\n"
13203                    "\n"
13204                    "// line comment \n"
13205                    "\n"
13206                    "int longbitfield : 6;",
13207                    Alignment));
13208 }
13209 
13210 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
13211   FormatStyle Alignment = getLLVMStyle();
13212   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13213   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
13214 
13215   Alignment.MaxEmptyLinesToKeep = 10;
13216   /* Test alignment across empty lines */
13217   EXPECT_EQ("int a = 5;\n"
13218             "\n"
13219             "int oneTwoThree = 123;",
13220             format("int a       = 5;\n"
13221                    "\n"
13222                    "int oneTwoThree= 123;",
13223                    Alignment));
13224   EXPECT_EQ("int a   = 5;\n"
13225             "int one = 1;\n"
13226             "\n"
13227             "int oneTwoThree = 123;",
13228             format("int a = 5;\n"
13229                    "int one = 1;\n"
13230                    "\n"
13231                    "int oneTwoThree = 123;",
13232                    Alignment));
13233 
13234   /* Test across comments */
13235   EXPECT_EQ("int a           = 5;\n"
13236             "/* block comment */\n"
13237             "int oneTwoThree = 123;",
13238             format("int a = 5;\n"
13239                    "/* block comment */\n"
13240                    "int oneTwoThree=123;",
13241                    Alignment));
13242 
13243   EXPECT_EQ("int a           = 5;\n"
13244             "// line comment\n"
13245             "int oneTwoThree = 123;",
13246             format("int a = 5;\n"
13247                    "// line comment\n"
13248                    "int oneTwoThree=123;",
13249                    Alignment));
13250 
13251   EXPECT_EQ("int a           = 5;\n"
13252             "/*\n"
13253             " * multi-line block comment\n"
13254             " */\n"
13255             "int oneTwoThree = 123;",
13256             format("int a = 5;\n"
13257                    "/*\n"
13258                    " * multi-line block comment\n"
13259                    " */\n"
13260                    "int oneTwoThree=123;",
13261                    Alignment));
13262 
13263   EXPECT_EQ("int a           = 5;\n"
13264             "//\n"
13265             "// multi-line line comment\n"
13266             "//\n"
13267             "int oneTwoThree = 123;",
13268             format("int a = 5;\n"
13269                    "//\n"
13270                    "// multi-line line comment\n"
13271                    "//\n"
13272                    "int oneTwoThree=123;",
13273                    Alignment));
13274 
13275   /* Test across comments and newlines */
13276   EXPECT_EQ("int a = 5;\n"
13277             "\n"
13278             "/* block comment */\n"
13279             "int oneTwoThree = 123;",
13280             format("int a = 5;\n"
13281                    "\n"
13282                    "/* block comment */\n"
13283                    "int oneTwoThree=123;",
13284                    Alignment));
13285 
13286   EXPECT_EQ("int a = 5;\n"
13287             "\n"
13288             "// line comment\n"
13289             "int oneTwoThree = 123;",
13290             format("int a = 5;\n"
13291                    "\n"
13292                    "// line comment\n"
13293                    "int oneTwoThree=123;",
13294                    Alignment));
13295 }
13296 
13297 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
13298   FormatStyle Alignment = getLLVMStyle();
13299   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13300   Alignment.AlignConsecutiveAssignments =
13301       FormatStyle::ACS_AcrossEmptyLinesAndComments;
13302   verifyFormat("int a           = 5;\n"
13303                "int oneTwoThree = 123;",
13304                Alignment);
13305   verifyFormat("int a           = method();\n"
13306                "int oneTwoThree = 133;",
13307                Alignment);
13308   verifyFormat("a &= 5;\n"
13309                "bcd *= 5;\n"
13310                "ghtyf += 5;\n"
13311                "dvfvdb -= 5;\n"
13312                "a /= 5;\n"
13313                "vdsvsv %= 5;\n"
13314                "sfdbddfbdfbb ^= 5;\n"
13315                "dvsdsv |= 5;\n"
13316                "int dsvvdvsdvvv = 123;",
13317                Alignment);
13318   verifyFormat("int i = 1, j = 10;\n"
13319                "something = 2000;",
13320                Alignment);
13321   verifyFormat("something = 2000;\n"
13322                "int i = 1, j = 10;\n",
13323                Alignment);
13324   verifyFormat("something = 2000;\n"
13325                "another   = 911;\n"
13326                "int i = 1, j = 10;\n"
13327                "oneMore = 1;\n"
13328                "i       = 2;",
13329                Alignment);
13330   verifyFormat("int a   = 5;\n"
13331                "int one = 1;\n"
13332                "method();\n"
13333                "int oneTwoThree = 123;\n"
13334                "int oneTwo      = 12;",
13335                Alignment);
13336   verifyFormat("int oneTwoThree = 123;\n"
13337                "int oneTwo      = 12;\n"
13338                "method();\n",
13339                Alignment);
13340   verifyFormat("int oneTwoThree = 123; // comment\n"
13341                "int oneTwo      = 12;  // comment",
13342                Alignment);
13343 
13344   // Bug 25167
13345   /* Uncomment when fixed
13346     verifyFormat("#if A\n"
13347                  "#else\n"
13348                  "int aaaaaaaa = 12;\n"
13349                  "#endif\n"
13350                  "#if B\n"
13351                  "#else\n"
13352                  "int a = 12;\n"
13353                  "#endif\n",
13354                  Alignment);
13355     verifyFormat("enum foo {\n"
13356                  "#if A\n"
13357                  "#else\n"
13358                  "  aaaaaaaa = 12;\n"
13359                  "#endif\n"
13360                  "#if B\n"
13361                  "#else\n"
13362                  "  a = 12;\n"
13363                  "#endif\n"
13364                  "};\n",
13365                  Alignment);
13366   */
13367 
13368   Alignment.MaxEmptyLinesToKeep = 10;
13369   /* Test alignment across empty lines */
13370   EXPECT_EQ("int a           = 5;\n"
13371             "\n"
13372             "int oneTwoThree = 123;",
13373             format("int a       = 5;\n"
13374                    "\n"
13375                    "int oneTwoThree= 123;",
13376                    Alignment));
13377   EXPECT_EQ("int a           = 5;\n"
13378             "int one         = 1;\n"
13379             "\n"
13380             "int oneTwoThree = 123;",
13381             format("int a = 5;\n"
13382                    "int one = 1;\n"
13383                    "\n"
13384                    "int oneTwoThree = 123;",
13385                    Alignment));
13386   EXPECT_EQ("int a           = 5;\n"
13387             "int one         = 1;\n"
13388             "\n"
13389             "int oneTwoThree = 123;\n"
13390             "int oneTwo      = 12;",
13391             format("int a = 5;\n"
13392                    "int one = 1;\n"
13393                    "\n"
13394                    "int oneTwoThree = 123;\n"
13395                    "int oneTwo = 12;",
13396                    Alignment));
13397 
13398   /* Test across comments */
13399   EXPECT_EQ("int a           = 5;\n"
13400             "/* block comment */\n"
13401             "int oneTwoThree = 123;",
13402             format("int a = 5;\n"
13403                    "/* block comment */\n"
13404                    "int oneTwoThree=123;",
13405                    Alignment));
13406 
13407   EXPECT_EQ("int a           = 5;\n"
13408             "// line comment\n"
13409             "int oneTwoThree = 123;",
13410             format("int a = 5;\n"
13411                    "// line comment\n"
13412                    "int oneTwoThree=123;",
13413                    Alignment));
13414 
13415   /* Test across comments and newlines */
13416   EXPECT_EQ("int a           = 5;\n"
13417             "\n"
13418             "/* block comment */\n"
13419             "int oneTwoThree = 123;",
13420             format("int a = 5;\n"
13421                    "\n"
13422                    "/* block comment */\n"
13423                    "int oneTwoThree=123;",
13424                    Alignment));
13425 
13426   EXPECT_EQ("int a           = 5;\n"
13427             "\n"
13428             "// line comment\n"
13429             "int oneTwoThree = 123;",
13430             format("int a = 5;\n"
13431                    "\n"
13432                    "// line comment\n"
13433                    "int oneTwoThree=123;",
13434                    Alignment));
13435 
13436   EXPECT_EQ("int a           = 5;\n"
13437             "//\n"
13438             "// multi-line line comment\n"
13439             "//\n"
13440             "int oneTwoThree = 123;",
13441             format("int a = 5;\n"
13442                    "//\n"
13443                    "// multi-line line comment\n"
13444                    "//\n"
13445                    "int oneTwoThree=123;",
13446                    Alignment));
13447 
13448   EXPECT_EQ("int a           = 5;\n"
13449             "/*\n"
13450             " *  multi-line block comment\n"
13451             " */\n"
13452             "int oneTwoThree = 123;",
13453             format("int a = 5;\n"
13454                    "/*\n"
13455                    " *  multi-line block comment\n"
13456                    " */\n"
13457                    "int oneTwoThree=123;",
13458                    Alignment));
13459 
13460   EXPECT_EQ("int a           = 5;\n"
13461             "\n"
13462             "/* block comment */\n"
13463             "\n"
13464             "\n"
13465             "\n"
13466             "int oneTwoThree = 123;",
13467             format("int a = 5;\n"
13468                    "\n"
13469                    "/* block comment */\n"
13470                    "\n"
13471                    "\n"
13472                    "\n"
13473                    "int oneTwoThree=123;",
13474                    Alignment));
13475 
13476   EXPECT_EQ("int a           = 5;\n"
13477             "\n"
13478             "// line comment\n"
13479             "\n"
13480             "\n"
13481             "\n"
13482             "int oneTwoThree = 123;",
13483             format("int a = 5;\n"
13484                    "\n"
13485                    "// line comment\n"
13486                    "\n"
13487                    "\n"
13488                    "\n"
13489                    "int oneTwoThree=123;",
13490                    Alignment));
13491 
13492   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
13493   verifyFormat("#define A \\\n"
13494                "  int aaaa       = 12; \\\n"
13495                "  int b          = 23; \\\n"
13496                "  int ccc        = 234; \\\n"
13497                "  int dddddddddd = 2345;",
13498                Alignment);
13499   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13500   verifyFormat("#define A               \\\n"
13501                "  int aaaa       = 12;  \\\n"
13502                "  int b          = 23;  \\\n"
13503                "  int ccc        = 234; \\\n"
13504                "  int dddddddddd = 2345;",
13505                Alignment);
13506   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
13507   verifyFormat("#define A                                                      "
13508                "                \\\n"
13509                "  int aaaa       = 12;                                         "
13510                "                \\\n"
13511                "  int b          = 23;                                         "
13512                "                \\\n"
13513                "  int ccc        = 234;                                        "
13514                "                \\\n"
13515                "  int dddddddddd = 2345;",
13516                Alignment);
13517   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
13518                "k = 4, int l = 5,\n"
13519                "                  int m = 6) {\n"
13520                "  int j      = 10;\n"
13521                "  otherThing = 1;\n"
13522                "}",
13523                Alignment);
13524   verifyFormat("void SomeFunction(int parameter = 0) {\n"
13525                "  int i   = 1;\n"
13526                "  int j   = 2;\n"
13527                "  int big = 10000;\n"
13528                "}",
13529                Alignment);
13530   verifyFormat("class C {\n"
13531                "public:\n"
13532                "  int i            = 1;\n"
13533                "  virtual void f() = 0;\n"
13534                "};",
13535                Alignment);
13536   verifyFormat("int i = 1;\n"
13537                "if (SomeType t = getSomething()) {\n"
13538                "}\n"
13539                "int j   = 2;\n"
13540                "int big = 10000;",
13541                Alignment);
13542   verifyFormat("int j = 7;\n"
13543                "for (int k = 0; k < N; ++k) {\n"
13544                "}\n"
13545                "int j   = 2;\n"
13546                "int big = 10000;\n"
13547                "}",
13548                Alignment);
13549   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
13550   verifyFormat("int i = 1;\n"
13551                "LooooooooooongType loooooooooooooooooooooongVariable\n"
13552                "    = someLooooooooooooooooongFunction();\n"
13553                "int j = 2;",
13554                Alignment);
13555   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
13556   verifyFormat("int i = 1;\n"
13557                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
13558                "    someLooooooooooooooooongFunction();\n"
13559                "int j = 2;",
13560                Alignment);
13561 
13562   verifyFormat("auto lambda = []() {\n"
13563                "  auto i = 0;\n"
13564                "  return 0;\n"
13565                "};\n"
13566                "int i  = 0;\n"
13567                "auto v = type{\n"
13568                "    i = 1,   //\n"
13569                "    (i = 2), //\n"
13570                "    i = 3    //\n"
13571                "};",
13572                Alignment);
13573 
13574   verifyFormat(
13575       "int i      = 1;\n"
13576       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
13577       "                          loooooooooooooooooooooongParameterB);\n"
13578       "int j      = 2;",
13579       Alignment);
13580 
13581   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
13582                "          typename B   = very_long_type_name_1,\n"
13583                "          typename T_2 = very_long_type_name_2>\n"
13584                "auto foo() {}\n",
13585                Alignment);
13586   verifyFormat("int a, b = 1;\n"
13587                "int c  = 2;\n"
13588                "int dd = 3;\n",
13589                Alignment);
13590   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
13591                "float b[1][] = {{3.f}};\n",
13592                Alignment);
13593   verifyFormat("for (int i = 0; i < 1; i++)\n"
13594                "  int x = 1;\n",
13595                Alignment);
13596   verifyFormat("for (i = 0; i < 1; i++)\n"
13597                "  x = 1;\n"
13598                "y = 1;\n",
13599                Alignment);
13600 
13601   Alignment.ReflowComments = true;
13602   Alignment.ColumnLimit = 50;
13603   EXPECT_EQ("int x   = 0;\n"
13604             "int yy  = 1; /// specificlennospace\n"
13605             "int zzz = 2;\n",
13606             format("int x   = 0;\n"
13607                    "int yy  = 1; ///specificlennospace\n"
13608                    "int zzz = 2;\n",
13609                    Alignment));
13610 }
13611 
13612 TEST_F(FormatTest, AlignConsecutiveAssignments) {
13613   FormatStyle Alignment = getLLVMStyle();
13614   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13615   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
13616   verifyFormat("int a = 5;\n"
13617                "int oneTwoThree = 123;",
13618                Alignment);
13619   verifyFormat("int a = 5;\n"
13620                "int oneTwoThree = 123;",
13621                Alignment);
13622 
13623   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13624   verifyFormat("int a           = 5;\n"
13625                "int oneTwoThree = 123;",
13626                Alignment);
13627   verifyFormat("int a           = method();\n"
13628                "int oneTwoThree = 133;",
13629                Alignment);
13630   verifyFormat("a &= 5;\n"
13631                "bcd *= 5;\n"
13632                "ghtyf += 5;\n"
13633                "dvfvdb -= 5;\n"
13634                "a /= 5;\n"
13635                "vdsvsv %= 5;\n"
13636                "sfdbddfbdfbb ^= 5;\n"
13637                "dvsdsv |= 5;\n"
13638                "int dsvvdvsdvvv = 123;",
13639                Alignment);
13640   verifyFormat("int i = 1, j = 10;\n"
13641                "something = 2000;",
13642                Alignment);
13643   verifyFormat("something = 2000;\n"
13644                "int i = 1, j = 10;\n",
13645                Alignment);
13646   verifyFormat("something = 2000;\n"
13647                "another   = 911;\n"
13648                "int i = 1, j = 10;\n"
13649                "oneMore = 1;\n"
13650                "i       = 2;",
13651                Alignment);
13652   verifyFormat("int a   = 5;\n"
13653                "int one = 1;\n"
13654                "method();\n"
13655                "int oneTwoThree = 123;\n"
13656                "int oneTwo      = 12;",
13657                Alignment);
13658   verifyFormat("int oneTwoThree = 123;\n"
13659                "int oneTwo      = 12;\n"
13660                "method();\n",
13661                Alignment);
13662   verifyFormat("int oneTwoThree = 123; // comment\n"
13663                "int oneTwo      = 12;  // comment",
13664                Alignment);
13665 
13666   // Bug 25167
13667   /* Uncomment when fixed
13668     verifyFormat("#if A\n"
13669                  "#else\n"
13670                  "int aaaaaaaa = 12;\n"
13671                  "#endif\n"
13672                  "#if B\n"
13673                  "#else\n"
13674                  "int a = 12;\n"
13675                  "#endif\n",
13676                  Alignment);
13677     verifyFormat("enum foo {\n"
13678                  "#if A\n"
13679                  "#else\n"
13680                  "  aaaaaaaa = 12;\n"
13681                  "#endif\n"
13682                  "#if B\n"
13683                  "#else\n"
13684                  "  a = 12;\n"
13685                  "#endif\n"
13686                  "};\n",
13687                  Alignment);
13688   */
13689 
13690   EXPECT_EQ("int a = 5;\n"
13691             "\n"
13692             "int oneTwoThree = 123;",
13693             format("int a       = 5;\n"
13694                    "\n"
13695                    "int oneTwoThree= 123;",
13696                    Alignment));
13697   EXPECT_EQ("int a   = 5;\n"
13698             "int one = 1;\n"
13699             "\n"
13700             "int oneTwoThree = 123;",
13701             format("int a = 5;\n"
13702                    "int one = 1;\n"
13703                    "\n"
13704                    "int oneTwoThree = 123;",
13705                    Alignment));
13706   EXPECT_EQ("int a   = 5;\n"
13707             "int one = 1;\n"
13708             "\n"
13709             "int oneTwoThree = 123;\n"
13710             "int oneTwo      = 12;",
13711             format("int a = 5;\n"
13712                    "int one = 1;\n"
13713                    "\n"
13714                    "int oneTwoThree = 123;\n"
13715                    "int oneTwo = 12;",
13716                    Alignment));
13717   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
13718   verifyFormat("#define A \\\n"
13719                "  int aaaa       = 12; \\\n"
13720                "  int b          = 23; \\\n"
13721                "  int ccc        = 234; \\\n"
13722                "  int dddddddddd = 2345;",
13723                Alignment);
13724   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13725   verifyFormat("#define A               \\\n"
13726                "  int aaaa       = 12;  \\\n"
13727                "  int b          = 23;  \\\n"
13728                "  int ccc        = 234; \\\n"
13729                "  int dddddddddd = 2345;",
13730                Alignment);
13731   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
13732   verifyFormat("#define A                                                      "
13733                "                \\\n"
13734                "  int aaaa       = 12;                                         "
13735                "                \\\n"
13736                "  int b          = 23;                                         "
13737                "                \\\n"
13738                "  int ccc        = 234;                                        "
13739                "                \\\n"
13740                "  int dddddddddd = 2345;",
13741                Alignment);
13742   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
13743                "k = 4, int l = 5,\n"
13744                "                  int m = 6) {\n"
13745                "  int j      = 10;\n"
13746                "  otherThing = 1;\n"
13747                "}",
13748                Alignment);
13749   verifyFormat("void SomeFunction(int parameter = 0) {\n"
13750                "  int i   = 1;\n"
13751                "  int j   = 2;\n"
13752                "  int big = 10000;\n"
13753                "}",
13754                Alignment);
13755   verifyFormat("class C {\n"
13756                "public:\n"
13757                "  int i            = 1;\n"
13758                "  virtual void f() = 0;\n"
13759                "};",
13760                Alignment);
13761   verifyFormat("int i = 1;\n"
13762                "if (SomeType t = getSomething()) {\n"
13763                "}\n"
13764                "int j   = 2;\n"
13765                "int big = 10000;",
13766                Alignment);
13767   verifyFormat("int j = 7;\n"
13768                "for (int k = 0; k < N; ++k) {\n"
13769                "}\n"
13770                "int j   = 2;\n"
13771                "int big = 10000;\n"
13772                "}",
13773                Alignment);
13774   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
13775   verifyFormat("int i = 1;\n"
13776                "LooooooooooongType loooooooooooooooooooooongVariable\n"
13777                "    = someLooooooooooooooooongFunction();\n"
13778                "int j = 2;",
13779                Alignment);
13780   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
13781   verifyFormat("int i = 1;\n"
13782                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
13783                "    someLooooooooooooooooongFunction();\n"
13784                "int j = 2;",
13785                Alignment);
13786 
13787   verifyFormat("auto lambda = []() {\n"
13788                "  auto i = 0;\n"
13789                "  return 0;\n"
13790                "};\n"
13791                "int i  = 0;\n"
13792                "auto v = type{\n"
13793                "    i = 1,   //\n"
13794                "    (i = 2), //\n"
13795                "    i = 3    //\n"
13796                "};",
13797                Alignment);
13798 
13799   verifyFormat(
13800       "int i      = 1;\n"
13801       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
13802       "                          loooooooooooooooooooooongParameterB);\n"
13803       "int j      = 2;",
13804       Alignment);
13805 
13806   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
13807                "          typename B   = very_long_type_name_1,\n"
13808                "          typename T_2 = very_long_type_name_2>\n"
13809                "auto foo() {}\n",
13810                Alignment);
13811   verifyFormat("int a, b = 1;\n"
13812                "int c  = 2;\n"
13813                "int dd = 3;\n",
13814                Alignment);
13815   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
13816                "float b[1][] = {{3.f}};\n",
13817                Alignment);
13818   verifyFormat("for (int i = 0; i < 1; i++)\n"
13819                "  int x = 1;\n",
13820                Alignment);
13821   verifyFormat("for (i = 0; i < 1; i++)\n"
13822                "  x = 1;\n"
13823                "y = 1;\n",
13824                Alignment);
13825 
13826   Alignment.ReflowComments = true;
13827   Alignment.ColumnLimit = 50;
13828   EXPECT_EQ("int x   = 0;\n"
13829             "int yy  = 1; /// specificlennospace\n"
13830             "int zzz = 2;\n",
13831             format("int x   = 0;\n"
13832                    "int yy  = 1; ///specificlennospace\n"
13833                    "int zzz = 2;\n",
13834                    Alignment));
13835 }
13836 
13837 TEST_F(FormatTest, AlignConsecutiveBitFields) {
13838   FormatStyle Alignment = getLLVMStyle();
13839   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
13840   verifyFormat("int const a     : 5;\n"
13841                "int oneTwoThree : 23;",
13842                Alignment);
13843 
13844   // Initializers are allowed starting with c++2a
13845   verifyFormat("int const a     : 5 = 1;\n"
13846                "int oneTwoThree : 23 = 0;",
13847                Alignment);
13848 
13849   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13850   verifyFormat("int const a           : 5;\n"
13851                "int       oneTwoThree : 23;",
13852                Alignment);
13853 
13854   verifyFormat("int const a           : 5;  // comment\n"
13855                "int       oneTwoThree : 23; // comment",
13856                Alignment);
13857 
13858   verifyFormat("int const a           : 5 = 1;\n"
13859                "int       oneTwoThree : 23 = 0;",
13860                Alignment);
13861 
13862   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13863   verifyFormat("int const a           : 5  = 1;\n"
13864                "int       oneTwoThree : 23 = 0;",
13865                Alignment);
13866   verifyFormat("int const a           : 5  = {1};\n"
13867                "int       oneTwoThree : 23 = 0;",
13868                Alignment);
13869 
13870   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
13871   verifyFormat("int const a          :5;\n"
13872                "int       oneTwoThree:23;",
13873                Alignment);
13874 
13875   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
13876   verifyFormat("int const a           :5;\n"
13877                "int       oneTwoThree :23;",
13878                Alignment);
13879 
13880   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
13881   verifyFormat("int const a          : 5;\n"
13882                "int       oneTwoThree: 23;",
13883                Alignment);
13884 
13885   // Known limitations: ':' is only recognized as a bitfield colon when
13886   // followed by a number.
13887   /*
13888   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
13889                "int a           : 5;",
13890                Alignment);
13891   */
13892 }
13893 
13894 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
13895   FormatStyle Alignment = getLLVMStyle();
13896   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13897   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
13898   verifyFormat("float const a = 5;\n"
13899                "int oneTwoThree = 123;",
13900                Alignment);
13901   verifyFormat("int a = 5;\n"
13902                "float const oneTwoThree = 123;",
13903                Alignment);
13904 
13905   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13906   verifyFormat("float const a = 5;\n"
13907                "int         oneTwoThree = 123;",
13908                Alignment);
13909   verifyFormat("int         a = method();\n"
13910                "float const oneTwoThree = 133;",
13911                Alignment);
13912   verifyFormat("int i = 1, j = 10;\n"
13913                "something = 2000;",
13914                Alignment);
13915   verifyFormat("something = 2000;\n"
13916                "int i = 1, j = 10;\n",
13917                Alignment);
13918   verifyFormat("float      something = 2000;\n"
13919                "double     another = 911;\n"
13920                "int        i = 1, j = 10;\n"
13921                "const int *oneMore = 1;\n"
13922                "unsigned   i = 2;",
13923                Alignment);
13924   verifyFormat("float a = 5;\n"
13925                "int   one = 1;\n"
13926                "method();\n"
13927                "const double       oneTwoThree = 123;\n"
13928                "const unsigned int oneTwo = 12;",
13929                Alignment);
13930   verifyFormat("int      oneTwoThree{0}; // comment\n"
13931                "unsigned oneTwo;         // comment",
13932                Alignment);
13933   EXPECT_EQ("float const a = 5;\n"
13934             "\n"
13935             "int oneTwoThree = 123;",
13936             format("float const   a = 5;\n"
13937                    "\n"
13938                    "int           oneTwoThree= 123;",
13939                    Alignment));
13940   EXPECT_EQ("float a = 5;\n"
13941             "int   one = 1;\n"
13942             "\n"
13943             "unsigned oneTwoThree = 123;",
13944             format("float    a = 5;\n"
13945                    "int      one = 1;\n"
13946                    "\n"
13947                    "unsigned oneTwoThree = 123;",
13948                    Alignment));
13949   EXPECT_EQ("float a = 5;\n"
13950             "int   one = 1;\n"
13951             "\n"
13952             "unsigned oneTwoThree = 123;\n"
13953             "int      oneTwo = 12;",
13954             format("float    a = 5;\n"
13955                    "int one = 1;\n"
13956                    "\n"
13957                    "unsigned oneTwoThree = 123;\n"
13958                    "int oneTwo = 12;",
13959                    Alignment));
13960   // Function prototype alignment
13961   verifyFormat("int    a();\n"
13962                "double b();",
13963                Alignment);
13964   verifyFormat("int    a(int x);\n"
13965                "double b();",
13966                Alignment);
13967   unsigned OldColumnLimit = Alignment.ColumnLimit;
13968   // We need to set ColumnLimit to zero, in order to stress nested alignments,
13969   // otherwise the function parameters will be re-flowed onto a single line.
13970   Alignment.ColumnLimit = 0;
13971   EXPECT_EQ("int    a(int   x,\n"
13972             "         float y);\n"
13973             "double b(int    x,\n"
13974             "         double y);",
13975             format("int a(int x,\n"
13976                    " float y);\n"
13977                    "double b(int x,\n"
13978                    " double y);",
13979                    Alignment));
13980   // This ensures that function parameters of function declarations are
13981   // correctly indented when their owning functions are indented.
13982   // The failure case here is for 'double y' to not be indented enough.
13983   EXPECT_EQ("double a(int x);\n"
13984             "int    b(int    y,\n"
13985             "         double z);",
13986             format("double a(int x);\n"
13987                    "int b(int y,\n"
13988                    " double z);",
13989                    Alignment));
13990   // Set ColumnLimit low so that we induce wrapping immediately after
13991   // the function name and opening paren.
13992   Alignment.ColumnLimit = 13;
13993   verifyFormat("int function(\n"
13994                "    int  x,\n"
13995                "    bool y);",
13996                Alignment);
13997   Alignment.ColumnLimit = OldColumnLimit;
13998   // Ensure function pointers don't screw up recursive alignment
13999   verifyFormat("int    a(int x, void (*fp)(int y));\n"
14000                "double b();",
14001                Alignment);
14002   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14003   // Ensure recursive alignment is broken by function braces, so that the
14004   // "a = 1" does not align with subsequent assignments inside the function
14005   // body.
14006   verifyFormat("int func(int a = 1) {\n"
14007                "  int b  = 2;\n"
14008                "  int cc = 3;\n"
14009                "}",
14010                Alignment);
14011   verifyFormat("float      something = 2000;\n"
14012                "double     another   = 911;\n"
14013                "int        i = 1, j = 10;\n"
14014                "const int *oneMore = 1;\n"
14015                "unsigned   i       = 2;",
14016                Alignment);
14017   verifyFormat("int      oneTwoThree = {0}; // comment\n"
14018                "unsigned oneTwo      = 0;   // comment",
14019                Alignment);
14020   // Make sure that scope is correctly tracked, in the absence of braces
14021   verifyFormat("for (int i = 0; i < n; i++)\n"
14022                "  j = i;\n"
14023                "double x = 1;\n",
14024                Alignment);
14025   verifyFormat("if (int i = 0)\n"
14026                "  j = i;\n"
14027                "double x = 1;\n",
14028                Alignment);
14029   // Ensure operator[] and operator() are comprehended
14030   verifyFormat("struct test {\n"
14031                "  long long int foo();\n"
14032                "  int           operator[](int a);\n"
14033                "  double        bar();\n"
14034                "};\n",
14035                Alignment);
14036   verifyFormat("struct test {\n"
14037                "  long long int foo();\n"
14038                "  int           operator()(int a);\n"
14039                "  double        bar();\n"
14040                "};\n",
14041                Alignment);
14042   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
14043             "  int const i   = 1;\n"
14044             "  int *     j   = 2;\n"
14045             "  int       big = 10000;\n"
14046             "\n"
14047             "  unsigned oneTwoThree = 123;\n"
14048             "  int      oneTwo      = 12;\n"
14049             "  method();\n"
14050             "  float k  = 2;\n"
14051             "  int   ll = 10000;\n"
14052             "}",
14053             format("void SomeFunction(int parameter= 0) {\n"
14054                    " int const  i= 1;\n"
14055                    "  int *j=2;\n"
14056                    " int big  =  10000;\n"
14057                    "\n"
14058                    "unsigned oneTwoThree  =123;\n"
14059                    "int oneTwo = 12;\n"
14060                    "  method();\n"
14061                    "float k= 2;\n"
14062                    "int ll=10000;\n"
14063                    "}",
14064                    Alignment));
14065   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14066   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
14067   verifyFormat("#define A \\\n"
14068                "  int       aaaa = 12; \\\n"
14069                "  float     b = 23; \\\n"
14070                "  const int ccc = 234; \\\n"
14071                "  unsigned  dddddddddd = 2345;",
14072                Alignment);
14073   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14074   verifyFormat("#define A              \\\n"
14075                "  int       aaaa = 12; \\\n"
14076                "  float     b = 23;    \\\n"
14077                "  const int ccc = 234; \\\n"
14078                "  unsigned  dddddddddd = 2345;",
14079                Alignment);
14080   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
14081   Alignment.ColumnLimit = 30;
14082   verifyFormat("#define A                    \\\n"
14083                "  int       aaaa = 12;       \\\n"
14084                "  float     b = 23;          \\\n"
14085                "  const int ccc = 234;       \\\n"
14086                "  int       dddddddddd = 2345;",
14087                Alignment);
14088   Alignment.ColumnLimit = 80;
14089   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
14090                "k = 4, int l = 5,\n"
14091                "                  int m = 6) {\n"
14092                "  const int j = 10;\n"
14093                "  otherThing = 1;\n"
14094                "}",
14095                Alignment);
14096   verifyFormat("void SomeFunction(int parameter = 0) {\n"
14097                "  int const i = 1;\n"
14098                "  int *     j = 2;\n"
14099                "  int       big = 10000;\n"
14100                "}",
14101                Alignment);
14102   verifyFormat("class C {\n"
14103                "public:\n"
14104                "  int          i = 1;\n"
14105                "  virtual void f() = 0;\n"
14106                "};",
14107                Alignment);
14108   verifyFormat("float i = 1;\n"
14109                "if (SomeType t = getSomething()) {\n"
14110                "}\n"
14111                "const unsigned j = 2;\n"
14112                "int            big = 10000;",
14113                Alignment);
14114   verifyFormat("float j = 7;\n"
14115                "for (int k = 0; k < N; ++k) {\n"
14116                "}\n"
14117                "unsigned j = 2;\n"
14118                "int      big = 10000;\n"
14119                "}",
14120                Alignment);
14121   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14122   verifyFormat("float              i = 1;\n"
14123                "LooooooooooongType loooooooooooooooooooooongVariable\n"
14124                "    = someLooooooooooooooooongFunction();\n"
14125                "int j = 2;",
14126                Alignment);
14127   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
14128   verifyFormat("int                i = 1;\n"
14129                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
14130                "    someLooooooooooooooooongFunction();\n"
14131                "int j = 2;",
14132                Alignment);
14133 
14134   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14135   verifyFormat("auto lambda = []() {\n"
14136                "  auto  ii = 0;\n"
14137                "  float j  = 0;\n"
14138                "  return 0;\n"
14139                "};\n"
14140                "int   i  = 0;\n"
14141                "float i2 = 0;\n"
14142                "auto  v  = type{\n"
14143                "    i = 1,   //\n"
14144                "    (i = 2), //\n"
14145                "    i = 3    //\n"
14146                "};",
14147                Alignment);
14148   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14149 
14150   verifyFormat(
14151       "int      i = 1;\n"
14152       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
14153       "                          loooooooooooooooooooooongParameterB);\n"
14154       "int      j = 2;",
14155       Alignment);
14156 
14157   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
14158   // We expect declarations and assignments to align, as long as it doesn't
14159   // exceed the column limit, starting a new alignment sequence whenever it
14160   // happens.
14161   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14162   Alignment.ColumnLimit = 30;
14163   verifyFormat("float    ii              = 1;\n"
14164                "unsigned j               = 2;\n"
14165                "int someVerylongVariable = 1;\n"
14166                "AnotherLongType  ll = 123456;\n"
14167                "VeryVeryLongType k  = 2;\n"
14168                "int              myvar = 1;",
14169                Alignment);
14170   Alignment.ColumnLimit = 80;
14171   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14172 
14173   verifyFormat(
14174       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
14175       "          typename LongType, typename B>\n"
14176       "auto foo() {}\n",
14177       Alignment);
14178   verifyFormat("float a, b = 1;\n"
14179                "int   c = 2;\n"
14180                "int   dd = 3;\n",
14181                Alignment);
14182   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
14183                "float b[1][] = {{3.f}};\n",
14184                Alignment);
14185   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14186   verifyFormat("float a, b = 1;\n"
14187                "int   c  = 2;\n"
14188                "int   dd = 3;\n",
14189                Alignment);
14190   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
14191                "float b[1][] = {{3.f}};\n",
14192                Alignment);
14193   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14194 
14195   Alignment.ColumnLimit = 30;
14196   Alignment.BinPackParameters = false;
14197   verifyFormat("void foo(float     a,\n"
14198                "         float     b,\n"
14199                "         int       c,\n"
14200                "         uint32_t *d) {\n"
14201                "  int *  e = 0;\n"
14202                "  float  f = 0;\n"
14203                "  double g = 0;\n"
14204                "}\n"
14205                "void bar(ino_t     a,\n"
14206                "         int       b,\n"
14207                "         uint32_t *c,\n"
14208                "         bool      d) {}\n",
14209                Alignment);
14210   Alignment.BinPackParameters = true;
14211   Alignment.ColumnLimit = 80;
14212 
14213   // Bug 33507
14214   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
14215   verifyFormat(
14216       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
14217       "  static const Version verVs2017;\n"
14218       "  return true;\n"
14219       "});\n",
14220       Alignment);
14221   Alignment.PointerAlignment = FormatStyle::PAS_Right;
14222 
14223   // See llvm.org/PR35641
14224   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14225   verifyFormat("int func() { //\n"
14226                "  int      b;\n"
14227                "  unsigned c;\n"
14228                "}",
14229                Alignment);
14230 
14231   // See PR37175
14232   FormatStyle Style = getMozillaStyle();
14233   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14234   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
14235             "foo(int a);",
14236             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
14237 }
14238 
14239 TEST_F(FormatTest, LinuxBraceBreaking) {
14240   FormatStyle LinuxBraceStyle = getLLVMStyle();
14241   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
14242   verifyFormat("namespace a\n"
14243                "{\n"
14244                "class A\n"
14245                "{\n"
14246                "  void f()\n"
14247                "  {\n"
14248                "    if (true) {\n"
14249                "      a();\n"
14250                "      b();\n"
14251                "    } else {\n"
14252                "      a();\n"
14253                "    }\n"
14254                "  }\n"
14255                "  void g() { return; }\n"
14256                "};\n"
14257                "struct B {\n"
14258                "  int x;\n"
14259                "};\n"
14260                "} // namespace a\n",
14261                LinuxBraceStyle);
14262   verifyFormat("enum X {\n"
14263                "  Y = 0,\n"
14264                "}\n",
14265                LinuxBraceStyle);
14266   verifyFormat("struct S {\n"
14267                "  int Type;\n"
14268                "  union {\n"
14269                "    int x;\n"
14270                "    double y;\n"
14271                "  } Value;\n"
14272                "  class C\n"
14273                "  {\n"
14274                "    MyFavoriteType Value;\n"
14275                "  } Class;\n"
14276                "}\n",
14277                LinuxBraceStyle);
14278 }
14279 
14280 TEST_F(FormatTest, MozillaBraceBreaking) {
14281   FormatStyle MozillaBraceStyle = getLLVMStyle();
14282   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
14283   MozillaBraceStyle.FixNamespaceComments = false;
14284   verifyFormat("namespace a {\n"
14285                "class A\n"
14286                "{\n"
14287                "  void f()\n"
14288                "  {\n"
14289                "    if (true) {\n"
14290                "      a();\n"
14291                "      b();\n"
14292                "    }\n"
14293                "  }\n"
14294                "  void g() { return; }\n"
14295                "};\n"
14296                "enum E\n"
14297                "{\n"
14298                "  A,\n"
14299                "  // foo\n"
14300                "  B,\n"
14301                "  C\n"
14302                "};\n"
14303                "struct B\n"
14304                "{\n"
14305                "  int x;\n"
14306                "};\n"
14307                "}\n",
14308                MozillaBraceStyle);
14309   verifyFormat("struct S\n"
14310                "{\n"
14311                "  int Type;\n"
14312                "  union\n"
14313                "  {\n"
14314                "    int x;\n"
14315                "    double y;\n"
14316                "  } Value;\n"
14317                "  class C\n"
14318                "  {\n"
14319                "    MyFavoriteType Value;\n"
14320                "  } Class;\n"
14321                "}\n",
14322                MozillaBraceStyle);
14323 }
14324 
14325 TEST_F(FormatTest, StroustrupBraceBreaking) {
14326   FormatStyle StroustrupBraceStyle = getLLVMStyle();
14327   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
14328   verifyFormat("namespace a {\n"
14329                "class A {\n"
14330                "  void f()\n"
14331                "  {\n"
14332                "    if (true) {\n"
14333                "      a();\n"
14334                "      b();\n"
14335                "    }\n"
14336                "  }\n"
14337                "  void g() { return; }\n"
14338                "};\n"
14339                "struct B {\n"
14340                "  int x;\n"
14341                "};\n"
14342                "} // namespace a\n",
14343                StroustrupBraceStyle);
14344 
14345   verifyFormat("void foo()\n"
14346                "{\n"
14347                "  if (a) {\n"
14348                "    a();\n"
14349                "  }\n"
14350                "  else {\n"
14351                "    b();\n"
14352                "  }\n"
14353                "}\n",
14354                StroustrupBraceStyle);
14355 
14356   verifyFormat("#ifdef _DEBUG\n"
14357                "int foo(int i = 0)\n"
14358                "#else\n"
14359                "int foo(int i = 5)\n"
14360                "#endif\n"
14361                "{\n"
14362                "  return i;\n"
14363                "}",
14364                StroustrupBraceStyle);
14365 
14366   verifyFormat("void foo() {}\n"
14367                "void bar()\n"
14368                "#ifdef _DEBUG\n"
14369                "{\n"
14370                "  foo();\n"
14371                "}\n"
14372                "#else\n"
14373                "{\n"
14374                "}\n"
14375                "#endif",
14376                StroustrupBraceStyle);
14377 
14378   verifyFormat("void foobar() { int i = 5; }\n"
14379                "#ifdef _DEBUG\n"
14380                "void bar() {}\n"
14381                "#else\n"
14382                "void bar() { foobar(); }\n"
14383                "#endif",
14384                StroustrupBraceStyle);
14385 }
14386 
14387 TEST_F(FormatTest, AllmanBraceBreaking) {
14388   FormatStyle AllmanBraceStyle = getLLVMStyle();
14389   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
14390 
14391   EXPECT_EQ("namespace a\n"
14392             "{\n"
14393             "void f();\n"
14394             "void g();\n"
14395             "} // namespace a\n",
14396             format("namespace a\n"
14397                    "{\n"
14398                    "void f();\n"
14399                    "void g();\n"
14400                    "}\n",
14401                    AllmanBraceStyle));
14402 
14403   verifyFormat("namespace a\n"
14404                "{\n"
14405                "class A\n"
14406                "{\n"
14407                "  void f()\n"
14408                "  {\n"
14409                "    if (true)\n"
14410                "    {\n"
14411                "      a();\n"
14412                "      b();\n"
14413                "    }\n"
14414                "  }\n"
14415                "  void g() { return; }\n"
14416                "};\n"
14417                "struct B\n"
14418                "{\n"
14419                "  int x;\n"
14420                "};\n"
14421                "union C\n"
14422                "{\n"
14423                "};\n"
14424                "} // namespace a",
14425                AllmanBraceStyle);
14426 
14427   verifyFormat("void f()\n"
14428                "{\n"
14429                "  if (true)\n"
14430                "  {\n"
14431                "    a();\n"
14432                "  }\n"
14433                "  else if (false)\n"
14434                "  {\n"
14435                "    b();\n"
14436                "  }\n"
14437                "  else\n"
14438                "  {\n"
14439                "    c();\n"
14440                "  }\n"
14441                "}\n",
14442                AllmanBraceStyle);
14443 
14444   verifyFormat("void f()\n"
14445                "{\n"
14446                "  for (int i = 0; i < 10; ++i)\n"
14447                "  {\n"
14448                "    a();\n"
14449                "  }\n"
14450                "  while (false)\n"
14451                "  {\n"
14452                "    b();\n"
14453                "  }\n"
14454                "  do\n"
14455                "  {\n"
14456                "    c();\n"
14457                "  } while (false)\n"
14458                "}\n",
14459                AllmanBraceStyle);
14460 
14461   verifyFormat("void f(int a)\n"
14462                "{\n"
14463                "  switch (a)\n"
14464                "  {\n"
14465                "  case 0:\n"
14466                "    break;\n"
14467                "  case 1:\n"
14468                "  {\n"
14469                "    break;\n"
14470                "  }\n"
14471                "  case 2:\n"
14472                "  {\n"
14473                "  }\n"
14474                "  break;\n"
14475                "  default:\n"
14476                "    break;\n"
14477                "  }\n"
14478                "}\n",
14479                AllmanBraceStyle);
14480 
14481   verifyFormat("enum X\n"
14482                "{\n"
14483                "  Y = 0,\n"
14484                "}\n",
14485                AllmanBraceStyle);
14486   verifyFormat("enum X\n"
14487                "{\n"
14488                "  Y = 0\n"
14489                "}\n",
14490                AllmanBraceStyle);
14491 
14492   verifyFormat("@interface BSApplicationController ()\n"
14493                "{\n"
14494                "@private\n"
14495                "  id _extraIvar;\n"
14496                "}\n"
14497                "@end\n",
14498                AllmanBraceStyle);
14499 
14500   verifyFormat("#ifdef _DEBUG\n"
14501                "int foo(int i = 0)\n"
14502                "#else\n"
14503                "int foo(int i = 5)\n"
14504                "#endif\n"
14505                "{\n"
14506                "  return i;\n"
14507                "}",
14508                AllmanBraceStyle);
14509 
14510   verifyFormat("void foo() {}\n"
14511                "void bar()\n"
14512                "#ifdef _DEBUG\n"
14513                "{\n"
14514                "  foo();\n"
14515                "}\n"
14516                "#else\n"
14517                "{\n"
14518                "}\n"
14519                "#endif",
14520                AllmanBraceStyle);
14521 
14522   verifyFormat("void foobar() { int i = 5; }\n"
14523                "#ifdef _DEBUG\n"
14524                "void bar() {}\n"
14525                "#else\n"
14526                "void bar() { foobar(); }\n"
14527                "#endif",
14528                AllmanBraceStyle);
14529 
14530   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
14531             FormatStyle::SLS_All);
14532 
14533   verifyFormat("[](int i) { return i + 2; };\n"
14534                "[](int i, int j)\n"
14535                "{\n"
14536                "  auto x = i + j;\n"
14537                "  auto y = i * j;\n"
14538                "  return x ^ y;\n"
14539                "};\n"
14540                "void foo()\n"
14541                "{\n"
14542                "  auto shortLambda = [](int i) { return i + 2; };\n"
14543                "  auto longLambda = [](int i, int j)\n"
14544                "  {\n"
14545                "    auto x = i + j;\n"
14546                "    auto y = i * j;\n"
14547                "    return x ^ y;\n"
14548                "  };\n"
14549                "}",
14550                AllmanBraceStyle);
14551 
14552   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
14553 
14554   verifyFormat("[](int i)\n"
14555                "{\n"
14556                "  return i + 2;\n"
14557                "};\n"
14558                "[](int i, int j)\n"
14559                "{\n"
14560                "  auto x = i + j;\n"
14561                "  auto y = i * j;\n"
14562                "  return x ^ y;\n"
14563                "};\n"
14564                "void foo()\n"
14565                "{\n"
14566                "  auto shortLambda = [](int i)\n"
14567                "  {\n"
14568                "    return i + 2;\n"
14569                "  };\n"
14570                "  auto longLambda = [](int i, int j)\n"
14571                "  {\n"
14572                "    auto x = i + j;\n"
14573                "    auto y = i * j;\n"
14574                "    return x ^ y;\n"
14575                "  };\n"
14576                "}",
14577                AllmanBraceStyle);
14578 
14579   // Reset
14580   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
14581 
14582   // This shouldn't affect ObjC blocks..
14583   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
14584                "  // ...\n"
14585                "  int i;\n"
14586                "}];",
14587                AllmanBraceStyle);
14588   verifyFormat("void (^block)(void) = ^{\n"
14589                "  // ...\n"
14590                "  int i;\n"
14591                "};",
14592                AllmanBraceStyle);
14593   // .. or dict literals.
14594   verifyFormat("void f()\n"
14595                "{\n"
14596                "  // ...\n"
14597                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
14598                "}",
14599                AllmanBraceStyle);
14600   verifyFormat("void f()\n"
14601                "{\n"
14602                "  // ...\n"
14603                "  [object someMethod:@{a : @\"b\"}];\n"
14604                "}",
14605                AllmanBraceStyle);
14606   verifyFormat("int f()\n"
14607                "{ // comment\n"
14608                "  return 42;\n"
14609                "}",
14610                AllmanBraceStyle);
14611 
14612   AllmanBraceStyle.ColumnLimit = 19;
14613   verifyFormat("void f() { int i; }", AllmanBraceStyle);
14614   AllmanBraceStyle.ColumnLimit = 18;
14615   verifyFormat("void f()\n"
14616                "{\n"
14617                "  int i;\n"
14618                "}",
14619                AllmanBraceStyle);
14620   AllmanBraceStyle.ColumnLimit = 80;
14621 
14622   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
14623   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
14624       FormatStyle::SIS_WithoutElse;
14625   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
14626   verifyFormat("void f(bool b)\n"
14627                "{\n"
14628                "  if (b)\n"
14629                "  {\n"
14630                "    return;\n"
14631                "  }\n"
14632                "}\n",
14633                BreakBeforeBraceShortIfs);
14634   verifyFormat("void f(bool b)\n"
14635                "{\n"
14636                "  if constexpr (b)\n"
14637                "  {\n"
14638                "    return;\n"
14639                "  }\n"
14640                "}\n",
14641                BreakBeforeBraceShortIfs);
14642   verifyFormat("void f(bool b)\n"
14643                "{\n"
14644                "  if CONSTEXPR (b)\n"
14645                "  {\n"
14646                "    return;\n"
14647                "  }\n"
14648                "}\n",
14649                BreakBeforeBraceShortIfs);
14650   verifyFormat("void f(bool b)\n"
14651                "{\n"
14652                "  if (b) return;\n"
14653                "}\n",
14654                BreakBeforeBraceShortIfs);
14655   verifyFormat("void f(bool b)\n"
14656                "{\n"
14657                "  if constexpr (b) return;\n"
14658                "}\n",
14659                BreakBeforeBraceShortIfs);
14660   verifyFormat("void f(bool b)\n"
14661                "{\n"
14662                "  if CONSTEXPR (b) return;\n"
14663                "}\n",
14664                BreakBeforeBraceShortIfs);
14665   verifyFormat("void f(bool b)\n"
14666                "{\n"
14667                "  while (b)\n"
14668                "  {\n"
14669                "    return;\n"
14670                "  }\n"
14671                "}\n",
14672                BreakBeforeBraceShortIfs);
14673 }
14674 
14675 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
14676   FormatStyle WhitesmithsBraceStyle = getLLVMStyle();
14677   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
14678 
14679   // Make a few changes to the style for testing purposes
14680   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
14681       FormatStyle::SFS_Empty;
14682   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
14683   WhitesmithsBraceStyle.ColumnLimit = 0;
14684 
14685   // FIXME: this test case can't decide whether there should be a blank line
14686   // after the ~D() line or not. It adds one if one doesn't exist in the test
14687   // and it removes the line if one exists.
14688   /*
14689   verifyFormat("class A;\n"
14690                "namespace B\n"
14691                "  {\n"
14692                "class C;\n"
14693                "// Comment\n"
14694                "class D\n"
14695                "  {\n"
14696                "public:\n"
14697                "  D();\n"
14698                "  ~D() {}\n"
14699                "private:\n"
14700                "  enum E\n"
14701                "    {\n"
14702                "    F\n"
14703                "    }\n"
14704                "  };\n"
14705                "  } // namespace B\n",
14706                WhitesmithsBraceStyle);
14707   */
14708 
14709   verifyFormat("namespace a\n"
14710                "  {\n"
14711                "class A\n"
14712                "  {\n"
14713                "  void f()\n"
14714                "    {\n"
14715                "    if (true)\n"
14716                "      {\n"
14717                "      a();\n"
14718                "      b();\n"
14719                "      }\n"
14720                "    }\n"
14721                "  void g()\n"
14722                "    {\n"
14723                "    return;\n"
14724                "    }\n"
14725                "  };\n"
14726                "struct B\n"
14727                "  {\n"
14728                "  int x;\n"
14729                "  };\n"
14730                "  } // namespace a",
14731                WhitesmithsBraceStyle);
14732 
14733   verifyFormat("void f()\n"
14734                "  {\n"
14735                "  if (true)\n"
14736                "    {\n"
14737                "    a();\n"
14738                "    }\n"
14739                "  else if (false)\n"
14740                "    {\n"
14741                "    b();\n"
14742                "    }\n"
14743                "  else\n"
14744                "    {\n"
14745                "    c();\n"
14746                "    }\n"
14747                "  }\n",
14748                WhitesmithsBraceStyle);
14749 
14750   verifyFormat("void f()\n"
14751                "  {\n"
14752                "  for (int i = 0; i < 10; ++i)\n"
14753                "    {\n"
14754                "    a();\n"
14755                "    }\n"
14756                "  while (false)\n"
14757                "    {\n"
14758                "    b();\n"
14759                "    }\n"
14760                "  do\n"
14761                "    {\n"
14762                "    c();\n"
14763                "    } while (false)\n"
14764                "  }\n",
14765                WhitesmithsBraceStyle);
14766 
14767   WhitesmithsBraceStyle.IndentCaseBlocks = true;
14768   verifyFormat("void switchTest1(int a)\n"
14769                "  {\n"
14770                "  switch (a)\n"
14771                "    {\n"
14772                "    case 2:\n"
14773                "      {\n"
14774                "      }\n"
14775                "    break;\n"
14776                "    }\n"
14777                "  }\n",
14778                WhitesmithsBraceStyle);
14779 
14780   verifyFormat("void switchTest2(int a)\n"
14781                "  {\n"
14782                "  switch (a)\n"
14783                "    {\n"
14784                "    case 0:\n"
14785                "    break;\n"
14786                "    case 1:\n"
14787                "      {\n"
14788                "      break;\n"
14789                "      }\n"
14790                "    case 2:\n"
14791                "      {\n"
14792                "      }\n"
14793                "    break;\n"
14794                "    default:\n"
14795                "    break;\n"
14796                "    }\n"
14797                "  }\n",
14798                WhitesmithsBraceStyle);
14799 
14800   verifyFormat("void switchTest3(int a)\n"
14801                "  {\n"
14802                "  switch (a)\n"
14803                "    {\n"
14804                "    case 0:\n"
14805                "      {\n"
14806                "      foo(x);\n"
14807                "      }\n"
14808                "    break;\n"
14809                "    default:\n"
14810                "      {\n"
14811                "      foo(1);\n"
14812                "      }\n"
14813                "    break;\n"
14814                "    }\n"
14815                "  }\n",
14816                WhitesmithsBraceStyle);
14817 
14818   WhitesmithsBraceStyle.IndentCaseBlocks = false;
14819 
14820   verifyFormat("void switchTest4(int a)\n"
14821                "  {\n"
14822                "  switch (a)\n"
14823                "    {\n"
14824                "  case 2:\n"
14825                "    {\n"
14826                "    }\n"
14827                "    break;\n"
14828                "    }\n"
14829                "  }\n",
14830                WhitesmithsBraceStyle);
14831 
14832   verifyFormat("void switchTest5(int a)\n"
14833                "  {\n"
14834                "  switch (a)\n"
14835                "    {\n"
14836                "  case 0:\n"
14837                "    break;\n"
14838                "  case 1:\n"
14839                "    {\n"
14840                "    foo();\n"
14841                "    break;\n"
14842                "    }\n"
14843                "  case 2:\n"
14844                "    {\n"
14845                "    }\n"
14846                "    break;\n"
14847                "  default:\n"
14848                "    break;\n"
14849                "    }\n"
14850                "  }\n",
14851                WhitesmithsBraceStyle);
14852 
14853   verifyFormat("void switchTest6(int a)\n"
14854                "  {\n"
14855                "  switch (a)\n"
14856                "    {\n"
14857                "  case 0:\n"
14858                "    {\n"
14859                "    foo(x);\n"
14860                "    }\n"
14861                "    break;\n"
14862                "  default:\n"
14863                "    {\n"
14864                "    foo(1);\n"
14865                "    }\n"
14866                "    break;\n"
14867                "    }\n"
14868                "  }\n",
14869                WhitesmithsBraceStyle);
14870 
14871   verifyFormat("enum X\n"
14872                "  {\n"
14873                "  Y = 0, // testing\n"
14874                "  }\n",
14875                WhitesmithsBraceStyle);
14876 
14877   verifyFormat("enum X\n"
14878                "  {\n"
14879                "  Y = 0\n"
14880                "  }\n",
14881                WhitesmithsBraceStyle);
14882   verifyFormat("enum X\n"
14883                "  {\n"
14884                "  Y = 0,\n"
14885                "  Z = 1\n"
14886                "  };\n",
14887                WhitesmithsBraceStyle);
14888 
14889   verifyFormat("@interface BSApplicationController ()\n"
14890                "  {\n"
14891                "@private\n"
14892                "  id _extraIvar;\n"
14893                "  }\n"
14894                "@end\n",
14895                WhitesmithsBraceStyle);
14896 
14897   verifyFormat("#ifdef _DEBUG\n"
14898                "int foo(int i = 0)\n"
14899                "#else\n"
14900                "int foo(int i = 5)\n"
14901                "#endif\n"
14902                "  {\n"
14903                "  return i;\n"
14904                "  }",
14905                WhitesmithsBraceStyle);
14906 
14907   verifyFormat("void foo() {}\n"
14908                "void bar()\n"
14909                "#ifdef _DEBUG\n"
14910                "  {\n"
14911                "  foo();\n"
14912                "  }\n"
14913                "#else\n"
14914                "  {\n"
14915                "  }\n"
14916                "#endif",
14917                WhitesmithsBraceStyle);
14918 
14919   verifyFormat("void foobar()\n"
14920                "  {\n"
14921                "  int i = 5;\n"
14922                "  }\n"
14923                "#ifdef _DEBUG\n"
14924                "void bar()\n"
14925                "  {\n"
14926                "  }\n"
14927                "#else\n"
14928                "void bar()\n"
14929                "  {\n"
14930                "  foobar();\n"
14931                "  }\n"
14932                "#endif",
14933                WhitesmithsBraceStyle);
14934 
14935   // This shouldn't affect ObjC blocks..
14936   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
14937                "  // ...\n"
14938                "  int i;\n"
14939                "}];",
14940                WhitesmithsBraceStyle);
14941   verifyFormat("void (^block)(void) = ^{\n"
14942                "  // ...\n"
14943                "  int i;\n"
14944                "};",
14945                WhitesmithsBraceStyle);
14946   // .. or dict literals.
14947   verifyFormat("void f()\n"
14948                "  {\n"
14949                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
14950                "  }",
14951                WhitesmithsBraceStyle);
14952 
14953   verifyFormat("int f()\n"
14954                "  { // comment\n"
14955                "  return 42;\n"
14956                "  }",
14957                WhitesmithsBraceStyle);
14958 
14959   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
14960   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
14961       FormatStyle::SIS_Always;
14962   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
14963   verifyFormat("void f(bool b)\n"
14964                "  {\n"
14965                "  if (b)\n"
14966                "    {\n"
14967                "    return;\n"
14968                "    }\n"
14969                "  }\n",
14970                BreakBeforeBraceShortIfs);
14971   verifyFormat("void f(bool b)\n"
14972                "  {\n"
14973                "  if (b) return;\n"
14974                "  }\n",
14975                BreakBeforeBraceShortIfs);
14976   verifyFormat("void f(bool b)\n"
14977                "  {\n"
14978                "  while (b)\n"
14979                "    {\n"
14980                "    return;\n"
14981                "    }\n"
14982                "  }\n",
14983                BreakBeforeBraceShortIfs);
14984 }
14985 
14986 TEST_F(FormatTest, GNUBraceBreaking) {
14987   FormatStyle GNUBraceStyle = getLLVMStyle();
14988   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
14989   verifyFormat("namespace a\n"
14990                "{\n"
14991                "class A\n"
14992                "{\n"
14993                "  void f()\n"
14994                "  {\n"
14995                "    int a;\n"
14996                "    {\n"
14997                "      int b;\n"
14998                "    }\n"
14999                "    if (true)\n"
15000                "      {\n"
15001                "        a();\n"
15002                "        b();\n"
15003                "      }\n"
15004                "  }\n"
15005                "  void g() { return; }\n"
15006                "}\n"
15007                "} // namespace a",
15008                GNUBraceStyle);
15009 
15010   verifyFormat("void f()\n"
15011                "{\n"
15012                "  if (true)\n"
15013                "    {\n"
15014                "      a();\n"
15015                "    }\n"
15016                "  else if (false)\n"
15017                "    {\n"
15018                "      b();\n"
15019                "    }\n"
15020                "  else\n"
15021                "    {\n"
15022                "      c();\n"
15023                "    }\n"
15024                "}\n",
15025                GNUBraceStyle);
15026 
15027   verifyFormat("void f()\n"
15028                "{\n"
15029                "  for (int i = 0; i < 10; ++i)\n"
15030                "    {\n"
15031                "      a();\n"
15032                "    }\n"
15033                "  while (false)\n"
15034                "    {\n"
15035                "      b();\n"
15036                "    }\n"
15037                "  do\n"
15038                "    {\n"
15039                "      c();\n"
15040                "    }\n"
15041                "  while (false);\n"
15042                "}\n",
15043                GNUBraceStyle);
15044 
15045   verifyFormat("void f(int a)\n"
15046                "{\n"
15047                "  switch (a)\n"
15048                "    {\n"
15049                "    case 0:\n"
15050                "      break;\n"
15051                "    case 1:\n"
15052                "      {\n"
15053                "        break;\n"
15054                "      }\n"
15055                "    case 2:\n"
15056                "      {\n"
15057                "      }\n"
15058                "      break;\n"
15059                "    default:\n"
15060                "      break;\n"
15061                "    }\n"
15062                "}\n",
15063                GNUBraceStyle);
15064 
15065   verifyFormat("enum X\n"
15066                "{\n"
15067                "  Y = 0,\n"
15068                "}\n",
15069                GNUBraceStyle);
15070 
15071   verifyFormat("@interface BSApplicationController ()\n"
15072                "{\n"
15073                "@private\n"
15074                "  id _extraIvar;\n"
15075                "}\n"
15076                "@end\n",
15077                GNUBraceStyle);
15078 
15079   verifyFormat("#ifdef _DEBUG\n"
15080                "int foo(int i = 0)\n"
15081                "#else\n"
15082                "int foo(int i = 5)\n"
15083                "#endif\n"
15084                "{\n"
15085                "  return i;\n"
15086                "}",
15087                GNUBraceStyle);
15088 
15089   verifyFormat("void foo() {}\n"
15090                "void bar()\n"
15091                "#ifdef _DEBUG\n"
15092                "{\n"
15093                "  foo();\n"
15094                "}\n"
15095                "#else\n"
15096                "{\n"
15097                "}\n"
15098                "#endif",
15099                GNUBraceStyle);
15100 
15101   verifyFormat("void foobar() { int i = 5; }\n"
15102                "#ifdef _DEBUG\n"
15103                "void bar() {}\n"
15104                "#else\n"
15105                "void bar() { foobar(); }\n"
15106                "#endif",
15107                GNUBraceStyle);
15108 }
15109 
15110 TEST_F(FormatTest, WebKitBraceBreaking) {
15111   FormatStyle WebKitBraceStyle = getLLVMStyle();
15112   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
15113   WebKitBraceStyle.FixNamespaceComments = false;
15114   verifyFormat("namespace a {\n"
15115                "class A {\n"
15116                "  void f()\n"
15117                "  {\n"
15118                "    if (true) {\n"
15119                "      a();\n"
15120                "      b();\n"
15121                "    }\n"
15122                "  }\n"
15123                "  void g() { return; }\n"
15124                "};\n"
15125                "enum E {\n"
15126                "  A,\n"
15127                "  // foo\n"
15128                "  B,\n"
15129                "  C\n"
15130                "};\n"
15131                "struct B {\n"
15132                "  int x;\n"
15133                "};\n"
15134                "}\n",
15135                WebKitBraceStyle);
15136   verifyFormat("struct S {\n"
15137                "  int Type;\n"
15138                "  union {\n"
15139                "    int x;\n"
15140                "    double y;\n"
15141                "  } Value;\n"
15142                "  class C {\n"
15143                "    MyFavoriteType Value;\n"
15144                "  } Class;\n"
15145                "};\n",
15146                WebKitBraceStyle);
15147 }
15148 
15149 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
15150   verifyFormat("void f() {\n"
15151                "  try {\n"
15152                "  } catch (const Exception &e) {\n"
15153                "  }\n"
15154                "}\n",
15155                getLLVMStyle());
15156 }
15157 
15158 TEST_F(FormatTest, UnderstandsPragmas) {
15159   verifyFormat("#pragma omp reduction(| : var)");
15160   verifyFormat("#pragma omp reduction(+ : var)");
15161 
15162   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
15163             "(including parentheses).",
15164             format("#pragma    mark   Any non-hyphenated or hyphenated string "
15165                    "(including parentheses)."));
15166 }
15167 
15168 TEST_F(FormatTest, UnderstandPragmaOption) {
15169   verifyFormat("#pragma option -C -A");
15170 
15171   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
15172 }
15173 
15174 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
15175   FormatStyle Style = getLLVMStyle();
15176   Style.ColumnLimit = 20;
15177 
15178   // See PR41213
15179   EXPECT_EQ("/*\n"
15180             " *\t9012345\n"
15181             " * /8901\n"
15182             " */",
15183             format("/*\n"
15184                    " *\t9012345 /8901\n"
15185                    " */",
15186                    Style));
15187   EXPECT_EQ("/*\n"
15188             " *345678\n"
15189             " *\t/8901\n"
15190             " */",
15191             format("/*\n"
15192                    " *345678\t/8901\n"
15193                    " */",
15194                    Style));
15195 
15196   verifyFormat("int a; // the\n"
15197                "       // comment",
15198                Style);
15199   EXPECT_EQ("int a; /* first line\n"
15200             "        * second\n"
15201             "        * line third\n"
15202             "        * line\n"
15203             "        */",
15204             format("int a; /* first line\n"
15205                    "        * second\n"
15206                    "        * line third\n"
15207                    "        * line\n"
15208                    "        */",
15209                    Style));
15210   EXPECT_EQ("int a; // first line\n"
15211             "       // second\n"
15212             "       // line third\n"
15213             "       // line",
15214             format("int a; // first line\n"
15215                    "       // second line\n"
15216                    "       // third line",
15217                    Style));
15218 
15219   Style.PenaltyExcessCharacter = 90;
15220   verifyFormat("int a; // the comment", Style);
15221   EXPECT_EQ("int a; // the comment\n"
15222             "       // aaa",
15223             format("int a; // the comment aaa", Style));
15224   EXPECT_EQ("int a; /* first line\n"
15225             "        * second line\n"
15226             "        * third line\n"
15227             "        */",
15228             format("int a; /* first line\n"
15229                    "        * second line\n"
15230                    "        * third line\n"
15231                    "        */",
15232                    Style));
15233   EXPECT_EQ("int a; // first line\n"
15234             "       // second line\n"
15235             "       // third line",
15236             format("int a; // first line\n"
15237                    "       // second line\n"
15238                    "       // third line",
15239                    Style));
15240   // FIXME: Investigate why this is not getting the same layout as the test
15241   // above.
15242   EXPECT_EQ("int a; /* first line\n"
15243             "        * second line\n"
15244             "        * third line\n"
15245             "        */",
15246             format("int a; /* first line second line third line"
15247                    "\n*/",
15248                    Style));
15249 
15250   EXPECT_EQ("// foo bar baz bazfoo\n"
15251             "// foo bar foo bar\n",
15252             format("// foo bar baz bazfoo\n"
15253                    "// foo bar foo           bar\n",
15254                    Style));
15255   EXPECT_EQ("// foo bar baz bazfoo\n"
15256             "// foo bar foo bar\n",
15257             format("// foo bar baz      bazfoo\n"
15258                    "// foo            bar foo bar\n",
15259                    Style));
15260 
15261   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
15262   // next one.
15263   EXPECT_EQ("// foo bar baz bazfoo\n"
15264             "// bar foo bar\n",
15265             format("// foo bar baz      bazfoo bar\n"
15266                    "// foo            bar\n",
15267                    Style));
15268 
15269   EXPECT_EQ("// foo bar baz bazfoo\n"
15270             "// foo bar baz bazfoo\n"
15271             "// bar foo bar\n",
15272             format("// foo bar baz      bazfoo\n"
15273                    "// foo bar baz      bazfoo bar\n"
15274                    "// foo bar\n",
15275                    Style));
15276 
15277   EXPECT_EQ("// foo bar baz bazfoo\n"
15278             "// foo bar baz bazfoo\n"
15279             "// bar foo bar\n",
15280             format("// foo bar baz      bazfoo\n"
15281                    "// foo bar baz      bazfoo bar\n"
15282                    "// foo           bar\n",
15283                    Style));
15284 
15285   // Make sure we do not keep protruding characters if strict mode reflow is
15286   // cheaper than keeping protruding characters.
15287   Style.ColumnLimit = 21;
15288   EXPECT_EQ(
15289       "// foo foo foo foo\n"
15290       "// foo foo foo foo\n"
15291       "// foo foo foo foo\n",
15292       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
15293 
15294   EXPECT_EQ("int a = /* long block\n"
15295             "           comment */\n"
15296             "    42;",
15297             format("int a = /* long block comment */ 42;", Style));
15298 }
15299 
15300 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
15301   for (size_t i = 1; i < Styles.size(); ++i)                                   \
15302   EXPECT_EQ(Styles[0], Styles[i])                                              \
15303       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
15304 
15305 TEST_F(FormatTest, GetsPredefinedStyleByName) {
15306   SmallVector<FormatStyle, 3> Styles;
15307   Styles.resize(3);
15308 
15309   Styles[0] = getLLVMStyle();
15310   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
15311   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
15312   EXPECT_ALL_STYLES_EQUAL(Styles);
15313 
15314   Styles[0] = getGoogleStyle();
15315   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
15316   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
15317   EXPECT_ALL_STYLES_EQUAL(Styles);
15318 
15319   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
15320   EXPECT_TRUE(
15321       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
15322   EXPECT_TRUE(
15323       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
15324   EXPECT_ALL_STYLES_EQUAL(Styles);
15325 
15326   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
15327   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
15328   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
15329   EXPECT_ALL_STYLES_EQUAL(Styles);
15330 
15331   Styles[0] = getMozillaStyle();
15332   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
15333   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
15334   EXPECT_ALL_STYLES_EQUAL(Styles);
15335 
15336   Styles[0] = getWebKitStyle();
15337   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
15338   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
15339   EXPECT_ALL_STYLES_EQUAL(Styles);
15340 
15341   Styles[0] = getGNUStyle();
15342   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
15343   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
15344   EXPECT_ALL_STYLES_EQUAL(Styles);
15345 
15346   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
15347 }
15348 
15349 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
15350   SmallVector<FormatStyle, 8> Styles;
15351   Styles.resize(2);
15352 
15353   Styles[0] = getGoogleStyle();
15354   Styles[1] = getLLVMStyle();
15355   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
15356   EXPECT_ALL_STYLES_EQUAL(Styles);
15357 
15358   Styles.resize(5);
15359   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
15360   Styles[1] = getLLVMStyle();
15361   Styles[1].Language = FormatStyle::LK_JavaScript;
15362   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
15363 
15364   Styles[2] = getLLVMStyle();
15365   Styles[2].Language = FormatStyle::LK_JavaScript;
15366   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
15367                                   "BasedOnStyle: Google",
15368                                   &Styles[2])
15369                    .value());
15370 
15371   Styles[3] = getLLVMStyle();
15372   Styles[3].Language = FormatStyle::LK_JavaScript;
15373   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
15374                                   "Language: JavaScript",
15375                                   &Styles[3])
15376                    .value());
15377 
15378   Styles[4] = getLLVMStyle();
15379   Styles[4].Language = FormatStyle::LK_JavaScript;
15380   EXPECT_EQ(0, parseConfiguration("---\n"
15381                                   "BasedOnStyle: LLVM\n"
15382                                   "IndentWidth: 123\n"
15383                                   "---\n"
15384                                   "BasedOnStyle: Google\n"
15385                                   "Language: JavaScript",
15386                                   &Styles[4])
15387                    .value());
15388   EXPECT_ALL_STYLES_EQUAL(Styles);
15389 }
15390 
15391 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
15392   Style.FIELD = false;                                                         \
15393   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
15394   EXPECT_TRUE(Style.FIELD);                                                    \
15395   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
15396   EXPECT_FALSE(Style.FIELD);
15397 
15398 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
15399 
15400 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
15401   Style.STRUCT.FIELD = false;                                                  \
15402   EXPECT_EQ(0,                                                                 \
15403             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
15404                 .value());                                                     \
15405   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
15406   EXPECT_EQ(0,                                                                 \
15407             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
15408                 .value());                                                     \
15409   EXPECT_FALSE(Style.STRUCT.FIELD);
15410 
15411 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
15412   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
15413 
15414 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
15415   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
15416   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
15417   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
15418 
15419 TEST_F(FormatTest, ParsesConfigurationBools) {
15420   FormatStyle Style = {};
15421   Style.Language = FormatStyle::LK_Cpp;
15422   CHECK_PARSE_BOOL(AlignTrailingComments);
15423   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
15424   CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine);
15425   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
15426   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
15427   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
15428   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
15429   CHECK_PARSE_BOOL(BinPackArguments);
15430   CHECK_PARSE_BOOL(BinPackParameters);
15431   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
15432   CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
15433   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
15434   CHECK_PARSE_BOOL(BreakStringLiterals);
15435   CHECK_PARSE_BOOL(CompactNamespaces);
15436   CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
15437   CHECK_PARSE_BOOL(DeriveLineEnding);
15438   CHECK_PARSE_BOOL(DerivePointerAlignment);
15439   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
15440   CHECK_PARSE_BOOL(DisableFormat);
15441   CHECK_PARSE_BOOL(IndentCaseLabels);
15442   CHECK_PARSE_BOOL(IndentCaseBlocks);
15443   CHECK_PARSE_BOOL(IndentGotoLabels);
15444   CHECK_PARSE_BOOL(IndentRequires);
15445   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
15446   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
15447   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
15448   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
15449   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
15450   CHECK_PARSE_BOOL(ReflowComments);
15451   CHECK_PARSE_BOOL(SortIncludes);
15452   CHECK_PARSE_BOOL(SortUsingDeclarations);
15453   CHECK_PARSE_BOOL(SpacesInParentheses);
15454   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
15455   CHECK_PARSE_BOOL(SpacesInAngles);
15456   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
15457   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
15458   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
15459   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
15460   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
15461   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
15462   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
15463   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
15464   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
15465   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
15466   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
15467   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
15468   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
15469   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
15470   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
15471   CHECK_PARSE_BOOL(UseCRLF);
15472 
15473   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
15474   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
15475   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
15476   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
15477   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
15478   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
15479   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
15480   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
15481   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
15482   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
15483   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
15484   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
15485   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
15486   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
15487   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
15488   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
15489   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
15490 }
15491 
15492 #undef CHECK_PARSE_BOOL
15493 
15494 TEST_F(FormatTest, ParsesConfiguration) {
15495   FormatStyle Style = {};
15496   Style.Language = FormatStyle::LK_Cpp;
15497   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
15498   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
15499               ConstructorInitializerIndentWidth, 1234u);
15500   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
15501   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
15502   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
15503   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
15504   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
15505               PenaltyBreakBeforeFirstCallParameter, 1234u);
15506   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
15507               PenaltyBreakTemplateDeclaration, 1234u);
15508   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
15509   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
15510               PenaltyReturnTypeOnItsOwnLine, 1234u);
15511   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
15512               SpacesBeforeTrailingComments, 1234u);
15513   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
15514   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
15515   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
15516 
15517   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15518   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
15519               FormatStyle::ACS_None);
15520   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
15521               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
15522   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
15523               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
15524   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
15525               AlignConsecutiveAssignments,
15526               FormatStyle::ACS_AcrossEmptyLinesAndComments);
15527   // For backwards compability, false / true should still parse
15528   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
15529               FormatStyle::ACS_None);
15530   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
15531               FormatStyle::ACS_Consecutive);
15532 
15533   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
15534   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
15535               FormatStyle::ACS_None);
15536   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
15537               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
15538   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
15539               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
15540   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
15541               AlignConsecutiveBitFields,
15542               FormatStyle::ACS_AcrossEmptyLinesAndComments);
15543   // For backwards compability, false / true should still parse
15544   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
15545               FormatStyle::ACS_None);
15546   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
15547               FormatStyle::ACS_Consecutive);
15548 
15549   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
15550   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
15551               FormatStyle::ACS_None);
15552   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
15553               FormatStyle::ACS_Consecutive);
15554   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
15555               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
15556   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
15557               AlignConsecutiveMacros,
15558               FormatStyle::ACS_AcrossEmptyLinesAndComments);
15559   // For backwards compability, false / true should still parse
15560   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
15561               FormatStyle::ACS_None);
15562   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
15563               FormatStyle::ACS_Consecutive);
15564 
15565   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15566   CHECK_PARSE("AlignConsecutiveDeclarations: None",
15567               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
15568   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
15569               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
15570   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
15571               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
15572   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
15573               AlignConsecutiveDeclarations,
15574               FormatStyle::ACS_AcrossEmptyLinesAndComments);
15575   // For backwards compability, false / true should still parse
15576   CHECK_PARSE("AlignConsecutiveDeclarations: false",
15577               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
15578   CHECK_PARSE("AlignConsecutiveDeclarations: true",
15579               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
15580 
15581   Style.PointerAlignment = FormatStyle::PAS_Middle;
15582   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
15583               FormatStyle::PAS_Left);
15584   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
15585               FormatStyle::PAS_Right);
15586   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
15587               FormatStyle::PAS_Middle);
15588   // For backward compatibility:
15589   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
15590               FormatStyle::PAS_Left);
15591   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
15592               FormatStyle::PAS_Right);
15593   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
15594               FormatStyle::PAS_Middle);
15595 
15596   Style.Standard = FormatStyle::LS_Auto;
15597   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
15598   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
15599   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
15600   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
15601   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
15602   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
15603   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
15604   // Legacy aliases:
15605   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
15606   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
15607   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
15608   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
15609 
15610   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
15611   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
15612               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
15613   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
15614               FormatStyle::BOS_None);
15615   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
15616               FormatStyle::BOS_All);
15617   // For backward compatibility:
15618   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
15619               FormatStyle::BOS_None);
15620   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
15621               FormatStyle::BOS_All);
15622 
15623   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
15624   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
15625               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
15626   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
15627               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
15628   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
15629               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
15630   // For backward compatibility:
15631   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
15632               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
15633 
15634   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
15635   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
15636               FormatStyle::BILS_BeforeComma);
15637   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
15638               FormatStyle::BILS_AfterColon);
15639   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
15640               FormatStyle::BILS_BeforeColon);
15641   // For backward compatibility:
15642   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
15643               FormatStyle::BILS_BeforeComma);
15644 
15645   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
15646   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
15647               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
15648   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
15649               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
15650   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
15651               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
15652   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
15653               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
15654 
15655   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
15656   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
15657               FormatStyle::BAS_Align);
15658   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
15659               FormatStyle::BAS_DontAlign);
15660   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
15661               FormatStyle::BAS_AlwaysBreak);
15662   // For backward compatibility:
15663   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
15664               FormatStyle::BAS_DontAlign);
15665   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
15666               FormatStyle::BAS_Align);
15667 
15668   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
15669   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
15670               FormatStyle::ENAS_DontAlign);
15671   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
15672               FormatStyle::ENAS_Left);
15673   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
15674               FormatStyle::ENAS_Right);
15675   // For backward compatibility:
15676   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
15677               FormatStyle::ENAS_Left);
15678   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
15679               FormatStyle::ENAS_Right);
15680 
15681   Style.AlignOperands = FormatStyle::OAS_Align;
15682   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
15683               FormatStyle::OAS_DontAlign);
15684   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
15685   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
15686               FormatStyle::OAS_AlignAfterOperator);
15687   // For backward compatibility:
15688   CHECK_PARSE("AlignOperands: false", AlignOperands,
15689               FormatStyle::OAS_DontAlign);
15690   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
15691 
15692   Style.UseTab = FormatStyle::UT_ForIndentation;
15693   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
15694   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
15695   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
15696   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
15697               FormatStyle::UT_ForContinuationAndIndentation);
15698   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
15699               FormatStyle::UT_AlignWithSpaces);
15700   // For backward compatibility:
15701   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
15702   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
15703 
15704   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
15705   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
15706               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
15707   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
15708               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
15709   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
15710               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
15711   // For backward compatibility:
15712   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
15713               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
15714   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
15715               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
15716 
15717   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
15718   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
15719               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
15720   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
15721               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
15722   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
15723               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
15724   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
15725               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
15726   // For backward compatibility:
15727   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
15728               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
15729   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
15730               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
15731 
15732   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
15733   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
15734               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
15735   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
15736               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
15737   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
15738               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
15739   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
15740               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
15741 
15742   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
15743   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
15744               FormatStyle::SBPO_Never);
15745   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
15746               FormatStyle::SBPO_Always);
15747   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
15748               FormatStyle::SBPO_ControlStatements);
15749   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
15750               FormatStyle::SBPO_NonEmptyParentheses);
15751   // For backward compatibility:
15752   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
15753               FormatStyle::SBPO_Never);
15754   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
15755               FormatStyle::SBPO_ControlStatements);
15756 
15757   Style.ColumnLimit = 123;
15758   FormatStyle BaseStyle = getLLVMStyle();
15759   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
15760   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
15761 
15762   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
15763   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
15764               FormatStyle::BS_Attach);
15765   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
15766               FormatStyle::BS_Linux);
15767   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
15768               FormatStyle::BS_Mozilla);
15769   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
15770               FormatStyle::BS_Stroustrup);
15771   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
15772               FormatStyle::BS_Allman);
15773   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
15774               FormatStyle::BS_Whitesmiths);
15775   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
15776   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
15777               FormatStyle::BS_WebKit);
15778   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
15779               FormatStyle::BS_Custom);
15780 
15781   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
15782   CHECK_PARSE("BraceWrapping:\n"
15783               "  AfterControlStatement: MultiLine",
15784               BraceWrapping.AfterControlStatement,
15785               FormatStyle::BWACS_MultiLine);
15786   CHECK_PARSE("BraceWrapping:\n"
15787               "  AfterControlStatement: Always",
15788               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
15789   CHECK_PARSE("BraceWrapping:\n"
15790               "  AfterControlStatement: Never",
15791               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
15792   // For backward compatibility:
15793   CHECK_PARSE("BraceWrapping:\n"
15794               "  AfterControlStatement: true",
15795               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
15796   CHECK_PARSE("BraceWrapping:\n"
15797               "  AfterControlStatement: false",
15798               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
15799 
15800   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
15801   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
15802               FormatStyle::RTBS_None);
15803   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
15804               FormatStyle::RTBS_All);
15805   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
15806               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
15807   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
15808               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
15809   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
15810               AlwaysBreakAfterReturnType,
15811               FormatStyle::RTBS_TopLevelDefinitions);
15812 
15813   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
15814   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
15815               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
15816   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
15817               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
15818   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
15819               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
15820   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
15821               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
15822   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
15823               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
15824 
15825   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
15826   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
15827               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
15828   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
15829               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
15830   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
15831               AlwaysBreakAfterDefinitionReturnType,
15832               FormatStyle::DRTBS_TopLevel);
15833 
15834   Style.NamespaceIndentation = FormatStyle::NI_All;
15835   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
15836               FormatStyle::NI_None);
15837   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
15838               FormatStyle::NI_Inner);
15839   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
15840               FormatStyle::NI_All);
15841 
15842   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
15843   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
15844               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
15845   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
15846               AllowShortIfStatementsOnASingleLine,
15847               FormatStyle::SIS_WithoutElse);
15848   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
15849               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Always);
15850   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
15851               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
15852   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
15853               AllowShortIfStatementsOnASingleLine,
15854               FormatStyle::SIS_WithoutElse);
15855 
15856   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
15857   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
15858               FormatStyle::IEBS_AfterExternBlock);
15859   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
15860               FormatStyle::IEBS_Indent);
15861   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
15862               FormatStyle::IEBS_NoIndent);
15863   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
15864               FormatStyle::IEBS_Indent);
15865   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
15866               FormatStyle::IEBS_NoIndent);
15867 
15868   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
15869   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
15870               FormatStyle::BFCS_Both);
15871   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
15872               FormatStyle::BFCS_None);
15873   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
15874               FormatStyle::BFCS_Before);
15875   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
15876               FormatStyle::BFCS_After);
15877 
15878   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
15879   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
15880               FormatStyle::SJSIO_After);
15881   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
15882               FormatStyle::SJSIO_Before);
15883 
15884   // FIXME: This is required because parsing a configuration simply overwrites
15885   // the first N elements of the list instead of resetting it.
15886   Style.ForEachMacros.clear();
15887   std::vector<std::string> BoostForeach;
15888   BoostForeach.push_back("BOOST_FOREACH");
15889   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
15890   std::vector<std::string> BoostAndQForeach;
15891   BoostAndQForeach.push_back("BOOST_FOREACH");
15892   BoostAndQForeach.push_back("Q_FOREACH");
15893   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
15894               BoostAndQForeach);
15895 
15896   Style.AttributeMacros.clear();
15897   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
15898               std::vector<std::string>{"__capability"});
15899   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
15900               std::vector<std::string>({"attr1", "attr2"}));
15901 
15902   Style.StatementAttributeLikeMacros.clear();
15903   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
15904               StatementAttributeLikeMacros,
15905               std::vector<std::string>({"emit", "Q_EMIT"}));
15906 
15907   Style.StatementMacros.clear();
15908   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
15909               std::vector<std::string>{"QUNUSED"});
15910   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
15911               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
15912 
15913   Style.NamespaceMacros.clear();
15914   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
15915               std::vector<std::string>{"TESTSUITE"});
15916   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
15917               std::vector<std::string>({"TESTSUITE", "SUITE"}));
15918 
15919   Style.WhitespaceSensitiveMacros.clear();
15920   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
15921               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
15922   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
15923               WhitespaceSensitiveMacros,
15924               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
15925   Style.WhitespaceSensitiveMacros.clear();
15926   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
15927               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
15928   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
15929               WhitespaceSensitiveMacros,
15930               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
15931 
15932   Style.IncludeStyle.IncludeCategories.clear();
15933   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
15934       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
15935   CHECK_PARSE("IncludeCategories:\n"
15936               "  - Regex: abc/.*\n"
15937               "    Priority: 2\n"
15938               "  - Regex: .*\n"
15939               "    Priority: 1\n"
15940               "    CaseSensitive: true\n",
15941               IncludeStyle.IncludeCategories, ExpectedCategories);
15942   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
15943               "abc$");
15944   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
15945               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
15946 
15947   Style.RawStringFormats.clear();
15948   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
15949       {
15950           FormatStyle::LK_TextProto,
15951           {"pb", "proto"},
15952           {"PARSE_TEXT_PROTO"},
15953           /*CanonicalDelimiter=*/"",
15954           "llvm",
15955       },
15956       {
15957           FormatStyle::LK_Cpp,
15958           {"cc", "cpp"},
15959           {"C_CODEBLOCK", "CPPEVAL"},
15960           /*CanonicalDelimiter=*/"cc",
15961           /*BasedOnStyle=*/"",
15962       },
15963   };
15964 
15965   CHECK_PARSE("RawStringFormats:\n"
15966               "  - Language: TextProto\n"
15967               "    Delimiters:\n"
15968               "      - 'pb'\n"
15969               "      - 'proto'\n"
15970               "    EnclosingFunctions:\n"
15971               "      - 'PARSE_TEXT_PROTO'\n"
15972               "    BasedOnStyle: llvm\n"
15973               "  - Language: Cpp\n"
15974               "    Delimiters:\n"
15975               "      - 'cc'\n"
15976               "      - 'cpp'\n"
15977               "    EnclosingFunctions:\n"
15978               "      - 'C_CODEBLOCK'\n"
15979               "      - 'CPPEVAL'\n"
15980               "    CanonicalDelimiter: 'cc'",
15981               RawStringFormats, ExpectedRawStringFormats);
15982 }
15983 
15984 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
15985   FormatStyle Style = {};
15986   Style.Language = FormatStyle::LK_Cpp;
15987   CHECK_PARSE("Language: Cpp\n"
15988               "IndentWidth: 12",
15989               IndentWidth, 12u);
15990   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
15991                                "IndentWidth: 34",
15992                                &Style),
15993             ParseError::Unsuitable);
15994   FormatStyle BinPackedTCS = {};
15995   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
15996   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
15997                                "InsertTrailingCommas: Wrapped",
15998                                &BinPackedTCS),
15999             ParseError::BinPackTrailingCommaConflict);
16000   EXPECT_EQ(12u, Style.IndentWidth);
16001   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
16002   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
16003 
16004   Style.Language = FormatStyle::LK_JavaScript;
16005   CHECK_PARSE("Language: JavaScript\n"
16006               "IndentWidth: 12",
16007               IndentWidth, 12u);
16008   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
16009   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
16010                                "IndentWidth: 34",
16011                                &Style),
16012             ParseError::Unsuitable);
16013   EXPECT_EQ(23u, Style.IndentWidth);
16014   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
16015   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
16016 
16017   CHECK_PARSE("BasedOnStyle: LLVM\n"
16018               "IndentWidth: 67",
16019               IndentWidth, 67u);
16020 
16021   CHECK_PARSE("---\n"
16022               "Language: JavaScript\n"
16023               "IndentWidth: 12\n"
16024               "---\n"
16025               "Language: Cpp\n"
16026               "IndentWidth: 34\n"
16027               "...\n",
16028               IndentWidth, 12u);
16029 
16030   Style.Language = FormatStyle::LK_Cpp;
16031   CHECK_PARSE("---\n"
16032               "Language: JavaScript\n"
16033               "IndentWidth: 12\n"
16034               "---\n"
16035               "Language: Cpp\n"
16036               "IndentWidth: 34\n"
16037               "...\n",
16038               IndentWidth, 34u);
16039   CHECK_PARSE("---\n"
16040               "IndentWidth: 78\n"
16041               "---\n"
16042               "Language: JavaScript\n"
16043               "IndentWidth: 56\n"
16044               "...\n",
16045               IndentWidth, 78u);
16046 
16047   Style.ColumnLimit = 123;
16048   Style.IndentWidth = 234;
16049   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
16050   Style.TabWidth = 345;
16051   EXPECT_FALSE(parseConfiguration("---\n"
16052                                   "IndentWidth: 456\n"
16053                                   "BreakBeforeBraces: Allman\n"
16054                                   "---\n"
16055                                   "Language: JavaScript\n"
16056                                   "IndentWidth: 111\n"
16057                                   "TabWidth: 111\n"
16058                                   "---\n"
16059                                   "Language: Cpp\n"
16060                                   "BreakBeforeBraces: Stroustrup\n"
16061                                   "TabWidth: 789\n"
16062                                   "...\n",
16063                                   &Style));
16064   EXPECT_EQ(123u, Style.ColumnLimit);
16065   EXPECT_EQ(456u, Style.IndentWidth);
16066   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
16067   EXPECT_EQ(789u, Style.TabWidth);
16068 
16069   EXPECT_EQ(parseConfiguration("---\n"
16070                                "Language: JavaScript\n"
16071                                "IndentWidth: 56\n"
16072                                "---\n"
16073                                "IndentWidth: 78\n"
16074                                "...\n",
16075                                &Style),
16076             ParseError::Error);
16077   EXPECT_EQ(parseConfiguration("---\n"
16078                                "Language: JavaScript\n"
16079                                "IndentWidth: 56\n"
16080                                "---\n"
16081                                "Language: JavaScript\n"
16082                                "IndentWidth: 78\n"
16083                                "...\n",
16084                                &Style),
16085             ParseError::Error);
16086 
16087   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
16088 }
16089 
16090 #undef CHECK_PARSE
16091 
16092 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
16093   FormatStyle Style = {};
16094   Style.Language = FormatStyle::LK_JavaScript;
16095   Style.BreakBeforeTernaryOperators = true;
16096   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
16097   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
16098 
16099   Style.BreakBeforeTernaryOperators = true;
16100   EXPECT_EQ(0, parseConfiguration("---\n"
16101                                   "BasedOnStyle: Google\n"
16102                                   "---\n"
16103                                   "Language: JavaScript\n"
16104                                   "IndentWidth: 76\n"
16105                                   "...\n",
16106                                   &Style)
16107                    .value());
16108   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
16109   EXPECT_EQ(76u, Style.IndentWidth);
16110   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
16111 }
16112 
16113 TEST_F(FormatTest, ConfigurationRoundTripTest) {
16114   FormatStyle Style = getLLVMStyle();
16115   std::string YAML = configurationAsText(Style);
16116   FormatStyle ParsedStyle = {};
16117   ParsedStyle.Language = FormatStyle::LK_Cpp;
16118   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
16119   EXPECT_EQ(Style, ParsedStyle);
16120 }
16121 
16122 TEST_F(FormatTest, WorksFor8bitEncodings) {
16123   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
16124             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
16125             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
16126             "\"\xef\xee\xf0\xf3...\"",
16127             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
16128                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
16129                    "\xef\xee\xf0\xf3...\"",
16130                    getLLVMStyleWithColumns(12)));
16131 }
16132 
16133 TEST_F(FormatTest, HandlesUTF8BOM) {
16134   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
16135   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
16136             format("\xef\xbb\xbf#include <iostream>"));
16137   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
16138             format("\xef\xbb\xbf\n#include <iostream>"));
16139 }
16140 
16141 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
16142 #if !defined(_MSC_VER)
16143 
16144 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
16145   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
16146                getLLVMStyleWithColumns(35));
16147   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
16148                getLLVMStyleWithColumns(31));
16149   verifyFormat("// Однажды в студёную зимнюю пору...",
16150                getLLVMStyleWithColumns(36));
16151   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
16152   verifyFormat("/* Однажды в студёную зимнюю пору... */",
16153                getLLVMStyleWithColumns(39));
16154   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
16155                getLLVMStyleWithColumns(35));
16156 }
16157 
16158 TEST_F(FormatTest, SplitsUTF8Strings) {
16159   // Non-printable characters' width is currently considered to be the length in
16160   // bytes in UTF8. The characters can be displayed in very different manner
16161   // (zero-width, single width with a substitution glyph, expanded to their code
16162   // (e.g. "<8d>"), so there's no single correct way to handle them.
16163   EXPECT_EQ("\"aaaaÄ\"\n"
16164             "\"\xc2\x8d\";",
16165             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
16166   EXPECT_EQ("\"aaaaaaaÄ\"\n"
16167             "\"\xc2\x8d\";",
16168             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
16169   EXPECT_EQ("\"Однажды, в \"\n"
16170             "\"студёную \"\n"
16171             "\"зимнюю \"\n"
16172             "\"пору,\"",
16173             format("\"Однажды, в студёную зимнюю пору,\"",
16174                    getLLVMStyleWithColumns(13)));
16175   EXPECT_EQ(
16176       "\"一 二 三 \"\n"
16177       "\"四 五六 \"\n"
16178       "\"七 八 九 \"\n"
16179       "\"十\"",
16180       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
16181   EXPECT_EQ("\"一\t\"\n"
16182             "\"二 \t\"\n"
16183             "\"三 四 \"\n"
16184             "\"五\t\"\n"
16185             "\"六 \t\"\n"
16186             "\"七 \"\n"
16187             "\"八九十\tqq\"",
16188             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
16189                    getLLVMStyleWithColumns(11)));
16190 
16191   // UTF8 character in an escape sequence.
16192   EXPECT_EQ("\"aaaaaa\"\n"
16193             "\"\\\xC2\x8D\"",
16194             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
16195 }
16196 
16197 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
16198   EXPECT_EQ("const char *sssss =\n"
16199             "    \"一二三四五六七八\\\n"
16200             " 九 十\";",
16201             format("const char *sssss = \"一二三四五六七八\\\n"
16202                    " 九 十\";",
16203                    getLLVMStyleWithColumns(30)));
16204 }
16205 
16206 TEST_F(FormatTest, SplitsUTF8LineComments) {
16207   EXPECT_EQ("// aaaaÄ\xc2\x8d",
16208             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
16209   EXPECT_EQ("// Я из лесу\n"
16210             "// вышел; был\n"
16211             "// сильный\n"
16212             "// мороз.",
16213             format("// Я из лесу вышел; был сильный мороз.",
16214                    getLLVMStyleWithColumns(13)));
16215   EXPECT_EQ("// 一二三\n"
16216             "// 四五六七\n"
16217             "// 八  九\n"
16218             "// 十",
16219             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
16220 }
16221 
16222 TEST_F(FormatTest, SplitsUTF8BlockComments) {
16223   EXPECT_EQ("/* Гляжу,\n"
16224             " * поднимается\n"
16225             " * медленно в\n"
16226             " * гору\n"
16227             " * Лошадка,\n"
16228             " * везущая\n"
16229             " * хворосту\n"
16230             " * воз. */",
16231             format("/* Гляжу, поднимается медленно в гору\n"
16232                    " * Лошадка, везущая хворосту воз. */",
16233                    getLLVMStyleWithColumns(13)));
16234   EXPECT_EQ(
16235       "/* 一二三\n"
16236       " * 四五六七\n"
16237       " * 八  九\n"
16238       " * 十  */",
16239       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
16240   EXPECT_EQ("/* �������� ��������\n"
16241             " * ��������\n"
16242             " * ������-�� */",
16243             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
16244 }
16245 
16246 #endif // _MSC_VER
16247 
16248 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
16249   FormatStyle Style = getLLVMStyle();
16250 
16251   Style.ConstructorInitializerIndentWidth = 4;
16252   verifyFormat(
16253       "SomeClass::Constructor()\n"
16254       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
16255       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
16256       Style);
16257 
16258   Style.ConstructorInitializerIndentWidth = 2;
16259   verifyFormat(
16260       "SomeClass::Constructor()\n"
16261       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
16262       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
16263       Style);
16264 
16265   Style.ConstructorInitializerIndentWidth = 0;
16266   verifyFormat(
16267       "SomeClass::Constructor()\n"
16268       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
16269       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
16270       Style);
16271   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
16272   verifyFormat(
16273       "SomeLongTemplateVariableName<\n"
16274       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
16275       Style);
16276   verifyFormat("bool smaller = 1 < "
16277                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
16278                "                       "
16279                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
16280                Style);
16281 
16282   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
16283   verifyFormat("SomeClass::Constructor() :\n"
16284                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
16285                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
16286                Style);
16287 }
16288 
16289 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
16290   FormatStyle Style = getLLVMStyle();
16291   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
16292   Style.ConstructorInitializerIndentWidth = 4;
16293   verifyFormat("SomeClass::Constructor()\n"
16294                "    : a(a)\n"
16295                "    , b(b)\n"
16296                "    , c(c) {}",
16297                Style);
16298   verifyFormat("SomeClass::Constructor()\n"
16299                "    : a(a) {}",
16300                Style);
16301 
16302   Style.ColumnLimit = 0;
16303   verifyFormat("SomeClass::Constructor()\n"
16304                "    : a(a) {}",
16305                Style);
16306   verifyFormat("SomeClass::Constructor() noexcept\n"
16307                "    : a(a) {}",
16308                Style);
16309   verifyFormat("SomeClass::Constructor()\n"
16310                "    : a(a)\n"
16311                "    , b(b)\n"
16312                "    , c(c) {}",
16313                Style);
16314   verifyFormat("SomeClass::Constructor()\n"
16315                "    : a(a) {\n"
16316                "  foo();\n"
16317                "  bar();\n"
16318                "}",
16319                Style);
16320 
16321   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
16322   verifyFormat("SomeClass::Constructor()\n"
16323                "    : a(a)\n"
16324                "    , b(b)\n"
16325                "    , c(c) {\n}",
16326                Style);
16327   verifyFormat("SomeClass::Constructor()\n"
16328                "    : a(a) {\n}",
16329                Style);
16330 
16331   Style.ColumnLimit = 80;
16332   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
16333   Style.ConstructorInitializerIndentWidth = 2;
16334   verifyFormat("SomeClass::Constructor()\n"
16335                "  : a(a)\n"
16336                "  , b(b)\n"
16337                "  , c(c) {}",
16338                Style);
16339 
16340   Style.ConstructorInitializerIndentWidth = 0;
16341   verifyFormat("SomeClass::Constructor()\n"
16342                ": a(a)\n"
16343                ", b(b)\n"
16344                ", c(c) {}",
16345                Style);
16346 
16347   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
16348   Style.ConstructorInitializerIndentWidth = 4;
16349   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
16350   verifyFormat(
16351       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
16352       Style);
16353   verifyFormat(
16354       "SomeClass::Constructor()\n"
16355       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
16356       Style);
16357   Style.ConstructorInitializerIndentWidth = 4;
16358   Style.ColumnLimit = 60;
16359   verifyFormat("SomeClass::Constructor()\n"
16360                "    : aaaaaaaa(aaaaaaaa)\n"
16361                "    , aaaaaaaa(aaaaaaaa)\n"
16362                "    , aaaaaaaa(aaaaaaaa) {}",
16363                Style);
16364 }
16365 
16366 TEST_F(FormatTest, Destructors) {
16367   verifyFormat("void F(int &i) { i.~int(); }");
16368   verifyFormat("void F(int &i) { i->~int(); }");
16369 }
16370 
16371 TEST_F(FormatTest, FormatsWithWebKitStyle) {
16372   FormatStyle Style = getWebKitStyle();
16373 
16374   // Don't indent in outer namespaces.
16375   verifyFormat("namespace outer {\n"
16376                "int i;\n"
16377                "namespace inner {\n"
16378                "    int i;\n"
16379                "} // namespace inner\n"
16380                "} // namespace outer\n"
16381                "namespace other_outer {\n"
16382                "int i;\n"
16383                "}",
16384                Style);
16385 
16386   // Don't indent case labels.
16387   verifyFormat("switch (variable) {\n"
16388                "case 1:\n"
16389                "case 2:\n"
16390                "    doSomething();\n"
16391                "    break;\n"
16392                "default:\n"
16393                "    ++variable;\n"
16394                "}",
16395                Style);
16396 
16397   // Wrap before binary operators.
16398   EXPECT_EQ("void f()\n"
16399             "{\n"
16400             "    if (aaaaaaaaaaaaaaaa\n"
16401             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
16402             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
16403             "        return;\n"
16404             "}",
16405             format("void f() {\n"
16406                    "if (aaaaaaaaaaaaaaaa\n"
16407                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
16408                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
16409                    "return;\n"
16410                    "}",
16411                    Style));
16412 
16413   // Allow functions on a single line.
16414   verifyFormat("void f() { return; }", Style);
16415 
16416   // Allow empty blocks on a single line and insert a space in empty blocks.
16417   EXPECT_EQ("void f() { }", format("void f() {}", Style));
16418   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
16419   // However, don't merge non-empty short loops.
16420   EXPECT_EQ("while (true) {\n"
16421             "    continue;\n"
16422             "}",
16423             format("while (true) { continue; }", Style));
16424 
16425   // Constructor initializers are formatted one per line with the "," on the
16426   // new line.
16427   verifyFormat("Constructor()\n"
16428                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
16429                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
16430                "          aaaaaaaaaaaaaa)\n"
16431                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
16432                "{\n"
16433                "}",
16434                Style);
16435   verifyFormat("SomeClass::Constructor()\n"
16436                "    : a(a)\n"
16437                "{\n"
16438                "}",
16439                Style);
16440   EXPECT_EQ("SomeClass::Constructor()\n"
16441             "    : a(a)\n"
16442             "{\n"
16443             "}",
16444             format("SomeClass::Constructor():a(a){}", Style));
16445   verifyFormat("SomeClass::Constructor()\n"
16446                "    : a(a)\n"
16447                "    , b(b)\n"
16448                "    , c(c)\n"
16449                "{\n"
16450                "}",
16451                Style);
16452   verifyFormat("SomeClass::Constructor()\n"
16453                "    : a(a)\n"
16454                "{\n"
16455                "    foo();\n"
16456                "    bar();\n"
16457                "}",
16458                Style);
16459 
16460   // Access specifiers should be aligned left.
16461   verifyFormat("class C {\n"
16462                "public:\n"
16463                "    int i;\n"
16464                "};",
16465                Style);
16466 
16467   // Do not align comments.
16468   verifyFormat("int a; // Do not\n"
16469                "double b; // align comments.",
16470                Style);
16471 
16472   // Do not align operands.
16473   EXPECT_EQ("ASSERT(aaaa\n"
16474             "    || bbbb);",
16475             format("ASSERT ( aaaa\n||bbbb);", Style));
16476 
16477   // Accept input's line breaks.
16478   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
16479             "    || bbbbbbbbbbbbbbb) {\n"
16480             "    i++;\n"
16481             "}",
16482             format("if (aaaaaaaaaaaaaaa\n"
16483                    "|| bbbbbbbbbbbbbbb) { i++; }",
16484                    Style));
16485   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
16486             "    i++;\n"
16487             "}",
16488             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
16489 
16490   // Don't automatically break all macro definitions (llvm.org/PR17842).
16491   verifyFormat("#define aNumber 10", Style);
16492   // However, generally keep the line breaks that the user authored.
16493   EXPECT_EQ("#define aNumber \\\n"
16494             "    10",
16495             format("#define aNumber \\\n"
16496                    " 10",
16497                    Style));
16498 
16499   // Keep empty and one-element array literals on a single line.
16500   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
16501             "                                  copyItems:YES];",
16502             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
16503                    "copyItems:YES];",
16504                    Style));
16505   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
16506             "                                  copyItems:YES];",
16507             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
16508                    "             copyItems:YES];",
16509                    Style));
16510   // FIXME: This does not seem right, there should be more indentation before
16511   // the array literal's entries. Nested blocks have the same problem.
16512   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
16513             "    @\"a\",\n"
16514             "    @\"a\"\n"
16515             "]\n"
16516             "                                  copyItems:YES];",
16517             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
16518                    "     @\"a\",\n"
16519                    "     @\"a\"\n"
16520                    "     ]\n"
16521                    "       copyItems:YES];",
16522                    Style));
16523   EXPECT_EQ(
16524       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
16525       "                                  copyItems:YES];",
16526       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
16527              "   copyItems:YES];",
16528              Style));
16529 
16530   verifyFormat("[self.a b:c c:d];", Style);
16531   EXPECT_EQ("[self.a b:c\n"
16532             "        c:d];",
16533             format("[self.a b:c\n"
16534                    "c:d];",
16535                    Style));
16536 }
16537 
16538 TEST_F(FormatTest, FormatsLambdas) {
16539   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
16540   verifyFormat(
16541       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
16542   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
16543   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
16544   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
16545   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
16546   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
16547   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
16548   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
16549   verifyFormat("int x = f(*+[] {});");
16550   verifyFormat("void f() {\n"
16551                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
16552                "}\n");
16553   verifyFormat("void f() {\n"
16554                "  other(x.begin(), //\n"
16555                "        x.end(),   //\n"
16556                "        [&](int, int) { return 1; });\n"
16557                "}\n");
16558   verifyFormat("void f() {\n"
16559                "  other.other.other.other.other(\n"
16560                "      x.begin(), x.end(),\n"
16561                "      [something, rather](int, int, int, int, int, int, int) { "
16562                "return 1; });\n"
16563                "}\n");
16564   verifyFormat(
16565       "void f() {\n"
16566       "  other.other.other.other.other(\n"
16567       "      x.begin(), x.end(),\n"
16568       "      [something, rather](int, int, int, int, int, int, int) {\n"
16569       "        //\n"
16570       "      });\n"
16571       "}\n");
16572   verifyFormat("SomeFunction([]() { // A cool function...\n"
16573                "  return 43;\n"
16574                "});");
16575   EXPECT_EQ("SomeFunction([]() {\n"
16576             "#define A a\n"
16577             "  return 43;\n"
16578             "});",
16579             format("SomeFunction([](){\n"
16580                    "#define A a\n"
16581                    "return 43;\n"
16582                    "});"));
16583   verifyFormat("void f() {\n"
16584                "  SomeFunction([](decltype(x), A *a) {});\n"
16585                "  SomeFunction([](typeof(x), A *a) {});\n"
16586                "  SomeFunction([](_Atomic(x), A *a) {});\n"
16587                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
16588                "}");
16589   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
16590                "    [](const aaaaaaaaaa &a) { return a; });");
16591   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
16592                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
16593                "});");
16594   verifyFormat("Constructor()\n"
16595                "    : Field([] { // comment\n"
16596                "        int i;\n"
16597                "      }) {}");
16598   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
16599                "  return some_parameter.size();\n"
16600                "};");
16601   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
16602                "    [](const string &s) { return s; };");
16603   verifyFormat("int i = aaaaaa ? 1 //\n"
16604                "               : [] {\n"
16605                "                   return 2; //\n"
16606                "                 }();");
16607   verifyFormat("llvm::errs() << \"number of twos is \"\n"
16608                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
16609                "                  return x == 2; // force break\n"
16610                "                });");
16611   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
16612                "    [=](int iiiiiiiiiiii) {\n"
16613                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
16614                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
16615                "    });",
16616                getLLVMStyleWithColumns(60));
16617   verifyFormat("SomeFunction({[&] {\n"
16618                "                // comment\n"
16619                "              },\n"
16620                "              [&] {\n"
16621                "                // comment\n"
16622                "              }});");
16623   verifyFormat("SomeFunction({[&] {\n"
16624                "  // comment\n"
16625                "}});");
16626   verifyFormat(
16627       "virtual aaaaaaaaaaaaaaaa(\n"
16628       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
16629       "    aaaaa aaaaaaaaa);");
16630 
16631   // Lambdas with return types.
16632   verifyFormat("int c = []() -> int { return 2; }();\n");
16633   verifyFormat("int c = []() -> int * { return 2; }();\n");
16634   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
16635   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
16636   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
16637   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
16638   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
16639   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
16640   verifyFormat("[a, a]() -> a<1> {};");
16641   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
16642   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
16643   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
16644   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
16645   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
16646   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
16647   verifyFormat("[]() -> foo<!5> { return {}; };");
16648   verifyFormat("[]() -> foo<~5> { return {}; };");
16649   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
16650   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
16651   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
16652   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
16653   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
16654   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
16655   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
16656   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
16657   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
16658   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
16659   verifyFormat("namespace bar {\n"
16660                "// broken:\n"
16661                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
16662                "} // namespace bar");
16663   verifyFormat("namespace bar {\n"
16664                "// broken:\n"
16665                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
16666                "} // namespace bar");
16667   verifyFormat("namespace bar {\n"
16668                "// broken:\n"
16669                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
16670                "} // namespace bar");
16671   verifyFormat("namespace bar {\n"
16672                "// broken:\n"
16673                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
16674                "} // namespace bar");
16675   verifyFormat("namespace bar {\n"
16676                "// broken:\n"
16677                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
16678                "} // namespace bar");
16679   verifyFormat("namespace bar {\n"
16680                "// broken:\n"
16681                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
16682                "} // namespace bar");
16683   verifyFormat("namespace bar {\n"
16684                "// broken:\n"
16685                "auto foo{[]() -> foo<!5> { return {}; }};\n"
16686                "} // namespace bar");
16687   verifyFormat("namespace bar {\n"
16688                "// broken:\n"
16689                "auto foo{[]() -> foo<~5> { return {}; }};\n"
16690                "} // namespace bar");
16691   verifyFormat("namespace bar {\n"
16692                "// broken:\n"
16693                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
16694                "} // namespace bar");
16695   verifyFormat("namespace bar {\n"
16696                "// broken:\n"
16697                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
16698                "} // namespace bar");
16699   verifyFormat("namespace bar {\n"
16700                "// broken:\n"
16701                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
16702                "} // namespace bar");
16703   verifyFormat("namespace bar {\n"
16704                "// broken:\n"
16705                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
16706                "} // namespace bar");
16707   verifyFormat("namespace bar {\n"
16708                "// broken:\n"
16709                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
16710                "} // namespace bar");
16711   verifyFormat("namespace bar {\n"
16712                "// broken:\n"
16713                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
16714                "} // namespace bar");
16715   verifyFormat("namespace bar {\n"
16716                "// broken:\n"
16717                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
16718                "} // namespace bar");
16719   verifyFormat("namespace bar {\n"
16720                "// broken:\n"
16721                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
16722                "} // namespace bar");
16723   verifyFormat("namespace bar {\n"
16724                "// broken:\n"
16725                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
16726                "} // namespace bar");
16727   verifyFormat("namespace bar {\n"
16728                "// broken:\n"
16729                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
16730                "} // namespace bar");
16731   verifyFormat("[]() -> a<1> {};");
16732   verifyFormat("[]() -> a<1> { ; };");
16733   verifyFormat("[]() -> a<1> { ; }();");
16734   verifyFormat("[a, a]() -> a<true> {};");
16735   verifyFormat("[]() -> a<true> {};");
16736   verifyFormat("[]() -> a<true> { ; };");
16737   verifyFormat("[]() -> a<true> { ; }();");
16738   verifyFormat("[a, a]() -> a<false> {};");
16739   verifyFormat("[]() -> a<false> {};");
16740   verifyFormat("[]() -> a<false> { ; };");
16741   verifyFormat("[]() -> a<false> { ; }();");
16742   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
16743   verifyFormat("namespace bar {\n"
16744                "auto foo{[]() -> foo<false> { ; }};\n"
16745                "} // namespace bar");
16746   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
16747                "                   int j) -> int {\n"
16748                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
16749                "};");
16750   verifyFormat(
16751       "aaaaaaaaaaaaaaaaaaaaaa(\n"
16752       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
16753       "      return aaaaaaaaaaaaaaaaa;\n"
16754       "    });",
16755       getLLVMStyleWithColumns(70));
16756   verifyFormat("[]() //\n"
16757                "    -> int {\n"
16758                "  return 1; //\n"
16759                "};");
16760   verifyFormat("[]() -> Void<T...> {};");
16761   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
16762 
16763   // Lambdas with explicit template argument lists.
16764   verifyFormat(
16765       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
16766 
16767   // Multiple lambdas in the same parentheses change indentation rules. These
16768   // lambdas are forced to start on new lines.
16769   verifyFormat("SomeFunction(\n"
16770                "    []() {\n"
16771                "      //\n"
16772                "    },\n"
16773                "    []() {\n"
16774                "      //\n"
16775                "    });");
16776 
16777   // A lambda passed as arg0 is always pushed to the next line.
16778   verifyFormat("SomeFunction(\n"
16779                "    [this] {\n"
16780                "      //\n"
16781                "    },\n"
16782                "    1);\n");
16783 
16784   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
16785   // the arg0 case above.
16786   auto Style = getGoogleStyle();
16787   Style.BinPackArguments = false;
16788   verifyFormat("SomeFunction(\n"
16789                "    a,\n"
16790                "    [this] {\n"
16791                "      //\n"
16792                "    },\n"
16793                "    b);\n",
16794                Style);
16795   verifyFormat("SomeFunction(\n"
16796                "    a,\n"
16797                "    [this] {\n"
16798                "      //\n"
16799                "    },\n"
16800                "    b);\n");
16801 
16802   // A lambda with a very long line forces arg0 to be pushed out irrespective of
16803   // the BinPackArguments value (as long as the code is wide enough).
16804   verifyFormat(
16805       "something->SomeFunction(\n"
16806       "    a,\n"
16807       "    [this] {\n"
16808       "      "
16809       "D0000000000000000000000000000000000000000000000000000000000001();\n"
16810       "    },\n"
16811       "    b);\n");
16812 
16813   // A multi-line lambda is pulled up as long as the introducer fits on the
16814   // previous line and there are no further args.
16815   verifyFormat("function(1, [this, that] {\n"
16816                "  //\n"
16817                "});\n");
16818   verifyFormat("function([this, that] {\n"
16819                "  //\n"
16820                "});\n");
16821   // FIXME: this format is not ideal and we should consider forcing the first
16822   // arg onto its own line.
16823   verifyFormat("function(a, b, c, //\n"
16824                "         d, [this, that] {\n"
16825                "           //\n"
16826                "         });\n");
16827 
16828   // Multiple lambdas are treated correctly even when there is a short arg0.
16829   verifyFormat("SomeFunction(\n"
16830                "    1,\n"
16831                "    [this] {\n"
16832                "      //\n"
16833                "    },\n"
16834                "    [this] {\n"
16835                "      //\n"
16836                "    },\n"
16837                "    1);\n");
16838 
16839   // More complex introducers.
16840   verifyFormat("return [i, args...] {};");
16841 
16842   // Not lambdas.
16843   verifyFormat("constexpr char hello[]{\"hello\"};");
16844   verifyFormat("double &operator[](int i) { return 0; }\n"
16845                "int i;");
16846   verifyFormat("std::unique_ptr<int[]> foo() {}");
16847   verifyFormat("int i = a[a][a]->f();");
16848   verifyFormat("int i = (*b)[a]->f();");
16849 
16850   // Other corner cases.
16851   verifyFormat("void f() {\n"
16852                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
16853                "  );\n"
16854                "}");
16855 
16856   // Lambdas created through weird macros.
16857   verifyFormat("void f() {\n"
16858                "  MACRO((const AA &a) { return 1; });\n"
16859                "  MACRO((AA &a) { return 1; });\n"
16860                "}");
16861 
16862   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
16863                "      doo_dah();\n"
16864                "      doo_dah();\n"
16865                "    })) {\n"
16866                "}");
16867   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
16868                "                doo_dah();\n"
16869                "                doo_dah();\n"
16870                "              })) {\n"
16871                "}");
16872   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
16873                "                doo_dah();\n"
16874                "                doo_dah();\n"
16875                "              })) {\n"
16876                "}");
16877   verifyFormat("auto lambda = []() {\n"
16878                "  int a = 2\n"
16879                "#if A\n"
16880                "          + 2\n"
16881                "#endif\n"
16882                "      ;\n"
16883                "};");
16884 
16885   // Lambdas with complex multiline introducers.
16886   verifyFormat(
16887       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
16888       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
16889       "        -> ::std::unordered_set<\n"
16890       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
16891       "      //\n"
16892       "    });");
16893 
16894   FormatStyle DoNotMerge = getLLVMStyle();
16895   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
16896   verifyFormat("auto c = []() {\n"
16897                "  return b;\n"
16898                "};",
16899                "auto c = []() { return b; };", DoNotMerge);
16900   verifyFormat("auto c = []() {\n"
16901                "};",
16902                " auto c = []() {};", DoNotMerge);
16903 
16904   FormatStyle MergeEmptyOnly = getLLVMStyle();
16905   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
16906   verifyFormat("auto c = []() {\n"
16907                "  return b;\n"
16908                "};",
16909                "auto c = []() {\n"
16910                "  return b;\n"
16911                " };",
16912                MergeEmptyOnly);
16913   verifyFormat("auto c = []() {};",
16914                "auto c = []() {\n"
16915                "};",
16916                MergeEmptyOnly);
16917 
16918   FormatStyle MergeInline = getLLVMStyle();
16919   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
16920   verifyFormat("auto c = []() {\n"
16921                "  return b;\n"
16922                "};",
16923                "auto c = []() { return b; };", MergeInline);
16924   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
16925                MergeInline);
16926   verifyFormat("function([]() { return b; }, a)",
16927                "function([]() { return b; }, a)", MergeInline);
16928   verifyFormat("function(a, []() { return b; })",
16929                "function(a, []() { return b; })", MergeInline);
16930 
16931   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
16932   // AllowShortLambdasOnASingleLine
16933   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
16934   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
16935   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
16936   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
16937       FormatStyle::ShortLambdaStyle::SLS_None;
16938   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
16939                "    []()\n"
16940                "    {\n"
16941                "      return 17;\n"
16942                "    });",
16943                LLVMWithBeforeLambdaBody);
16944   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
16945                "    []()\n"
16946                "    {\n"
16947                "    });",
16948                LLVMWithBeforeLambdaBody);
16949   verifyFormat("auto fct_SLS_None = []()\n"
16950                "{\n"
16951                "  return 17;\n"
16952                "};",
16953                LLVMWithBeforeLambdaBody);
16954   verifyFormat("TwoNestedLambdas_SLS_None(\n"
16955                "    []()\n"
16956                "    {\n"
16957                "      return Call(\n"
16958                "          []()\n"
16959                "          {\n"
16960                "            return 17;\n"
16961                "          });\n"
16962                "    });",
16963                LLVMWithBeforeLambdaBody);
16964   verifyFormat("void Fct()\n"
16965                "{\n"
16966                "  return {[]()\n"
16967                "          {\n"
16968                "            return 17;\n"
16969                "          }};\n"
16970                "}",
16971                LLVMWithBeforeLambdaBody);
16972 
16973   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
16974       FormatStyle::ShortLambdaStyle::SLS_Empty;
16975   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
16976                "    []()\n"
16977                "    {\n"
16978                "      return 17;\n"
16979                "    });",
16980                LLVMWithBeforeLambdaBody);
16981   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
16982                LLVMWithBeforeLambdaBody);
16983   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
16984                "ongFunctionName_SLS_Empty(\n"
16985                "    []() {});",
16986                LLVMWithBeforeLambdaBody);
16987   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
16988                "                                []()\n"
16989                "                                {\n"
16990                "                                  return 17;\n"
16991                "                                });",
16992                LLVMWithBeforeLambdaBody);
16993   verifyFormat("auto fct_SLS_Empty = []()\n"
16994                "{\n"
16995                "  return 17;\n"
16996                "};",
16997                LLVMWithBeforeLambdaBody);
16998   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
16999                "    []()\n"
17000                "    {\n"
17001                "      return Call([]() {});\n"
17002                "    });",
17003                LLVMWithBeforeLambdaBody);
17004   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
17005                "                           []()\n"
17006                "                           {\n"
17007                "                             return Call([]() {});\n"
17008                "                           });",
17009                LLVMWithBeforeLambdaBody);
17010   verifyFormat(
17011       "FctWithLongLineInLambda_SLS_Empty(\n"
17012       "    []()\n"
17013       "    {\n"
17014       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17015       "                               AndShouldNotBeConsiderAsInline,\n"
17016       "                               LambdaBodyMustBeBreak);\n"
17017       "    });",
17018       LLVMWithBeforeLambdaBody);
17019 
17020   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17021       FormatStyle::ShortLambdaStyle::SLS_Inline;
17022   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
17023                LLVMWithBeforeLambdaBody);
17024   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
17025                LLVMWithBeforeLambdaBody);
17026   verifyFormat("auto fct_SLS_Inline = []()\n"
17027                "{\n"
17028                "  return 17;\n"
17029                "};",
17030                LLVMWithBeforeLambdaBody);
17031   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
17032                "17; }); });",
17033                LLVMWithBeforeLambdaBody);
17034   verifyFormat(
17035       "FctWithLongLineInLambda_SLS_Inline(\n"
17036       "    []()\n"
17037       "    {\n"
17038       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17039       "                               AndShouldNotBeConsiderAsInline,\n"
17040       "                               LambdaBodyMustBeBreak);\n"
17041       "    });",
17042       LLVMWithBeforeLambdaBody);
17043   verifyFormat("FctWithMultipleParams_SLS_Inline("
17044                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
17045                "                                 []() { return 17; });",
17046                LLVMWithBeforeLambdaBody);
17047   verifyFormat(
17048       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
17049       LLVMWithBeforeLambdaBody);
17050 
17051   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17052       FormatStyle::ShortLambdaStyle::SLS_All;
17053   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
17054                LLVMWithBeforeLambdaBody);
17055   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
17056                LLVMWithBeforeLambdaBody);
17057   verifyFormat("auto fct_SLS_All = []() { return 17; };",
17058                LLVMWithBeforeLambdaBody);
17059   verifyFormat("FctWithOneParam_SLS_All(\n"
17060                "    []()\n"
17061                "    {\n"
17062                "      // A cool function...\n"
17063                "      return 43;\n"
17064                "    });",
17065                LLVMWithBeforeLambdaBody);
17066   verifyFormat("FctWithMultipleParams_SLS_All("
17067                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
17068                "                              []() { return 17; });",
17069                LLVMWithBeforeLambdaBody);
17070   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
17071                LLVMWithBeforeLambdaBody);
17072   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
17073                LLVMWithBeforeLambdaBody);
17074   verifyFormat(
17075       "FctWithLongLineInLambda_SLS_All(\n"
17076       "    []()\n"
17077       "    {\n"
17078       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17079       "                               AndShouldNotBeConsiderAsInline,\n"
17080       "                               LambdaBodyMustBeBreak);\n"
17081       "    });",
17082       LLVMWithBeforeLambdaBody);
17083   verifyFormat(
17084       "auto fct_SLS_All = []()\n"
17085       "{\n"
17086       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17087       "                           AndShouldNotBeConsiderAsInline,\n"
17088       "                           LambdaBodyMustBeBreak);\n"
17089       "};",
17090       LLVMWithBeforeLambdaBody);
17091   LLVMWithBeforeLambdaBody.BinPackParameters = false;
17092   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
17093                LLVMWithBeforeLambdaBody);
17094   verifyFormat(
17095       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
17096       "                                FirstParam,\n"
17097       "                                SecondParam,\n"
17098       "                                ThirdParam,\n"
17099       "                                FourthParam);",
17100       LLVMWithBeforeLambdaBody);
17101   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
17102                "    []() { return "
17103                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
17104                "    FirstParam,\n"
17105                "    SecondParam,\n"
17106                "    ThirdParam,\n"
17107                "    FourthParam);",
17108                LLVMWithBeforeLambdaBody);
17109   verifyFormat(
17110       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
17111       "                                SecondParam,\n"
17112       "                                ThirdParam,\n"
17113       "                                FourthParam,\n"
17114       "                                []() { return SomeValueNotSoLong; });",
17115       LLVMWithBeforeLambdaBody);
17116   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
17117                "    []()\n"
17118                "    {\n"
17119                "      return "
17120                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
17121                "eConsiderAsInline;\n"
17122                "    });",
17123                LLVMWithBeforeLambdaBody);
17124   verifyFormat(
17125       "FctWithLongLineInLambda_SLS_All(\n"
17126       "    []()\n"
17127       "    {\n"
17128       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17129       "                               AndShouldNotBeConsiderAsInline,\n"
17130       "                               LambdaBodyMustBeBreak);\n"
17131       "    });",
17132       LLVMWithBeforeLambdaBody);
17133   verifyFormat("FctWithTwoParams_SLS_All(\n"
17134                "    []()\n"
17135                "    {\n"
17136                "      // A cool function...\n"
17137                "      return 43;\n"
17138                "    },\n"
17139                "    87);",
17140                LLVMWithBeforeLambdaBody);
17141   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
17142                LLVMWithBeforeLambdaBody);
17143   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
17144                LLVMWithBeforeLambdaBody);
17145   verifyFormat(
17146       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
17147       LLVMWithBeforeLambdaBody);
17148   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
17149                "}); }, x);",
17150                LLVMWithBeforeLambdaBody);
17151   verifyFormat("TwoNestedLambdas_SLS_All(\n"
17152                "    []()\n"
17153                "    {\n"
17154                "      // A cool function...\n"
17155                "      return Call([]() { return 17; });\n"
17156                "    });",
17157                LLVMWithBeforeLambdaBody);
17158   verifyFormat("TwoNestedLambdas_SLS_All(\n"
17159                "    []()\n"
17160                "    {\n"
17161                "      return Call(\n"
17162                "          []()\n"
17163                "          {\n"
17164                "            // A cool function...\n"
17165                "            return 17;\n"
17166                "          });\n"
17167                "    });",
17168                LLVMWithBeforeLambdaBody);
17169 }
17170 
17171 TEST_F(FormatTest, LambdaWithLineComments) {
17172   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
17173   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
17174   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
17175   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17176       FormatStyle::ShortLambdaStyle::SLS_All;
17177 
17178   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
17179   verifyFormat("auto k = []() // comment\n"
17180                "{ return; }",
17181                LLVMWithBeforeLambdaBody);
17182   verifyFormat("auto k = []() /* comment */ { return; }",
17183                LLVMWithBeforeLambdaBody);
17184   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
17185                LLVMWithBeforeLambdaBody);
17186   verifyFormat("auto k = []() // X\n"
17187                "{ return; }",
17188                LLVMWithBeforeLambdaBody);
17189   verifyFormat(
17190       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
17191       "{ return; }",
17192       LLVMWithBeforeLambdaBody);
17193 }
17194 
17195 TEST_F(FormatTest, EmptyLinesInLambdas) {
17196   verifyFormat("auto lambda = []() {\n"
17197                "  x(); //\n"
17198                "};",
17199                "auto lambda = []() {\n"
17200                "\n"
17201                "  x(); //\n"
17202                "\n"
17203                "};");
17204 }
17205 
17206 TEST_F(FormatTest, FormatsBlocks) {
17207   FormatStyle ShortBlocks = getLLVMStyle();
17208   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
17209   verifyFormat("int (^Block)(int, int);", ShortBlocks);
17210   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
17211   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
17212   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
17213   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
17214   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
17215 
17216   verifyFormat("foo(^{ bar(); });", ShortBlocks);
17217   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
17218   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
17219 
17220   verifyFormat("[operation setCompletionBlock:^{\n"
17221                "  [self onOperationDone];\n"
17222                "}];");
17223   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
17224                "  [self onOperationDone];\n"
17225                "}]};");
17226   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
17227                "  f();\n"
17228                "}];");
17229   verifyFormat("int a = [operation block:^int(int *i) {\n"
17230                "  return 1;\n"
17231                "}];");
17232   verifyFormat("[myObject doSomethingWith:arg1\n"
17233                "                      aaa:^int(int *a) {\n"
17234                "                        return 1;\n"
17235                "                      }\n"
17236                "                      bbb:f(a * bbbbbbbb)];");
17237 
17238   verifyFormat("[operation setCompletionBlock:^{\n"
17239                "  [self.delegate newDataAvailable];\n"
17240                "}];",
17241                getLLVMStyleWithColumns(60));
17242   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
17243                "  NSString *path = [self sessionFilePath];\n"
17244                "  if (path) {\n"
17245                "    // ...\n"
17246                "  }\n"
17247                "});");
17248   verifyFormat("[[SessionService sharedService]\n"
17249                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
17250                "      if (window) {\n"
17251                "        [self windowDidLoad:window];\n"
17252                "      } else {\n"
17253                "        [self errorLoadingWindow];\n"
17254                "      }\n"
17255                "    }];");
17256   verifyFormat("void (^largeBlock)(void) = ^{\n"
17257                "  // ...\n"
17258                "};\n",
17259                getLLVMStyleWithColumns(40));
17260   verifyFormat("[[SessionService sharedService]\n"
17261                "    loadWindowWithCompletionBlock: //\n"
17262                "        ^(SessionWindow *window) {\n"
17263                "          if (window) {\n"
17264                "            [self windowDidLoad:window];\n"
17265                "          } else {\n"
17266                "            [self errorLoadingWindow];\n"
17267                "          }\n"
17268                "        }];",
17269                getLLVMStyleWithColumns(60));
17270   verifyFormat("[myObject doSomethingWith:arg1\n"
17271                "    firstBlock:^(Foo *a) {\n"
17272                "      // ...\n"
17273                "      int i;\n"
17274                "    }\n"
17275                "    secondBlock:^(Bar *b) {\n"
17276                "      // ...\n"
17277                "      int i;\n"
17278                "    }\n"
17279                "    thirdBlock:^Foo(Bar *b) {\n"
17280                "      // ...\n"
17281                "      int i;\n"
17282                "    }];");
17283   verifyFormat("[myObject doSomethingWith:arg1\n"
17284                "               firstBlock:-1\n"
17285                "              secondBlock:^(Bar *b) {\n"
17286                "                // ...\n"
17287                "                int i;\n"
17288                "              }];");
17289 
17290   verifyFormat("f(^{\n"
17291                "  @autoreleasepool {\n"
17292                "    if (a) {\n"
17293                "      g();\n"
17294                "    }\n"
17295                "  }\n"
17296                "});");
17297   verifyFormat("Block b = ^int *(A *a, B *b) {}");
17298   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
17299                "};");
17300 
17301   FormatStyle FourIndent = getLLVMStyle();
17302   FourIndent.ObjCBlockIndentWidth = 4;
17303   verifyFormat("[operation setCompletionBlock:^{\n"
17304                "    [self onOperationDone];\n"
17305                "}];",
17306                FourIndent);
17307 }
17308 
17309 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
17310   FormatStyle ZeroColumn = getLLVMStyle();
17311   ZeroColumn.ColumnLimit = 0;
17312 
17313   verifyFormat("[[SessionService sharedService] "
17314                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
17315                "  if (window) {\n"
17316                "    [self windowDidLoad:window];\n"
17317                "  } else {\n"
17318                "    [self errorLoadingWindow];\n"
17319                "  }\n"
17320                "}];",
17321                ZeroColumn);
17322   EXPECT_EQ("[[SessionService sharedService]\n"
17323             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
17324             "      if (window) {\n"
17325             "        [self windowDidLoad:window];\n"
17326             "      } else {\n"
17327             "        [self errorLoadingWindow];\n"
17328             "      }\n"
17329             "    }];",
17330             format("[[SessionService sharedService]\n"
17331                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
17332                    "                if (window) {\n"
17333                    "    [self windowDidLoad:window];\n"
17334                    "  } else {\n"
17335                    "    [self errorLoadingWindow];\n"
17336                    "  }\n"
17337                    "}];",
17338                    ZeroColumn));
17339   verifyFormat("[myObject doSomethingWith:arg1\n"
17340                "    firstBlock:^(Foo *a) {\n"
17341                "      // ...\n"
17342                "      int i;\n"
17343                "    }\n"
17344                "    secondBlock:^(Bar *b) {\n"
17345                "      // ...\n"
17346                "      int i;\n"
17347                "    }\n"
17348                "    thirdBlock:^Foo(Bar *b) {\n"
17349                "      // ...\n"
17350                "      int i;\n"
17351                "    }];",
17352                ZeroColumn);
17353   verifyFormat("f(^{\n"
17354                "  @autoreleasepool {\n"
17355                "    if (a) {\n"
17356                "      g();\n"
17357                "    }\n"
17358                "  }\n"
17359                "});",
17360                ZeroColumn);
17361   verifyFormat("void (^largeBlock)(void) = ^{\n"
17362                "  // ...\n"
17363                "};",
17364                ZeroColumn);
17365 
17366   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
17367   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
17368             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
17369   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
17370   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
17371             "  int i;\n"
17372             "};",
17373             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
17374 }
17375 
17376 TEST_F(FormatTest, SupportsCRLF) {
17377   EXPECT_EQ("int a;\r\n"
17378             "int b;\r\n"
17379             "int c;\r\n",
17380             format("int a;\r\n"
17381                    "  int b;\r\n"
17382                    "    int c;\r\n",
17383                    getLLVMStyle()));
17384   EXPECT_EQ("int a;\r\n"
17385             "int b;\r\n"
17386             "int c;\r\n",
17387             format("int a;\r\n"
17388                    "  int b;\n"
17389                    "    int c;\r\n",
17390                    getLLVMStyle()));
17391   EXPECT_EQ("int a;\n"
17392             "int b;\n"
17393             "int c;\n",
17394             format("int a;\r\n"
17395                    "  int b;\n"
17396                    "    int c;\n",
17397                    getLLVMStyle()));
17398   EXPECT_EQ("\"aaaaaaa \"\r\n"
17399             "\"bbbbbbb\";\r\n",
17400             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
17401   EXPECT_EQ("#define A \\\r\n"
17402             "  b;      \\\r\n"
17403             "  c;      \\\r\n"
17404             "  d;\r\n",
17405             format("#define A \\\r\n"
17406                    "  b; \\\r\n"
17407                    "  c; d; \r\n",
17408                    getGoogleStyle()));
17409 
17410   EXPECT_EQ("/*\r\n"
17411             "multi line block comments\r\n"
17412             "should not introduce\r\n"
17413             "an extra carriage return\r\n"
17414             "*/\r\n",
17415             format("/*\r\n"
17416                    "multi line block comments\r\n"
17417                    "should not introduce\r\n"
17418                    "an extra carriage return\r\n"
17419                    "*/\r\n"));
17420   EXPECT_EQ("/*\r\n"
17421             "\r\n"
17422             "*/",
17423             format("/*\r\n"
17424                    "    \r\r\r\n"
17425                    "*/"));
17426 
17427   FormatStyle style = getLLVMStyle();
17428 
17429   style.DeriveLineEnding = true;
17430   style.UseCRLF = false;
17431   EXPECT_EQ("union FooBarBazQux {\n"
17432             "  int foo;\n"
17433             "  int bar;\n"
17434             "  int baz;\n"
17435             "};",
17436             format("union FooBarBazQux {\r\n"
17437                    "  int foo;\n"
17438                    "  int bar;\r\n"
17439                    "  int baz;\n"
17440                    "};",
17441                    style));
17442   style.UseCRLF = true;
17443   EXPECT_EQ("union FooBarBazQux {\r\n"
17444             "  int foo;\r\n"
17445             "  int bar;\r\n"
17446             "  int baz;\r\n"
17447             "};",
17448             format("union FooBarBazQux {\r\n"
17449                    "  int foo;\n"
17450                    "  int bar;\r\n"
17451                    "  int baz;\n"
17452                    "};",
17453                    style));
17454 
17455   style.DeriveLineEnding = false;
17456   style.UseCRLF = false;
17457   EXPECT_EQ("union FooBarBazQux {\n"
17458             "  int foo;\n"
17459             "  int bar;\n"
17460             "  int baz;\n"
17461             "  int qux;\n"
17462             "};",
17463             format("union FooBarBazQux {\r\n"
17464                    "  int foo;\n"
17465                    "  int bar;\r\n"
17466                    "  int baz;\n"
17467                    "  int qux;\r\n"
17468                    "};",
17469                    style));
17470   style.UseCRLF = true;
17471   EXPECT_EQ("union FooBarBazQux {\r\n"
17472             "  int foo;\r\n"
17473             "  int bar;\r\n"
17474             "  int baz;\r\n"
17475             "  int qux;\r\n"
17476             "};",
17477             format("union FooBarBazQux {\r\n"
17478                    "  int foo;\n"
17479                    "  int bar;\r\n"
17480                    "  int baz;\n"
17481                    "  int qux;\n"
17482                    "};",
17483                    style));
17484 
17485   style.DeriveLineEnding = true;
17486   style.UseCRLF = false;
17487   EXPECT_EQ("union FooBarBazQux {\r\n"
17488             "  int foo;\r\n"
17489             "  int bar;\r\n"
17490             "  int baz;\r\n"
17491             "  int qux;\r\n"
17492             "};",
17493             format("union FooBarBazQux {\r\n"
17494                    "  int foo;\n"
17495                    "  int bar;\r\n"
17496                    "  int baz;\n"
17497                    "  int qux;\r\n"
17498                    "};",
17499                    style));
17500   style.UseCRLF = true;
17501   EXPECT_EQ("union FooBarBazQux {\n"
17502             "  int foo;\n"
17503             "  int bar;\n"
17504             "  int baz;\n"
17505             "  int qux;\n"
17506             "};",
17507             format("union FooBarBazQux {\r\n"
17508                    "  int foo;\n"
17509                    "  int bar;\r\n"
17510                    "  int baz;\n"
17511                    "  int qux;\n"
17512                    "};",
17513                    style));
17514 }
17515 
17516 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
17517   verifyFormat("MY_CLASS(C) {\n"
17518                "  int i;\n"
17519                "  int j;\n"
17520                "};");
17521 }
17522 
17523 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
17524   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
17525   TwoIndent.ContinuationIndentWidth = 2;
17526 
17527   EXPECT_EQ("int i =\n"
17528             "  longFunction(\n"
17529             "    arg);",
17530             format("int i = longFunction(arg);", TwoIndent));
17531 
17532   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
17533   SixIndent.ContinuationIndentWidth = 6;
17534 
17535   EXPECT_EQ("int i =\n"
17536             "      longFunction(\n"
17537             "            arg);",
17538             format("int i = longFunction(arg);", SixIndent));
17539 }
17540 
17541 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
17542   FormatStyle Style = getLLVMStyle();
17543   verifyFormat("int Foo::getter(\n"
17544                "    //\n"
17545                ") const {\n"
17546                "  return foo;\n"
17547                "}",
17548                Style);
17549   verifyFormat("void Foo::setter(\n"
17550                "    //\n"
17551                ") {\n"
17552                "  foo = 1;\n"
17553                "}",
17554                Style);
17555 }
17556 
17557 TEST_F(FormatTest, SpacesInAngles) {
17558   FormatStyle Spaces = getLLVMStyle();
17559   Spaces.SpacesInAngles = true;
17560 
17561   verifyFormat("static_cast< int >(arg);", Spaces);
17562   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
17563   verifyFormat("f< int, float >();", Spaces);
17564   verifyFormat("template <> g() {}", Spaces);
17565   verifyFormat("template < std::vector< int > > f() {}", Spaces);
17566   verifyFormat("std::function< void(int, int) > fct;", Spaces);
17567   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
17568                Spaces);
17569 
17570   Spaces.Standard = FormatStyle::LS_Cpp03;
17571   Spaces.SpacesInAngles = true;
17572   verifyFormat("A< A< int > >();", Spaces);
17573 
17574   Spaces.SpacesInAngles = false;
17575   verifyFormat("A<A<int> >();", Spaces);
17576 
17577   Spaces.Standard = FormatStyle::LS_Cpp11;
17578   Spaces.SpacesInAngles = true;
17579   verifyFormat("A< A< int > >();", Spaces);
17580 
17581   Spaces.SpacesInAngles = false;
17582   verifyFormat("A<A<int>>();", Spaces);
17583 }
17584 
17585 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
17586   FormatStyle Style = getLLVMStyle();
17587   Style.SpaceAfterTemplateKeyword = false;
17588   verifyFormat("template<int> void foo();", Style);
17589 }
17590 
17591 TEST_F(FormatTest, TripleAngleBrackets) {
17592   verifyFormat("f<<<1, 1>>>();");
17593   verifyFormat("f<<<1, 1, 1, s>>>();");
17594   verifyFormat("f<<<a, b, c, d>>>();");
17595   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
17596   verifyFormat("f<param><<<1, 1>>>();");
17597   verifyFormat("f<1><<<1, 1>>>();");
17598   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
17599   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
17600                "aaaaaaaaaaa<<<\n    1, 1>>>();");
17601   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
17602                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
17603 }
17604 
17605 TEST_F(FormatTest, MergeLessLessAtEnd) {
17606   verifyFormat("<<");
17607   EXPECT_EQ("< < <", format("\\\n<<<"));
17608   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
17609                "aaallvm::outs() <<");
17610   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
17611                "aaaallvm::outs()\n    <<");
17612 }
17613 
17614 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
17615   std::string code = "#if A\n"
17616                      "#if B\n"
17617                      "a.\n"
17618                      "#endif\n"
17619                      "    a = 1;\n"
17620                      "#else\n"
17621                      "#endif\n"
17622                      "#if C\n"
17623                      "#else\n"
17624                      "#endif\n";
17625   EXPECT_EQ(code, format(code));
17626 }
17627 
17628 TEST_F(FormatTest, HandleConflictMarkers) {
17629   // Git/SVN conflict markers.
17630   EXPECT_EQ("int a;\n"
17631             "void f() {\n"
17632             "  callme(some(parameter1,\n"
17633             "<<<<<<< text by the vcs\n"
17634             "              parameter2),\n"
17635             "||||||| text by the vcs\n"
17636             "              parameter2),\n"
17637             "         parameter3,\n"
17638             "======= text by the vcs\n"
17639             "              parameter2, parameter3),\n"
17640             ">>>>>>> text by the vcs\n"
17641             "         otherparameter);\n",
17642             format("int a;\n"
17643                    "void f() {\n"
17644                    "  callme(some(parameter1,\n"
17645                    "<<<<<<< text by the vcs\n"
17646                    "  parameter2),\n"
17647                    "||||||| text by the vcs\n"
17648                    "  parameter2),\n"
17649                    "  parameter3,\n"
17650                    "======= text by the vcs\n"
17651                    "  parameter2,\n"
17652                    "  parameter3),\n"
17653                    ">>>>>>> text by the vcs\n"
17654                    "  otherparameter);\n"));
17655 
17656   // Perforce markers.
17657   EXPECT_EQ("void f() {\n"
17658             "  function(\n"
17659             ">>>> text by the vcs\n"
17660             "      parameter,\n"
17661             "==== text by the vcs\n"
17662             "      parameter,\n"
17663             "==== text by the vcs\n"
17664             "      parameter,\n"
17665             "<<<< text by the vcs\n"
17666             "      parameter);\n",
17667             format("void f() {\n"
17668                    "  function(\n"
17669                    ">>>> text by the vcs\n"
17670                    "  parameter,\n"
17671                    "==== text by the vcs\n"
17672                    "  parameter,\n"
17673                    "==== text by the vcs\n"
17674                    "  parameter,\n"
17675                    "<<<< text by the vcs\n"
17676                    "  parameter);\n"));
17677 
17678   EXPECT_EQ("<<<<<<<\n"
17679             "|||||||\n"
17680             "=======\n"
17681             ">>>>>>>",
17682             format("<<<<<<<\n"
17683                    "|||||||\n"
17684                    "=======\n"
17685                    ">>>>>>>"));
17686 
17687   EXPECT_EQ("<<<<<<<\n"
17688             "|||||||\n"
17689             "int i;\n"
17690             "=======\n"
17691             ">>>>>>>",
17692             format("<<<<<<<\n"
17693                    "|||||||\n"
17694                    "int i;\n"
17695                    "=======\n"
17696                    ">>>>>>>"));
17697 
17698   // FIXME: Handle parsing of macros around conflict markers correctly:
17699   EXPECT_EQ("#define Macro \\\n"
17700             "<<<<<<<\n"
17701             "Something \\\n"
17702             "|||||||\n"
17703             "Else \\\n"
17704             "=======\n"
17705             "Other \\\n"
17706             ">>>>>>>\n"
17707             "    End int i;\n",
17708             format("#define Macro \\\n"
17709                    "<<<<<<<\n"
17710                    "  Something \\\n"
17711                    "|||||||\n"
17712                    "  Else \\\n"
17713                    "=======\n"
17714                    "  Other \\\n"
17715                    ">>>>>>>\n"
17716                    "  End\n"
17717                    "int i;\n"));
17718 }
17719 
17720 TEST_F(FormatTest, DisableRegions) {
17721   EXPECT_EQ("int i;\n"
17722             "// clang-format off\n"
17723             "  int j;\n"
17724             "// clang-format on\n"
17725             "int k;",
17726             format(" int  i;\n"
17727                    "   // clang-format off\n"
17728                    "  int j;\n"
17729                    " // clang-format on\n"
17730                    "   int   k;"));
17731   EXPECT_EQ("int i;\n"
17732             "/* clang-format off */\n"
17733             "  int j;\n"
17734             "/* clang-format on */\n"
17735             "int k;",
17736             format(" int  i;\n"
17737                    "   /* clang-format off */\n"
17738                    "  int j;\n"
17739                    " /* clang-format on */\n"
17740                    "   int   k;"));
17741 
17742   // Don't reflow comments within disabled regions.
17743   EXPECT_EQ("// clang-format off\n"
17744             "// long long long long long long line\n"
17745             "/* clang-format on */\n"
17746             "/* long long long\n"
17747             " * long long long\n"
17748             " * line */\n"
17749             "int i;\n"
17750             "/* clang-format off */\n"
17751             "/* long long long long long long line */\n",
17752             format("// clang-format off\n"
17753                    "// long long long long long long line\n"
17754                    "/* clang-format on */\n"
17755                    "/* long long long long long long line */\n"
17756                    "int i;\n"
17757                    "/* clang-format off */\n"
17758                    "/* long long long long long long line */\n",
17759                    getLLVMStyleWithColumns(20)));
17760 }
17761 
17762 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
17763   format("? ) =");
17764   verifyNoCrash("#define a\\\n /**/}");
17765 }
17766 
17767 TEST_F(FormatTest, FormatsTableGenCode) {
17768   FormatStyle Style = getLLVMStyle();
17769   Style.Language = FormatStyle::LK_TableGen;
17770   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
17771 }
17772 
17773 TEST_F(FormatTest, ArrayOfTemplates) {
17774   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
17775             format("auto a = new unique_ptr<int > [ 10];"));
17776 
17777   FormatStyle Spaces = getLLVMStyle();
17778   Spaces.SpacesInSquareBrackets = true;
17779   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
17780             format("auto a = new unique_ptr<int > [10];", Spaces));
17781 }
17782 
17783 TEST_F(FormatTest, ArrayAsTemplateType) {
17784   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
17785             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
17786 
17787   FormatStyle Spaces = getLLVMStyle();
17788   Spaces.SpacesInSquareBrackets = true;
17789   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
17790             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
17791 }
17792 
17793 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
17794 
17795 TEST(FormatStyle, GetStyleWithEmptyFileName) {
17796   llvm::vfs::InMemoryFileSystem FS;
17797   auto Style1 = getStyle("file", "", "Google", "", &FS);
17798   ASSERT_TRUE((bool)Style1);
17799   ASSERT_EQ(*Style1, getGoogleStyle());
17800 }
17801 
17802 TEST(FormatStyle, GetStyleOfFile) {
17803   llvm::vfs::InMemoryFileSystem FS;
17804   // Test 1: format file in the same directory.
17805   ASSERT_TRUE(
17806       FS.addFile("/a/.clang-format", 0,
17807                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
17808   ASSERT_TRUE(
17809       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
17810   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
17811   ASSERT_TRUE((bool)Style1);
17812   ASSERT_EQ(*Style1, getLLVMStyle());
17813 
17814   // Test 2.1: fallback to default.
17815   ASSERT_TRUE(
17816       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
17817   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
17818   ASSERT_TRUE((bool)Style2);
17819   ASSERT_EQ(*Style2, getMozillaStyle());
17820 
17821   // Test 2.2: no format on 'none' fallback style.
17822   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
17823   ASSERT_TRUE((bool)Style2);
17824   ASSERT_EQ(*Style2, getNoStyle());
17825 
17826   // Test 2.3: format if config is found with no based style while fallback is
17827   // 'none'.
17828   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
17829                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
17830   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
17831   ASSERT_TRUE((bool)Style2);
17832   ASSERT_EQ(*Style2, getLLVMStyle());
17833 
17834   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
17835   Style2 = getStyle("{}", "a.h", "none", "", &FS);
17836   ASSERT_TRUE((bool)Style2);
17837   ASSERT_EQ(*Style2, getLLVMStyle());
17838 
17839   // Test 3: format file in parent directory.
17840   ASSERT_TRUE(
17841       FS.addFile("/c/.clang-format", 0,
17842                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
17843   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
17844                          llvm::MemoryBuffer::getMemBuffer("int i;")));
17845   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
17846   ASSERT_TRUE((bool)Style3);
17847   ASSERT_EQ(*Style3, getGoogleStyle());
17848 
17849   // Test 4: error on invalid fallback style
17850   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
17851   ASSERT_FALSE((bool)Style4);
17852   llvm::consumeError(Style4.takeError());
17853 
17854   // Test 5: error on invalid yaml on command line
17855   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
17856   ASSERT_FALSE((bool)Style5);
17857   llvm::consumeError(Style5.takeError());
17858 
17859   // Test 6: error on invalid style
17860   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
17861   ASSERT_FALSE((bool)Style6);
17862   llvm::consumeError(Style6.takeError());
17863 
17864   // Test 7: found config file, error on parsing it
17865   ASSERT_TRUE(
17866       FS.addFile("/d/.clang-format", 0,
17867                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
17868                                                   "InvalidKey: InvalidValue")));
17869   ASSERT_TRUE(
17870       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
17871   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
17872   ASSERT_FALSE((bool)Style7a);
17873   llvm::consumeError(Style7a.takeError());
17874 
17875   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
17876   ASSERT_TRUE((bool)Style7b);
17877 
17878   // Test 8: inferred per-language defaults apply.
17879   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
17880   ASSERT_TRUE((bool)StyleTd);
17881   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
17882 }
17883 
17884 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
17885   // Column limit is 20.
17886   std::string Code = "Type *a =\n"
17887                      "    new Type();\n"
17888                      "g(iiiii, 0, jjjjj,\n"
17889                      "  0, kkkkk, 0, mm);\n"
17890                      "int  bad     = format   ;";
17891   std::string Expected = "auto a = new Type();\n"
17892                          "g(iiiii, nullptr,\n"
17893                          "  jjjjj, nullptr,\n"
17894                          "  kkkkk, nullptr,\n"
17895                          "  mm);\n"
17896                          "int  bad     = format   ;";
17897   FileID ID = Context.createInMemoryFile("format.cpp", Code);
17898   tooling::Replacements Replaces = toReplacements(
17899       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
17900                             "auto "),
17901        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
17902                             "nullptr"),
17903        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
17904                             "nullptr"),
17905        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
17906                             "nullptr")});
17907 
17908   format::FormatStyle Style = format::getLLVMStyle();
17909   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
17910   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
17911   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
17912       << llvm::toString(FormattedReplaces.takeError()) << "\n";
17913   auto Result = applyAllReplacements(Code, *FormattedReplaces);
17914   EXPECT_TRUE(static_cast<bool>(Result));
17915   EXPECT_EQ(Expected, *Result);
17916 }
17917 
17918 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
17919   std::string Code = "#include \"a.h\"\n"
17920                      "#include \"c.h\"\n"
17921                      "\n"
17922                      "int main() {\n"
17923                      "  return 0;\n"
17924                      "}";
17925   std::string Expected = "#include \"a.h\"\n"
17926                          "#include \"b.h\"\n"
17927                          "#include \"c.h\"\n"
17928                          "\n"
17929                          "int main() {\n"
17930                          "  return 0;\n"
17931                          "}";
17932   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
17933   tooling::Replacements Replaces = toReplacements(
17934       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
17935                             "#include \"b.h\"\n")});
17936 
17937   format::FormatStyle Style = format::getLLVMStyle();
17938   Style.SortIncludes = true;
17939   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
17940   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
17941       << llvm::toString(FormattedReplaces.takeError()) << "\n";
17942   auto Result = applyAllReplacements(Code, *FormattedReplaces);
17943   EXPECT_TRUE(static_cast<bool>(Result));
17944   EXPECT_EQ(Expected, *Result);
17945 }
17946 
17947 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
17948   EXPECT_EQ("using std::cin;\n"
17949             "using std::cout;",
17950             format("using std::cout;\n"
17951                    "using std::cin;",
17952                    getGoogleStyle()));
17953 }
17954 
17955 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
17956   format::FormatStyle Style = format::getLLVMStyle();
17957   Style.Standard = FormatStyle::LS_Cpp03;
17958   // cpp03 recognize this string as identifier u8 and literal character 'a'
17959   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
17960 }
17961 
17962 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
17963   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
17964   // all modes, including C++11, C++14 and C++17
17965   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
17966 }
17967 
17968 TEST_F(FormatTest, DoNotFormatLikelyXml) {
17969   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
17970   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
17971 }
17972 
17973 TEST_F(FormatTest, StructuredBindings) {
17974   // Structured bindings is a C++17 feature.
17975   // all modes, including C++11, C++14 and C++17
17976   verifyFormat("auto [a, b] = f();");
17977   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
17978   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
17979   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
17980   EXPECT_EQ("auto const volatile [a, b] = f();",
17981             format("auto  const   volatile[a, b] = f();"));
17982   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
17983   EXPECT_EQ("auto &[a, b, c] = f();",
17984             format("auto   &[  a  ,  b,c   ] = f();"));
17985   EXPECT_EQ("auto &&[a, b, c] = f();",
17986             format("auto   &&[  a  ,  b,c   ] = f();"));
17987   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
17988   EXPECT_EQ("auto const volatile &&[a, b] = f();",
17989             format("auto  const  volatile  &&[a, b] = f();"));
17990   EXPECT_EQ("auto const &&[a, b] = f();",
17991             format("auto  const   &&  [a, b] = f();"));
17992   EXPECT_EQ("const auto &[a, b] = f();",
17993             format("const  auto  &  [a, b] = f();"));
17994   EXPECT_EQ("const auto volatile &&[a, b] = f();",
17995             format("const  auto   volatile  &&[a, b] = f();"));
17996   EXPECT_EQ("volatile const auto &&[a, b] = f();",
17997             format("volatile  const  auto   &&[a, b] = f();"));
17998   EXPECT_EQ("const auto &&[a, b] = f();",
17999             format("const  auto  &&  [a, b] = f();"));
18000 
18001   // Make sure we don't mistake structured bindings for lambdas.
18002   FormatStyle PointerMiddle = getLLVMStyle();
18003   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
18004   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
18005   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
18006   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
18007   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
18008   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
18009   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
18010   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
18011   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
18012   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
18013   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
18014   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
18015   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
18016 
18017   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
18018             format("for (const auto   &&   [a, b] : some_range) {\n}"));
18019   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
18020             format("for (const auto   &   [a, b] : some_range) {\n}"));
18021   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
18022             format("for (const auto[a, b] : some_range) {\n}"));
18023   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
18024   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
18025   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
18026   EXPECT_EQ("auto const &[x, y](expr);",
18027             format("auto  const  &  [x,y]  (expr);"));
18028   EXPECT_EQ("auto const &&[x, y](expr);",
18029             format("auto  const  &&  [x,y]  (expr);"));
18030   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
18031   EXPECT_EQ("auto const &[x, y]{expr};",
18032             format("auto  const  &  [x,y]  {expr};"));
18033   EXPECT_EQ("auto const &&[x, y]{expr};",
18034             format("auto  const  &&  [x,y]  {expr};"));
18035 
18036   format::FormatStyle Spaces = format::getLLVMStyle();
18037   Spaces.SpacesInSquareBrackets = true;
18038   verifyFormat("auto [ a, b ] = f();", Spaces);
18039   verifyFormat("auto &&[ a, b ] = f();", Spaces);
18040   verifyFormat("auto &[ a, b ] = f();", Spaces);
18041   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
18042   verifyFormat("auto const &[ a, b ] = f();", Spaces);
18043 }
18044 
18045 TEST_F(FormatTest, FileAndCode) {
18046   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
18047   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
18048   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
18049   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
18050   EXPECT_EQ(FormatStyle::LK_ObjC,
18051             guessLanguage("foo.h", "@interface Foo\n@end\n"));
18052   EXPECT_EQ(
18053       FormatStyle::LK_ObjC,
18054       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
18055   EXPECT_EQ(FormatStyle::LK_ObjC,
18056             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
18057   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
18058   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
18059   EXPECT_EQ(FormatStyle::LK_ObjC,
18060             guessLanguage("foo", "@interface Foo\n@end\n"));
18061   EXPECT_EQ(FormatStyle::LK_ObjC,
18062             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
18063   EXPECT_EQ(
18064       FormatStyle::LK_ObjC,
18065       guessLanguage("foo.h",
18066                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
18067   EXPECT_EQ(
18068       FormatStyle::LK_Cpp,
18069       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
18070 }
18071 
18072 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
18073   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
18074   EXPECT_EQ(FormatStyle::LK_ObjC,
18075             guessLanguage("foo.h", "array[[calculator getIndex]];"));
18076   EXPECT_EQ(FormatStyle::LK_Cpp,
18077             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
18078   EXPECT_EQ(
18079       FormatStyle::LK_Cpp,
18080       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
18081   EXPECT_EQ(FormatStyle::LK_ObjC,
18082             guessLanguage("foo.h", "[[noreturn foo] bar];"));
18083   EXPECT_EQ(FormatStyle::LK_Cpp,
18084             guessLanguage("foo.h", "[[clang::fallthrough]];"));
18085   EXPECT_EQ(FormatStyle::LK_ObjC,
18086             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
18087   EXPECT_EQ(FormatStyle::LK_Cpp,
18088             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
18089   EXPECT_EQ(FormatStyle::LK_Cpp,
18090             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
18091   EXPECT_EQ(FormatStyle::LK_ObjC,
18092             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
18093   EXPECT_EQ(FormatStyle::LK_Cpp,
18094             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
18095   EXPECT_EQ(
18096       FormatStyle::LK_Cpp,
18097       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
18098   EXPECT_EQ(
18099       FormatStyle::LK_Cpp,
18100       guessLanguage("foo.h",
18101                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
18102   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
18103 }
18104 
18105 TEST_F(FormatTest, GuessLanguageWithCaret) {
18106   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
18107   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
18108   EXPECT_EQ(FormatStyle::LK_ObjC,
18109             guessLanguage("foo.h", "int(^)(char, float);"));
18110   EXPECT_EQ(FormatStyle::LK_ObjC,
18111             guessLanguage("foo.h", "int(^foo)(char, float);"));
18112   EXPECT_EQ(FormatStyle::LK_ObjC,
18113             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
18114   EXPECT_EQ(FormatStyle::LK_ObjC,
18115             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
18116   EXPECT_EQ(
18117       FormatStyle::LK_ObjC,
18118       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
18119 }
18120 
18121 TEST_F(FormatTest, GuessLanguageWithPragmas) {
18122   EXPECT_EQ(FormatStyle::LK_Cpp,
18123             guessLanguage("foo.h", "__pragma(warning(disable:))"));
18124   EXPECT_EQ(FormatStyle::LK_Cpp,
18125             guessLanguage("foo.h", "#pragma(warning(disable:))"));
18126   EXPECT_EQ(FormatStyle::LK_Cpp,
18127             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
18128 }
18129 
18130 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
18131   // ASM symbolic names are identifiers that must be surrounded by [] without
18132   // space in between:
18133   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
18134 
18135   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
18136   verifyFormat(R"(//
18137 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
18138 )");
18139 
18140   // A list of several ASM symbolic names.
18141   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
18142 
18143   // ASM symbolic names in inline ASM with inputs and outputs.
18144   verifyFormat(R"(//
18145 asm("cmoveq %1, %2, %[result]"
18146     : [result] "=r"(result)
18147     : "r"(test), "r"(new), "[result]"(old));
18148 )");
18149 
18150   // ASM symbolic names in inline ASM with no outputs.
18151   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
18152 }
18153 
18154 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
18155   EXPECT_EQ(FormatStyle::LK_Cpp,
18156             guessLanguage("foo.h", "void f() {\n"
18157                                    "  asm (\"mov %[e], %[d]\"\n"
18158                                    "     : [d] \"=rm\" (d)\n"
18159                                    "       [e] \"rm\" (*e));\n"
18160                                    "}"));
18161   EXPECT_EQ(FormatStyle::LK_Cpp,
18162             guessLanguage("foo.h", "void f() {\n"
18163                                    "  _asm (\"mov %[e], %[d]\"\n"
18164                                    "     : [d] \"=rm\" (d)\n"
18165                                    "       [e] \"rm\" (*e));\n"
18166                                    "}"));
18167   EXPECT_EQ(FormatStyle::LK_Cpp,
18168             guessLanguage("foo.h", "void f() {\n"
18169                                    "  __asm (\"mov %[e], %[d]\"\n"
18170                                    "     : [d] \"=rm\" (d)\n"
18171                                    "       [e] \"rm\" (*e));\n"
18172                                    "}"));
18173   EXPECT_EQ(FormatStyle::LK_Cpp,
18174             guessLanguage("foo.h", "void f() {\n"
18175                                    "  __asm__ (\"mov %[e], %[d]\"\n"
18176                                    "     : [d] \"=rm\" (d)\n"
18177                                    "       [e] \"rm\" (*e));\n"
18178                                    "}"));
18179   EXPECT_EQ(FormatStyle::LK_Cpp,
18180             guessLanguage("foo.h", "void f() {\n"
18181                                    "  asm (\"mov %[e], %[d]\"\n"
18182                                    "     : [d] \"=rm\" (d),\n"
18183                                    "       [e] \"rm\" (*e));\n"
18184                                    "}"));
18185   EXPECT_EQ(FormatStyle::LK_Cpp,
18186             guessLanguage("foo.h", "void f() {\n"
18187                                    "  asm volatile (\"mov %[e], %[d]\"\n"
18188                                    "     : [d] \"=rm\" (d)\n"
18189                                    "       [e] \"rm\" (*e));\n"
18190                                    "}"));
18191 }
18192 
18193 TEST_F(FormatTest, GuessLanguageWithChildLines) {
18194   EXPECT_EQ(FormatStyle::LK_Cpp,
18195             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
18196   EXPECT_EQ(FormatStyle::LK_ObjC,
18197             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
18198   EXPECT_EQ(
18199       FormatStyle::LK_Cpp,
18200       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
18201   EXPECT_EQ(
18202       FormatStyle::LK_ObjC,
18203       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
18204 }
18205 
18206 TEST_F(FormatTest, TypenameMacros) {
18207   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
18208 
18209   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
18210   FormatStyle Google = getGoogleStyleWithColumns(0);
18211   Google.TypenameMacros = TypenameMacros;
18212   verifyFormat("struct foo {\n"
18213                "  int bar;\n"
18214                "  TAILQ_ENTRY(a) bleh;\n"
18215                "};",
18216                Google);
18217 
18218   FormatStyle Macros = getLLVMStyle();
18219   Macros.TypenameMacros = TypenameMacros;
18220 
18221   verifyFormat("STACK_OF(int) a;", Macros);
18222   verifyFormat("STACK_OF(int) *a;", Macros);
18223   verifyFormat("STACK_OF(int const *) *a;", Macros);
18224   verifyFormat("STACK_OF(int *const) *a;", Macros);
18225   verifyFormat("STACK_OF(int, string) a;", Macros);
18226   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
18227   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
18228   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
18229   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
18230   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
18231   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
18232 
18233   Macros.PointerAlignment = FormatStyle::PAS_Left;
18234   verifyFormat("STACK_OF(int)* a;", Macros);
18235   verifyFormat("STACK_OF(int*)* a;", Macros);
18236   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
18237   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
18238   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
18239 }
18240 
18241 TEST_F(FormatTest, AtomicQualifier) {
18242   // Check that we treate _Atomic as a type and not a function call
18243   FormatStyle Google = getGoogleStyleWithColumns(0);
18244   verifyFormat("struct foo {\n"
18245                "  int a1;\n"
18246                "  _Atomic(a) a2;\n"
18247                "  _Atomic(_Atomic(int) *const) a3;\n"
18248                "};",
18249                Google);
18250   verifyFormat("_Atomic(uint64_t) a;");
18251   verifyFormat("_Atomic(uint64_t) *a;");
18252   verifyFormat("_Atomic(uint64_t const *) *a;");
18253   verifyFormat("_Atomic(uint64_t *const) *a;");
18254   verifyFormat("_Atomic(const uint64_t *) *a;");
18255   verifyFormat("_Atomic(uint64_t) a;");
18256   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
18257   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
18258   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
18259   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
18260 
18261   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
18262   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
18263   FormatStyle Style = getLLVMStyle();
18264   Style.PointerAlignment = FormatStyle::PAS_Left;
18265   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
18266   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
18267   verifyFormat("_Atomic(int)* a;", Style);
18268   verifyFormat("_Atomic(int*)* a;", Style);
18269   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
18270 
18271   Style.SpacesInCStyleCastParentheses = true;
18272   Style.SpacesInParentheses = false;
18273   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
18274   Style.SpacesInCStyleCastParentheses = false;
18275   Style.SpacesInParentheses = true;
18276   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
18277   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
18278 }
18279 
18280 TEST_F(FormatTest, AmbersandInLamda) {
18281   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
18282   FormatStyle AlignStyle = getLLVMStyle();
18283   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
18284   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
18285   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
18286   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
18287 }
18288 
18289 TEST_F(FormatTest, SpacesInConditionalStatement) {
18290   FormatStyle Spaces = getLLVMStyle();
18291   Spaces.SpacesInConditionalStatement = true;
18292   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
18293   verifyFormat("if ( !a )\n  return;", Spaces);
18294   verifyFormat("if ( a )\n  return;", Spaces);
18295   verifyFormat("if constexpr ( a )\n  return;", Spaces);
18296   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
18297   verifyFormat("while ( a )\n  return;", Spaces);
18298   verifyFormat("while ( (a && b) )\n  return;", Spaces);
18299   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
18300   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
18301   // Check that space on the left of "::" is inserted as expected at beginning
18302   // of condition.
18303   verifyFormat("while ( ::func() )\n  return;", Spaces);
18304 }
18305 
18306 TEST_F(FormatTest, AlternativeOperators) {
18307   // Test case for ensuring alternate operators are not
18308   // combined with their right most neighbour.
18309   verifyFormat("int a and b;");
18310   verifyFormat("int a and_eq b;");
18311   verifyFormat("int a bitand b;");
18312   verifyFormat("int a bitor b;");
18313   verifyFormat("int a compl b;");
18314   verifyFormat("int a not b;");
18315   verifyFormat("int a not_eq b;");
18316   verifyFormat("int a or b;");
18317   verifyFormat("int a xor b;");
18318   verifyFormat("int a xor_eq b;");
18319   verifyFormat("return this not_eq bitand other;");
18320   verifyFormat("bool operator not_eq(const X bitand other)");
18321 
18322   verifyFormat("int a and 5;");
18323   verifyFormat("int a and_eq 5;");
18324   verifyFormat("int a bitand 5;");
18325   verifyFormat("int a bitor 5;");
18326   verifyFormat("int a compl 5;");
18327   verifyFormat("int a not 5;");
18328   verifyFormat("int a not_eq 5;");
18329   verifyFormat("int a or 5;");
18330   verifyFormat("int a xor 5;");
18331   verifyFormat("int a xor_eq 5;");
18332 
18333   verifyFormat("int a compl(5);");
18334   verifyFormat("int a not(5);");
18335 
18336   /* FIXME handle alternate tokens
18337    * https://en.cppreference.com/w/cpp/language/operator_alternative
18338   // alternative tokens
18339   verifyFormat("compl foo();");     //  ~foo();
18340   verifyFormat("foo() <%%>;");      // foo();
18341   verifyFormat("void foo() <%%>;"); // void foo(){}
18342   verifyFormat("int a <:1:>;");     // int a[1];[
18343   verifyFormat("%:define ABC abc"); // #define ABC abc
18344   verifyFormat("%:%:");             // ##
18345   */
18346 }
18347 
18348 TEST_F(FormatTest, STLWhileNotDefineChed) {
18349   verifyFormat("#if defined(while)\n"
18350                "#define while EMIT WARNING C4005\n"
18351                "#endif // while");
18352 }
18353 
18354 TEST_F(FormatTest, OperatorSpacing) {
18355   FormatStyle Style = getLLVMStyle();
18356   Style.PointerAlignment = FormatStyle::PAS_Right;
18357   verifyFormat("Foo::operator*();", Style);
18358   verifyFormat("Foo::operator void *();", Style);
18359   verifyFormat("Foo::operator void **();", Style);
18360   verifyFormat("Foo::operator void *&();", Style);
18361   verifyFormat("Foo::operator void *&&();", Style);
18362   verifyFormat("Foo::operator()(void *);", Style);
18363   verifyFormat("Foo::operator*(void *);", Style);
18364   verifyFormat("Foo::operator*();", Style);
18365   verifyFormat("Foo::operator**();", Style);
18366   verifyFormat("Foo::operator&();", Style);
18367   verifyFormat("Foo::operator<int> *();", Style);
18368   verifyFormat("Foo::operator<Foo> *();", Style);
18369   verifyFormat("Foo::operator<int> **();", Style);
18370   verifyFormat("Foo::operator<Foo> **();", Style);
18371   verifyFormat("Foo::operator<int> &();", Style);
18372   verifyFormat("Foo::operator<Foo> &();", Style);
18373   verifyFormat("Foo::operator<int> &&();", Style);
18374   verifyFormat("Foo::operator<Foo> &&();", Style);
18375   verifyFormat("Foo::operator<int> *&();", Style);
18376   verifyFormat("Foo::operator<Foo> *&();", Style);
18377   verifyFormat("Foo::operator<int> *&&();", Style);
18378   verifyFormat("Foo::operator<Foo> *&&();", Style);
18379   verifyFormat("operator*(int (*)(), class Foo);", Style);
18380 
18381   verifyFormat("Foo::operator&();", Style);
18382   verifyFormat("Foo::operator void &();", Style);
18383   verifyFormat("Foo::operator()(void &);", Style);
18384   verifyFormat("Foo::operator&(void &);", Style);
18385   verifyFormat("Foo::operator&();", Style);
18386   verifyFormat("operator&(int (&)(), class Foo);", Style);
18387 
18388   verifyFormat("Foo::operator&&();", Style);
18389   verifyFormat("Foo::operator**();", Style);
18390   verifyFormat("Foo::operator void &&();", Style);
18391   verifyFormat("Foo::operator()(void &&);", Style);
18392   verifyFormat("Foo::operator&&(void &&);", Style);
18393   verifyFormat("Foo::operator&&();", Style);
18394   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
18395   verifyFormat("operator const nsTArrayRight<E> &()", Style);
18396   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
18397                Style);
18398   verifyFormat("operator void **()", Style);
18399   verifyFormat("operator const FooRight<Object> &()", Style);
18400   verifyFormat("operator const FooRight<Object> *()", Style);
18401   verifyFormat("operator const FooRight<Object> **()", Style);
18402   verifyFormat("operator const FooRight<Object> *&()", Style);
18403   verifyFormat("operator const FooRight<Object> *&&()", Style);
18404 
18405   Style.PointerAlignment = FormatStyle::PAS_Left;
18406   verifyFormat("Foo::operator*();", Style);
18407   verifyFormat("Foo::operator**();", Style);
18408   verifyFormat("Foo::operator void*();", Style);
18409   verifyFormat("Foo::operator void**();", Style);
18410   verifyFormat("Foo::operator void*&();", Style);
18411   verifyFormat("Foo::operator/*comment*/ void*();", Style);
18412   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
18413   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
18414   verifyFormat("Foo::operator()(void*);", Style);
18415   verifyFormat("Foo::operator*(void*);", Style);
18416   verifyFormat("Foo::operator*();", Style);
18417   verifyFormat("Foo::operator<int>*();", Style);
18418   verifyFormat("Foo::operator<Foo>*();", Style);
18419   verifyFormat("Foo::operator<int>**();", Style);
18420   verifyFormat("Foo::operator<Foo>**();", Style);
18421   verifyFormat("Foo::operator<Foo>*&();", Style);
18422   verifyFormat("Foo::operator<int>&();", Style);
18423   verifyFormat("Foo::operator<Foo>&();", Style);
18424   verifyFormat("Foo::operator<int>&&();", Style);
18425   verifyFormat("Foo::operator<Foo>&&();", Style);
18426   verifyFormat("Foo::operator<int>*&();", Style);
18427   verifyFormat("Foo::operator<Foo>*&();", Style);
18428   verifyFormat("operator*(int (*)(), class Foo);", Style);
18429 
18430   verifyFormat("Foo::operator&();", Style);
18431   verifyFormat("Foo::operator void&();", Style);
18432   verifyFormat("Foo::operator/*comment*/ void&();", Style);
18433   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
18434   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
18435   verifyFormat("Foo::operator()(void&);", Style);
18436   verifyFormat("Foo::operator&(void&);", Style);
18437   verifyFormat("Foo::operator&();", Style);
18438   verifyFormat("operator&(int (&)(), class Foo);", Style);
18439 
18440   verifyFormat("Foo::operator&&();", Style);
18441   verifyFormat("Foo::operator void&&();", Style);
18442   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
18443   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
18444   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
18445   verifyFormat("Foo::operator()(void&&);", Style);
18446   verifyFormat("Foo::operator&&(void&&);", Style);
18447   verifyFormat("Foo::operator&&();", Style);
18448   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
18449   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
18450   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
18451                Style);
18452   verifyFormat("operator void**()", Style);
18453   verifyFormat("operator const FooLeft<Object>&()", Style);
18454   verifyFormat("operator const FooLeft<Object>*()", Style);
18455   verifyFormat("operator const FooLeft<Object>**()", Style);
18456   verifyFormat("operator const FooLeft<Object>*&()", Style);
18457   verifyFormat("operator const FooLeft<Object>*&&()", Style);
18458 
18459   // PR45107
18460   verifyFormat("operator Vector<String>&();", Style);
18461   verifyFormat("operator const Vector<String>&();", Style);
18462   verifyFormat("operator foo::Bar*();", Style);
18463   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
18464   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
18465                Style);
18466 
18467   Style.PointerAlignment = FormatStyle::PAS_Middle;
18468   verifyFormat("Foo::operator*();", Style);
18469   verifyFormat("Foo::operator void *();", Style);
18470   verifyFormat("Foo::operator()(void *);", Style);
18471   verifyFormat("Foo::operator*(void *);", Style);
18472   verifyFormat("Foo::operator*();", Style);
18473   verifyFormat("operator*(int (*)(), class Foo);", Style);
18474 
18475   verifyFormat("Foo::operator&();", Style);
18476   verifyFormat("Foo::operator void &();", Style);
18477   verifyFormat("Foo::operator()(void &);", Style);
18478   verifyFormat("Foo::operator&(void &);", Style);
18479   verifyFormat("Foo::operator&();", Style);
18480   verifyFormat("operator&(int (&)(), class Foo);", Style);
18481 
18482   verifyFormat("Foo::operator&&();", Style);
18483   verifyFormat("Foo::operator void &&();", Style);
18484   verifyFormat("Foo::operator()(void &&);", Style);
18485   verifyFormat("Foo::operator&&(void &&);", Style);
18486   verifyFormat("Foo::operator&&();", Style);
18487   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
18488 }
18489 
18490 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
18491   FormatStyle Style = getLLVMStyle();
18492   // PR46157
18493   verifyFormat("foo(operator+, -42);", Style);
18494   verifyFormat("foo(operator++, -42);", Style);
18495   verifyFormat("foo(operator--, -42);", Style);
18496   verifyFormat("foo(-42, operator--);", Style);
18497   verifyFormat("foo(-42, operator, );", Style);
18498   verifyFormat("foo(operator, , -42);", Style);
18499 }
18500 
18501 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
18502   FormatStyle Style = getLLVMStyle();
18503   Style.WhitespaceSensitiveMacros.push_back("FOO");
18504 
18505   // Don't use the helpers here, since 'mess up' will change the whitespace
18506   // and these are all whitespace sensitive by definition
18507   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
18508             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
18509   EXPECT_EQ(
18510       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
18511       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
18512   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
18513             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
18514   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
18515             "       Still=Intentional);",
18516             format("FOO(String-ized&Messy+But,: :\n"
18517                    "       Still=Intentional);",
18518                    Style));
18519   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
18520   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
18521             "       Still=Intentional);",
18522             format("FOO(String-ized=&Messy+But,: :\n"
18523                    "       Still=Intentional);",
18524                    Style));
18525 
18526   Style.ColumnLimit = 21;
18527   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
18528             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
18529 }
18530 
18531 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
18532   // These tests are not in NamespaceFixer because that doesn't
18533   // test its interaction with line wrapping
18534   FormatStyle Style = getLLVMStyle();
18535   Style.ColumnLimit = 80;
18536   verifyFormat("namespace {\n"
18537                "int i;\n"
18538                "int j;\n"
18539                "} // namespace",
18540                Style);
18541 
18542   verifyFormat("namespace AAA {\n"
18543                "int i;\n"
18544                "int j;\n"
18545                "} // namespace AAA",
18546                Style);
18547 
18548   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
18549             "int i;\n"
18550             "int j;\n"
18551             "} // namespace Averyveryveryverylongnamespace",
18552             format("namespace Averyveryveryverylongnamespace {\n"
18553                    "int i;\n"
18554                    "int j;\n"
18555                    "}",
18556                    Style));
18557 
18558   EXPECT_EQ(
18559       "namespace "
18560       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
18561       "    went::mad::now {\n"
18562       "int i;\n"
18563       "int j;\n"
18564       "} // namespace\n"
18565       "  // "
18566       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
18567       "went::mad::now",
18568       format("namespace "
18569              "would::it::save::you::a::lot::of::time::if_::i::"
18570              "just::gave::up::and_::went::mad::now {\n"
18571              "int i;\n"
18572              "int j;\n"
18573              "}",
18574              Style));
18575 
18576   // This used to duplicate the comment again and again on subsequent runs
18577   EXPECT_EQ(
18578       "namespace "
18579       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
18580       "    went::mad::now {\n"
18581       "int i;\n"
18582       "int j;\n"
18583       "} // namespace\n"
18584       "  // "
18585       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
18586       "went::mad::now",
18587       format("namespace "
18588              "would::it::save::you::a::lot::of::time::if_::i::"
18589              "just::gave::up::and_::went::mad::now {\n"
18590              "int i;\n"
18591              "int j;\n"
18592              "} // namespace\n"
18593              "  // "
18594              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
18595              "and_::went::mad::now",
18596              Style));
18597 }
18598 
18599 TEST_F(FormatTest, LikelyUnlikely) {
18600   FormatStyle Style = getLLVMStyle();
18601 
18602   verifyFormat("if (argc > 5) [[unlikely]] {\n"
18603                "  return 29;\n"
18604                "}",
18605                Style);
18606 
18607   verifyFormat("if (argc > 5) [[likely]] {\n"
18608                "  return 29;\n"
18609                "}",
18610                Style);
18611 
18612   verifyFormat("if (argc > 5) [[unlikely]] {\n"
18613                "  return 29;\n"
18614                "} else [[likely]] {\n"
18615                "  return 42;\n"
18616                "}\n",
18617                Style);
18618 
18619   verifyFormat("if (argc > 5) [[unlikely]] {\n"
18620                "  return 29;\n"
18621                "} else if (argc > 10) [[likely]] {\n"
18622                "  return 99;\n"
18623                "} else {\n"
18624                "  return 42;\n"
18625                "}\n",
18626                Style);
18627 
18628   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
18629                "  return 29;\n"
18630                "}",
18631                Style);
18632 }
18633 
18634 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
18635   verifyFormat("Constructor()\n"
18636                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
18637                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
18638                "aaaaaaaaaaaaaaaaaat))");
18639   verifyFormat("Constructor()\n"
18640                "    : aaaaaaaaaaaaa(aaaaaa), "
18641                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
18642 
18643   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
18644   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
18645   verifyFormat("Constructor()\n"
18646                "    : aaaaaa(aaaaaa),\n"
18647                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
18648                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
18649                StyleWithWhitespacePenalty);
18650   verifyFormat("Constructor()\n"
18651                "    : aaaaaaaaaaaaa(aaaaaa), "
18652                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
18653                StyleWithWhitespacePenalty);
18654 }
18655 
18656 TEST_F(FormatTest, LLVMDefaultStyle) {
18657   FormatStyle Style = getLLVMStyle();
18658   verifyFormat("extern \"C\" {\n"
18659                "int foo();\n"
18660                "}",
18661                Style);
18662 }
18663 TEST_F(FormatTest, GNUDefaultStyle) {
18664   FormatStyle Style = getGNUStyle();
18665   verifyFormat("extern \"C\"\n"
18666                "{\n"
18667                "  int foo ();\n"
18668                "}",
18669                Style);
18670 }
18671 TEST_F(FormatTest, MozillaDefaultStyle) {
18672   FormatStyle Style = getMozillaStyle();
18673   verifyFormat("extern \"C\"\n"
18674                "{\n"
18675                "  int foo();\n"
18676                "}",
18677                Style);
18678 }
18679 TEST_F(FormatTest, GoogleDefaultStyle) {
18680   FormatStyle Style = getGoogleStyle();
18681   verifyFormat("extern \"C\" {\n"
18682                "int foo();\n"
18683                "}",
18684                Style);
18685 }
18686 TEST_F(FormatTest, ChromiumDefaultStyle) {
18687   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
18688   verifyFormat("extern \"C\" {\n"
18689                "int foo();\n"
18690                "}",
18691                Style);
18692 }
18693 TEST_F(FormatTest, MicrosoftDefaultStyle) {
18694   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
18695   verifyFormat("extern \"C\"\n"
18696                "{\n"
18697                "    int foo();\n"
18698                "}",
18699                Style);
18700 }
18701 TEST_F(FormatTest, WebKitDefaultStyle) {
18702   FormatStyle Style = getWebKitStyle();
18703   verifyFormat("extern \"C\" {\n"
18704                "int foo();\n"
18705                "}",
18706                Style);
18707 }
18708 
18709 TEST_F(FormatTest, ConceptsAndRequires) {
18710   FormatStyle Style = getLLVMStyle();
18711   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
18712 
18713   verifyFormat("template <typename T>\n"
18714                "concept Hashable = requires(T a) {\n"
18715                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
18716                "};",
18717                Style);
18718   verifyFormat("template <typename T>\n"
18719                "concept EqualityComparable = requires(T a, T b) {\n"
18720                "  { a == b } -> bool;\n"
18721                "};",
18722                Style);
18723   verifyFormat("template <typename T>\n"
18724                "concept EqualityComparable = requires(T a, T b) {\n"
18725                "  { a == b } -> bool;\n"
18726                "  { a != b } -> bool;\n"
18727                "};",
18728                Style);
18729   verifyFormat("template <typename T>\n"
18730                "concept EqualityComparable = requires(T a, T b) {\n"
18731                "  { a == b } -> bool;\n"
18732                "  { a != b } -> bool;\n"
18733                "};",
18734                Style);
18735 
18736   verifyFormat("template <typename It>\n"
18737                "requires Iterator<It>\n"
18738                "void sort(It begin, It end) {\n"
18739                "  //....\n"
18740                "}",
18741                Style);
18742 
18743   verifyFormat("template <typename T>\n"
18744                "concept Large = sizeof(T) > 10;",
18745                Style);
18746 
18747   verifyFormat("template <typename T, typename U>\n"
18748                "concept FooableWith = requires(T t, U u) {\n"
18749                "  typename T::foo_type;\n"
18750                "  { t.foo(u) } -> typename T::foo_type;\n"
18751                "  t++;\n"
18752                "};\n"
18753                "void doFoo(FooableWith<int> auto t) {\n"
18754                "  t.foo(3);\n"
18755                "}",
18756                Style);
18757   verifyFormat("template <typename T>\n"
18758                "concept Context = sizeof(T) == 1;",
18759                Style);
18760   verifyFormat("template <typename T>\n"
18761                "concept Context = is_specialization_of_v<context, T>;",
18762                Style);
18763   verifyFormat("template <typename T>\n"
18764                "concept Node = std::is_object_v<T>;",
18765                Style);
18766   verifyFormat("template <typename T>\n"
18767                "concept Tree = true;",
18768                Style);
18769 
18770   verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
18771                "  //...\n"
18772                "}",
18773                Style);
18774 
18775   verifyFormat(
18776       "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
18777       "  //...\n"
18778       "}",
18779       Style);
18780 
18781   verifyFormat(
18782       "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
18783       "  //...\n"
18784       "}",
18785       Style);
18786 
18787   verifyFormat("template <typename T>\n"
18788                "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
18789                "Concept2<I> {\n"
18790                "  //...\n"
18791                "}",
18792                Style);
18793 
18794   verifyFormat("template <typename T>\n"
18795                "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
18796                "Concept2<I> {\n"
18797                "  //...\n"
18798                "}",
18799                Style);
18800 
18801   verifyFormat(
18802       "template <typename T>\n"
18803       "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
18804       "  //...\n"
18805       "}",
18806       Style);
18807 
18808   verifyFormat(
18809       "template <typename T>\n"
18810       "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
18811       "  //...\n"
18812       "}",
18813       Style);
18814 
18815   verifyFormat("template <typename It>\n"
18816                "requires Foo<It>() && Bar<It> {\n"
18817                "  //....\n"
18818                "}",
18819                Style);
18820 
18821   verifyFormat("template <typename It>\n"
18822                "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
18823                "  //....\n"
18824                "}",
18825                Style);
18826 
18827   verifyFormat("template <typename It>\n"
18828                "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
18829                "  //....\n"
18830                "}",
18831                Style);
18832 
18833   verifyFormat(
18834       "template <typename It>\n"
18835       "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
18836       "  //....\n"
18837       "}",
18838       Style);
18839 
18840   Style.IndentRequires = true;
18841   verifyFormat("template <typename It>\n"
18842                "  requires Iterator<It>\n"
18843                "void sort(It begin, It end) {\n"
18844                "  //....\n"
18845                "}",
18846                Style);
18847   verifyFormat("template <std::size index_>\n"
18848                "  requires(index_ < sizeof...(Children_))\n"
18849                "Tree auto &child() {\n"
18850                "  // ...\n"
18851                "}",
18852                Style);
18853 
18854   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
18855   verifyFormat("template <typename T>\n"
18856                "concept Hashable = requires (T a) {\n"
18857                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
18858                "};",
18859                Style);
18860 
18861   verifyFormat("template <class T = void>\n"
18862                "  requires EqualityComparable<T> || Same<T, void>\n"
18863                "struct equal_to;",
18864                Style);
18865 
18866   verifyFormat("template <class T>\n"
18867                "  requires requires {\n"
18868                "    T{};\n"
18869                "    T (int);\n"
18870                "  }\n",
18871                Style);
18872 
18873   Style.ColumnLimit = 78;
18874   verifyFormat("template <typename T>\n"
18875                "concept Context = Traits<typename T::traits_type> and\n"
18876                "    Interface<typename T::interface_type> and\n"
18877                "    Request<typename T::request_type> and\n"
18878                "    Response<typename T::response_type> and\n"
18879                "    ContextExtension<typename T::extension_type> and\n"
18880                "    ::std::is_copy_constructable<T> and "
18881                "::std::is_move_constructable<T> and\n"
18882                "    requires (T c) {\n"
18883                "  { c.response; } -> Response;\n"
18884                "} and requires (T c) {\n"
18885                "  { c.request; } -> Request;\n"
18886                "}\n",
18887                Style);
18888 
18889   verifyFormat("template <typename T>\n"
18890                "concept Context = Traits<typename T::traits_type> or\n"
18891                "    Interface<typename T::interface_type> or\n"
18892                "    Request<typename T::request_type> or\n"
18893                "    Response<typename T::response_type> or\n"
18894                "    ContextExtension<typename T::extension_type> or\n"
18895                "    ::std::is_copy_constructable<T> or "
18896                "::std::is_move_constructable<T> or\n"
18897                "    requires (T c) {\n"
18898                "  { c.response; } -> Response;\n"
18899                "} or requires (T c) {\n"
18900                "  { c.request; } -> Request;\n"
18901                "}\n",
18902                Style);
18903 
18904   verifyFormat("template <typename T>\n"
18905                "concept Context = Traits<typename T::traits_type> &&\n"
18906                "    Interface<typename T::interface_type> &&\n"
18907                "    Request<typename T::request_type> &&\n"
18908                "    Response<typename T::response_type> &&\n"
18909                "    ContextExtension<typename T::extension_type> &&\n"
18910                "    ::std::is_copy_constructable<T> && "
18911                "::std::is_move_constructable<T> &&\n"
18912                "    requires (T c) {\n"
18913                "  { c.response; } -> Response;\n"
18914                "} && requires (T c) {\n"
18915                "  { c.request; } -> Request;\n"
18916                "}\n",
18917                Style);
18918 
18919   verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
18920                "Constraint2<T>;");
18921 
18922   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
18923   Style.BraceWrapping.AfterFunction = true;
18924   Style.BraceWrapping.AfterClass = true;
18925   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
18926   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
18927   verifyFormat("void Foo () requires (std::copyable<T>)\n"
18928                "{\n"
18929                "  return\n"
18930                "}\n",
18931                Style);
18932 
18933   verifyFormat("void Foo () requires std::copyable<T>\n"
18934                "{\n"
18935                "  return\n"
18936                "}\n",
18937                Style);
18938 
18939   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
18940                "  requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
18941                "struct constant;",
18942                Style);
18943 
18944   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
18945                "  requires std::invocable<F, std::invoke_result_t<Args>...>\n"
18946                "struct constant;",
18947                Style);
18948 
18949   verifyFormat("template <class T>\n"
18950                "class plane_with_very_very_very_long_name\n"
18951                "{\n"
18952                "  constexpr plane_with_very_very_very_long_name () requires "
18953                "std::copyable<T>\n"
18954                "      : plane_with_very_very_very_long_name (1)\n"
18955                "  {\n"
18956                "  }\n"
18957                "}\n",
18958                Style);
18959 
18960   verifyFormat("template <class T>\n"
18961                "class plane_with_long_name\n"
18962                "{\n"
18963                "  constexpr plane_with_long_name () requires std::copyable<T>\n"
18964                "      : plane_with_long_name (1)\n"
18965                "  {\n"
18966                "  }\n"
18967                "}\n",
18968                Style);
18969 
18970   Style.BreakBeforeConceptDeclarations = false;
18971   verifyFormat("template <typename T> concept Tree = true;", Style);
18972 
18973   Style.IndentRequires = false;
18974   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
18975                "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
18976                "struct constant;",
18977                Style);
18978 }
18979 
18980 TEST_F(FormatTest, StatementAttributeLikeMacros) {
18981   FormatStyle Style = getLLVMStyle();
18982   StringRef Source = "void Foo::slot() {\n"
18983                      "  unsigned char MyChar = 'x';\n"
18984                      "  emit signal(MyChar);\n"
18985                      "  Q_EMIT signal(MyChar);\n"
18986                      "}";
18987 
18988   EXPECT_EQ(Source, format(Source, Style));
18989 
18990   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
18991   EXPECT_EQ("void Foo::slot() {\n"
18992             "  unsigned char MyChar = 'x';\n"
18993             "  emit          signal(MyChar);\n"
18994             "  Q_EMIT signal(MyChar);\n"
18995             "}",
18996             format(Source, Style));
18997 
18998   Style.StatementAttributeLikeMacros.push_back("emit");
18999   EXPECT_EQ(Source, format(Source, Style));
19000 
19001   Style.StatementAttributeLikeMacros = {};
19002   EXPECT_EQ("void Foo::slot() {\n"
19003             "  unsigned char MyChar = 'x';\n"
19004             "  emit          signal(MyChar);\n"
19005             "  Q_EMIT        signal(MyChar);\n"
19006             "}",
19007             format(Source, Style));
19008 }
19009 } // namespace
19010 } // namespace format
19011 } // namespace clang
19012