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 "clang/Frontend/TextDiagnosticPrinter.h"
15 #include "llvm/Support/Debug.h"
16 #include "llvm/Support/MemoryBuffer.h"
17 #include "gtest/gtest.h"
18 
19 #define DEBUG_TYPE "format-test"
20 
21 using clang::tooling::ReplacementTest;
22 using clang::tooling::toReplacements;
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(llvm::StringRef Expected, llvm::StringRef Code,
69                     const FormatStyle &Style = getLLVMStyle()) {
70     EXPECT_EQ(Expected.str(), format(Expected, Style))
71         << "Expected code is not stable";
72     EXPECT_EQ(Expected.str(), format(Code, Style));
73     if (Style.Language == FormatStyle::LK_Cpp) {
74       // Objective-C++ is a superset of C++, so everything checked for C++
75       // needs to be checked for Objective-C++ as well.
76       FormatStyle ObjCStyle = Style;
77       ObjCStyle.Language = FormatStyle::LK_ObjC;
78       EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle));
79     }
80   }
81 
82   void verifyFormat(llvm::StringRef Code,
83                     const FormatStyle &Style = getLLVMStyle()) {
84     verifyFormat(Code, test::messUp(Code), Style);
85   }
86 
87   void verifyIncompleteFormat(llvm::StringRef Code,
88                               const FormatStyle &Style = getLLVMStyle()) {
89     EXPECT_EQ(Code.str(),
90               format(test::messUp(Code), Style, SC_ExpectIncomplete));
91   }
92 
93   void verifyGoogleFormat(llvm::StringRef Code) {
94     verifyFormat(Code, getGoogleStyle());
95   }
96 
97   void verifyIndependentOfContext(llvm::StringRef text) {
98     verifyFormat(text);
99     verifyFormat(llvm::Twine("void f() { " + text + " }").str());
100   }
101 
102   /// \brief Verify that clang-format does not crash on the given input.
103   void verifyNoCrash(llvm::StringRef Code,
104                      const FormatStyle &Style = getLLVMStyle()) {
105     format(Code, Style, SC_DoNotCheck);
106   }
107 
108   int ReplacementCount;
109 };
110 
111 TEST_F(FormatTest, MessUp) {
112   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
113   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
114   EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
115   EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
116   EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
117 }
118 
119 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
120   EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
121 }
122 
123 TEST_F(FormatTest, LLVMStyleOverride) {
124   EXPECT_EQ(FormatStyle::LK_Proto,
125             getLLVMStyle(FormatStyle::LK_Proto).Language);
126 }
127 
128 //===----------------------------------------------------------------------===//
129 // Basic function tests.
130 //===----------------------------------------------------------------------===//
131 
132 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
133   EXPECT_EQ(";", format(";"));
134 }
135 
136 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
137   EXPECT_EQ("int i;", format("  int i;"));
138   EXPECT_EQ("\nint i;", format(" \n\t \v \f  int i;"));
139   EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
140   EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
141 }
142 
143 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
144   EXPECT_EQ("int i;", format("int\ni;"));
145 }
146 
147 TEST_F(FormatTest, FormatsNestedBlockStatements) {
148   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
149 }
150 
151 TEST_F(FormatTest, FormatsNestedCall) {
152   verifyFormat("Method(f1, f2(f3));");
153   verifyFormat("Method(f1(f2, f3()));");
154   verifyFormat("Method(f1(f2, (f3())));");
155 }
156 
157 TEST_F(FormatTest, NestedNameSpecifiers) {
158   verifyFormat("vector<::Type> v;");
159   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
160   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
161   verifyFormat("bool a = 2 < ::SomeFunction();");
162   verifyFormat("ALWAYS_INLINE ::std::string getName();");
163   verifyFormat("some::string getName();");
164 }
165 
166 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
167   EXPECT_EQ("if (a) {\n"
168             "  f();\n"
169             "}",
170             format("if(a){f();}"));
171   EXPECT_EQ(4, ReplacementCount);
172   EXPECT_EQ("if (a) {\n"
173             "  f();\n"
174             "}",
175             format("if (a) {\n"
176                    "  f();\n"
177                    "}"));
178   EXPECT_EQ(0, ReplacementCount);
179   EXPECT_EQ("/*\r\n"
180             "\r\n"
181             "*/\r\n",
182             format("/*\r\n"
183                    "\r\n"
184                    "*/\r\n"));
185   EXPECT_EQ(0, ReplacementCount);
186 }
187 
188 TEST_F(FormatTest, RemovesEmptyLines) {
189   EXPECT_EQ("class C {\n"
190             "  int i;\n"
191             "};",
192             format("class C {\n"
193                    " int i;\n"
194                    "\n"
195                    "};"));
196 
197   // Don't remove empty lines at the start of namespaces or extern "C" blocks.
198   EXPECT_EQ("namespace N {\n"
199             "\n"
200             "int i;\n"
201             "}",
202             format("namespace N {\n"
203                    "\n"
204                    "int    i;\n"
205                    "}",
206                    getGoogleStyle()));
207   EXPECT_EQ("/* something */ namespace N {\n"
208             "\n"
209             "int i;\n"
210             "}",
211             format("/* something */ namespace N {\n"
212                    "\n"
213                    "int    i;\n"
214                    "}",
215                    getGoogleStyle()));
216   EXPECT_EQ("inline namespace N {\n"
217             "\n"
218             "int i;\n"
219             "}",
220             format("inline namespace N {\n"
221                    "\n"
222                    "int    i;\n"
223                    "}",
224                    getGoogleStyle()));
225   EXPECT_EQ("/* something */ inline namespace N {\n"
226             "\n"
227             "int i;\n"
228             "}",
229             format("/* something */ inline namespace N {\n"
230                    "\n"
231                    "int    i;\n"
232                    "}",
233                    getGoogleStyle()));
234   EXPECT_EQ("export namespace N {\n"
235             "\n"
236             "int i;\n"
237             "}",
238             format("export namespace N {\n"
239                    "\n"
240                    "int    i;\n"
241                    "}",
242                    getGoogleStyle()));
243   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
244             "\n"
245             "int i;\n"
246             "}",
247             format("extern /**/ \"C\" /**/ {\n"
248                    "\n"
249                    "int    i;\n"
250                    "}",
251                    getGoogleStyle()));
252 
253   // ...but do keep inlining and removing empty lines for non-block extern "C"
254   // functions.
255   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
256   EXPECT_EQ("extern \"C\" int f() {\n"
257             "  int i = 42;\n"
258             "  return i;\n"
259             "}",
260             format("extern \"C\" int f() {\n"
261                    "\n"
262                    "  int i = 42;\n"
263                    "  return i;\n"
264                    "}",
265                    getGoogleStyle()));
266 
267   // Remove empty lines at the beginning and end of blocks.
268   EXPECT_EQ("void f() {\n"
269             "\n"
270             "  if (a) {\n"
271             "\n"
272             "    f();\n"
273             "  }\n"
274             "}",
275             format("void f() {\n"
276                    "\n"
277                    "  if (a) {\n"
278                    "\n"
279                    "    f();\n"
280                    "\n"
281                    "  }\n"
282                    "\n"
283                    "}",
284                    getLLVMStyle()));
285   EXPECT_EQ("void f() {\n"
286             "  if (a) {\n"
287             "    f();\n"
288             "  }\n"
289             "}",
290             format("void f() {\n"
291                    "\n"
292                    "  if (a) {\n"
293                    "\n"
294                    "    f();\n"
295                    "\n"
296                    "  }\n"
297                    "\n"
298                    "}",
299                    getGoogleStyle()));
300 
301   // Don't remove empty lines in more complex control statements.
302   EXPECT_EQ("void f() {\n"
303             "  if (a) {\n"
304             "    f();\n"
305             "\n"
306             "  } else if (b) {\n"
307             "    f();\n"
308             "  }\n"
309             "}",
310             format("void f() {\n"
311                    "  if (a) {\n"
312                    "    f();\n"
313                    "\n"
314                    "  } else if (b) {\n"
315                    "    f();\n"
316                    "\n"
317                    "  }\n"
318                    "\n"
319                    "}"));
320 
321   // Don't remove empty lines before namespace endings.
322   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
323   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
324   EXPECT_EQ("namespace {\n"
325             "int i;\n"
326             "\n"
327             "}",
328             format("namespace {\n"
329                    "int i;\n"
330                    "\n"
331                    "}",
332                    LLVMWithNoNamespaceFix));
333   EXPECT_EQ("namespace {\n"
334             "int i;\n"
335             "}",
336             format("namespace {\n"
337                    "int i;\n"
338                    "}",
339                    LLVMWithNoNamespaceFix));
340   EXPECT_EQ("namespace {\n"
341             "int i;\n"
342             "\n"
343             "};",
344             format("namespace {\n"
345                    "int i;\n"
346                    "\n"
347                    "};",
348                    LLVMWithNoNamespaceFix));
349   EXPECT_EQ("namespace {\n"
350             "int i;\n"
351             "};",
352             format("namespace {\n"
353                    "int i;\n"
354                    "};",
355                    LLVMWithNoNamespaceFix));
356   EXPECT_EQ("namespace {\n"
357             "int i;\n"
358             "\n"
359             "}",
360             format("namespace {\n"
361                    "int i;\n"
362                    "\n"
363                    "}"));
364   EXPECT_EQ("namespace {\n"
365             "int i;\n"
366             "\n"
367             "} // namespace",
368             format("namespace {\n"
369                    "int i;\n"
370                    "\n"
371                    "}  // namespace"));
372 
373   FormatStyle Style = getLLVMStyle();
374   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
375   Style.MaxEmptyLinesToKeep = 2;
376   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
377   Style.BraceWrapping.AfterClass = true;
378   Style.BraceWrapping.AfterFunction = true;
379   Style.KeepEmptyLinesAtTheStartOfBlocks = false;
380 
381   EXPECT_EQ("class Foo\n"
382             "{\n"
383             "  Foo() {}\n"
384             "\n"
385             "  void funk() {}\n"
386             "};",
387             format("class Foo\n"
388                    "{\n"
389                    "  Foo()\n"
390                    "  {\n"
391                    "  }\n"
392                    "\n"
393                    "  void funk() {}\n"
394                    "};",
395                    Style));
396 }
397 
398 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
399   verifyFormat("x = (a) and (b);");
400   verifyFormat("x = (a) or (b);");
401   verifyFormat("x = (a) bitand (b);");
402   verifyFormat("x = (a) bitor (b);");
403   verifyFormat("x = (a) not_eq (b);");
404   verifyFormat("x = (a) and_eq (b);");
405   verifyFormat("x = (a) or_eq (b);");
406   verifyFormat("x = (a) xor (b);");
407 }
408 
409 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
410   verifyFormat("x = compl(a);");
411   verifyFormat("x = not(a);");
412   verifyFormat("x = bitand(a);");
413   // Unary operator must not be merged with the next identifier
414   verifyFormat("x = compl a;");
415   verifyFormat("x = not a;");
416   verifyFormat("x = bitand a;");
417 }
418 
419 //===----------------------------------------------------------------------===//
420 // Tests for control statements.
421 //===----------------------------------------------------------------------===//
422 
423 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
424   verifyFormat("if (true)\n  f();\ng();");
425   verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
426   verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
427   verifyFormat("if constexpr (true)\n"
428                "  f();\ng();");
429   verifyFormat("if CONSTEXPR (true)\n"
430                "  f();\ng();");
431   verifyFormat("if constexpr (a)\n"
432                "  if constexpr (b)\n"
433                "    if constexpr (c)\n"
434                "      g();\n"
435                "h();");
436   verifyFormat("if CONSTEXPR (a)\n"
437                "  if CONSTEXPR (b)\n"
438                "    if CONSTEXPR (c)\n"
439                "      g();\n"
440                "h();");
441   verifyFormat("if constexpr (a)\n"
442                "  if constexpr (b) {\n"
443                "    f();\n"
444                "  }\n"
445                "g();");
446   verifyFormat("if CONSTEXPR (a)\n"
447                "  if CONSTEXPR (b) {\n"
448                "    f();\n"
449                "  }\n"
450                "g();");
451 
452   FormatStyle AllowsMergedIf = getLLVMStyle();
453   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
454   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
455       FormatStyle::SIS_WithoutElse;
456   verifyFormat("if (a)\n"
457                "  // comment\n"
458                "  f();",
459                AllowsMergedIf);
460   verifyFormat("{\n"
461                "  if (a)\n"
462                "  label:\n"
463                "    f();\n"
464                "}",
465                AllowsMergedIf);
466   verifyFormat("#define A \\\n"
467                "  if (a)  \\\n"
468                "  label:  \\\n"
469                "    f()",
470                AllowsMergedIf);
471   verifyFormat("if (a)\n"
472                "  ;",
473                AllowsMergedIf);
474   verifyFormat("if (a)\n"
475                "  if (b) return;",
476                AllowsMergedIf);
477 
478   verifyFormat("if (a) // Can't merge this\n"
479                "  f();\n",
480                AllowsMergedIf);
481   verifyFormat("if (a) /* still don't merge */\n"
482                "  f();",
483                AllowsMergedIf);
484   verifyFormat("if (a) { // Never merge this\n"
485                "  f();\n"
486                "}",
487                AllowsMergedIf);
488   verifyFormat("if (a) { /* Never merge this */\n"
489                "  f();\n"
490                "}",
491                AllowsMergedIf);
492 
493   AllowsMergedIf.ColumnLimit = 14;
494   verifyFormat("if (a) return;", AllowsMergedIf);
495   verifyFormat("if (aaaaaaaaa)\n"
496                "  return;",
497                AllowsMergedIf);
498 
499   AllowsMergedIf.ColumnLimit = 13;
500   verifyFormat("if (a)\n  return;", AllowsMergedIf);
501 }
502 
503 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
504   FormatStyle AllowsMergedIf = getLLVMStyle();
505   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
506   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
507       FormatStyle::SIS_WithoutElse;
508   verifyFormat("if (a)\n"
509                "  f();\n"
510                "else {\n"
511                "  g();\n"
512                "}",
513                AllowsMergedIf);
514   verifyFormat("if (a)\n"
515                "  f();\n"
516                "else\n"
517                "  g();\n",
518                AllowsMergedIf);
519 
520   AllowsMergedIf.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
521 
522   verifyFormat("if (a) f();\n"
523                "else {\n"
524                "  g();\n"
525                "}",
526                AllowsMergedIf);
527   verifyFormat("if (a) f();\n"
528                "else {\n"
529                "  if (a) f();\n"
530                "  else {\n"
531                "    g();\n"
532                "  }\n"
533                "  g();\n"
534                "}",
535                AllowsMergedIf);
536 }
537 
538 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
539   FormatStyle AllowsMergedLoops = getLLVMStyle();
540   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
541   verifyFormat("while (true) continue;", AllowsMergedLoops);
542   verifyFormat("for (;;) continue;", AllowsMergedLoops);
543   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
544   verifyFormat("while (true)\n"
545                "  ;",
546                AllowsMergedLoops);
547   verifyFormat("for (;;)\n"
548                "  ;",
549                AllowsMergedLoops);
550   verifyFormat("for (;;)\n"
551                "  for (;;) continue;",
552                AllowsMergedLoops);
553   verifyFormat("for (;;) // Can't merge this\n"
554                "  continue;",
555                AllowsMergedLoops);
556   verifyFormat("for (;;) /* still don't merge */\n"
557                "  continue;",
558                AllowsMergedLoops);
559   verifyFormat("do a++;\n"
560                "while (true);",
561                AllowsMergedLoops);
562   verifyFormat("do /* Don't merge */\n"
563                "  a++;\n"
564                "while (true);",
565                AllowsMergedLoops);
566   verifyFormat("do // Don't merge\n"
567                "  a++;\n"
568                "while (true);",
569                AllowsMergedLoops);
570   verifyFormat("do\n"
571                "  // Don't merge\n"
572                "  a++;\n"
573                "while (true);",
574                AllowsMergedLoops);
575   // Without braces labels are interpreted differently.
576   verifyFormat("{\n"
577                "  do\n"
578                "  label:\n"
579                "    a++;\n"
580                "  while (true);\n"
581                "}",
582                AllowsMergedLoops);
583 }
584 
585 TEST_F(FormatTest, FormatShortBracedStatements) {
586   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
587   AllowSimpleBracedStatements.ColumnLimit = 40;
588   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
589       FormatStyle::SBS_Always;
590 
591   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
592       FormatStyle::SIS_WithoutElse;
593   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
594 
595   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
596   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
597   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
598 
599   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
600   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
601   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
602   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
603   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
604   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
605   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
606   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
607   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
608   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
609   verifyFormat("if (true) {\n"
610                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
611                "}",
612                AllowSimpleBracedStatements);
613   verifyFormat("if (true) { //\n"
614                "  f();\n"
615                "}",
616                AllowSimpleBracedStatements);
617   verifyFormat("if (true) {\n"
618                "  f();\n"
619                "  f();\n"
620                "}",
621                AllowSimpleBracedStatements);
622   verifyFormat("if (true) {\n"
623                "  f();\n"
624                "} else {\n"
625                "  f();\n"
626                "}",
627                AllowSimpleBracedStatements);
628 
629   verifyFormat("struct A2 {\n"
630                "  int X;\n"
631                "};",
632                AllowSimpleBracedStatements);
633   verifyFormat("typedef struct A2 {\n"
634                "  int X;\n"
635                "} A2_t;",
636                AllowSimpleBracedStatements);
637   verifyFormat("template <int> struct A2 {\n"
638                "  struct B {};\n"
639                "};",
640                AllowSimpleBracedStatements);
641 
642   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
643       FormatStyle::SIS_Never;
644   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
645   verifyFormat("if (true) {\n"
646                "  f();\n"
647                "}",
648                AllowSimpleBracedStatements);
649   verifyFormat("if (true) {\n"
650                "  f();\n"
651                "} else {\n"
652                "  f();\n"
653                "}",
654                AllowSimpleBracedStatements);
655 
656   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
657   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
658   verifyFormat("while (true) {\n"
659                "  f();\n"
660                "}",
661                AllowSimpleBracedStatements);
662   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
663   verifyFormat("for (;;) {\n"
664                "  f();\n"
665                "}",
666                AllowSimpleBracedStatements);
667 
668   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
669       FormatStyle::SIS_WithoutElse;
670   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
671   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
672       FormatStyle::BWACS_Always;
673 
674   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
675   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
676   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
677   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
678   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
679   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
680   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
681   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
682   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
683   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
684   verifyFormat("if (true)\n"
685                "{\n"
686                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
687                "}",
688                AllowSimpleBracedStatements);
689   verifyFormat("if (true)\n"
690                "{ //\n"
691                "  f();\n"
692                "}",
693                AllowSimpleBracedStatements);
694   verifyFormat("if (true)\n"
695                "{\n"
696                "  f();\n"
697                "  f();\n"
698                "}",
699                AllowSimpleBracedStatements);
700   verifyFormat("if (true)\n"
701                "{\n"
702                "  f();\n"
703                "} else\n"
704                "{\n"
705                "  f();\n"
706                "}",
707                AllowSimpleBracedStatements);
708 
709   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
710       FormatStyle::SIS_Never;
711   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
712   verifyFormat("if (true)\n"
713                "{\n"
714                "  f();\n"
715                "}",
716                AllowSimpleBracedStatements);
717   verifyFormat("if (true)\n"
718                "{\n"
719                "  f();\n"
720                "} else\n"
721                "{\n"
722                "  f();\n"
723                "}",
724                AllowSimpleBracedStatements);
725 
726   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
727   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
728   verifyFormat("while (true)\n"
729                "{\n"
730                "  f();\n"
731                "}",
732                AllowSimpleBracedStatements);
733   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
734   verifyFormat("for (;;)\n"
735                "{\n"
736                "  f();\n"
737                "}",
738                AllowSimpleBracedStatements);
739 }
740 
741 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
742   FormatStyle Style = getLLVMStyleWithColumns(60);
743   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
744   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
745   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
746   EXPECT_EQ("#define A                                                  \\\n"
747             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
748             "  { RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; }\n"
749             "X;",
750             format("#define A \\\n"
751                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
752                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
753                    "   }\n"
754                    "X;",
755                    Style));
756 }
757 
758 TEST_F(FormatTest, ParseIfElse) {
759   verifyFormat("if (true)\n"
760                "  if (true)\n"
761                "    if (true)\n"
762                "      f();\n"
763                "    else\n"
764                "      g();\n"
765                "  else\n"
766                "    h();\n"
767                "else\n"
768                "  i();");
769   verifyFormat("if (true)\n"
770                "  if (true)\n"
771                "    if (true) {\n"
772                "      if (true)\n"
773                "        f();\n"
774                "    } else {\n"
775                "      g();\n"
776                "    }\n"
777                "  else\n"
778                "    h();\n"
779                "else {\n"
780                "  i();\n"
781                "}");
782   verifyFormat("if (true)\n"
783                "  if constexpr (true)\n"
784                "    if (true) {\n"
785                "      if constexpr (true)\n"
786                "        f();\n"
787                "    } else {\n"
788                "      g();\n"
789                "    }\n"
790                "  else\n"
791                "    h();\n"
792                "else {\n"
793                "  i();\n"
794                "}");
795   verifyFormat("if (true)\n"
796                "  if CONSTEXPR (true)\n"
797                "    if (true) {\n"
798                "      if CONSTEXPR (true)\n"
799                "        f();\n"
800                "    } else {\n"
801                "      g();\n"
802                "    }\n"
803                "  else\n"
804                "    h();\n"
805                "else {\n"
806                "  i();\n"
807                "}");
808   verifyFormat("void f() {\n"
809                "  if (a) {\n"
810                "  } else {\n"
811                "  }\n"
812                "}");
813 }
814 
815 TEST_F(FormatTest, ElseIf) {
816   verifyFormat("if (a) {\n} else if (b) {\n}");
817   verifyFormat("if (a)\n"
818                "  f();\n"
819                "else if (b)\n"
820                "  g();\n"
821                "else\n"
822                "  h();");
823   verifyFormat("if constexpr (a)\n"
824                "  f();\n"
825                "else if constexpr (b)\n"
826                "  g();\n"
827                "else\n"
828                "  h();");
829   verifyFormat("if CONSTEXPR (a)\n"
830                "  f();\n"
831                "else if CONSTEXPR (b)\n"
832                "  g();\n"
833                "else\n"
834                "  h();");
835   verifyFormat("if (a) {\n"
836                "  f();\n"
837                "}\n"
838                "// or else ..\n"
839                "else {\n"
840                "  g()\n"
841                "}");
842 
843   verifyFormat("if (a) {\n"
844                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
845                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
846                "}");
847   verifyFormat("if (a) {\n"
848                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
849                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
850                "}");
851   verifyFormat("if (a) {\n"
852                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
853                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
854                "}");
855   verifyFormat("if (a) {\n"
856                "} else if (\n"
857                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
858                "}",
859                getLLVMStyleWithColumns(62));
860   verifyFormat("if (a) {\n"
861                "} else if constexpr (\n"
862                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
863                "}",
864                getLLVMStyleWithColumns(62));
865   verifyFormat("if (a) {\n"
866                "} else if CONSTEXPR (\n"
867                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
868                "}",
869                getLLVMStyleWithColumns(62));
870 }
871 
872 TEST_F(FormatTest, FormatsForLoop) {
873   verifyFormat(
874       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
875       "     ++VeryVeryLongLoopVariable)\n"
876       "  ;");
877   verifyFormat("for (;;)\n"
878                "  f();");
879   verifyFormat("for (;;) {\n}");
880   verifyFormat("for (;;) {\n"
881                "  f();\n"
882                "}");
883   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
884 
885   verifyFormat(
886       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
887       "                                          E = UnwrappedLines.end();\n"
888       "     I != E; ++I) {\n}");
889 
890   verifyFormat(
891       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
892       "     ++IIIII) {\n}");
893   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
894                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
895                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
896   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
897                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
898                "         E = FD->getDeclsInPrototypeScope().end();\n"
899                "     I != E; ++I) {\n}");
900   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
901                "         I = Container.begin(),\n"
902                "         E = Container.end();\n"
903                "     I != E; ++I) {\n}",
904                getLLVMStyleWithColumns(76));
905 
906   verifyFormat(
907       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
908       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
909       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
910       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
911       "     ++aaaaaaaaaaa) {\n}");
912   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
913                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
914                "     ++i) {\n}");
915   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
916                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
917                "}");
918   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
919                "         aaaaaaaaaa);\n"
920                "     iter; ++iter) {\n"
921                "}");
922   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
923                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
924                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
925                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
926 
927   // These should not be formatted as Objective-C for-in loops.
928   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
929   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
930   verifyFormat("Foo *x;\nfor (x in y) {\n}");
931   verifyFormat(
932       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
933 
934   FormatStyle NoBinPacking = getLLVMStyle();
935   NoBinPacking.BinPackParameters = false;
936   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
937                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
938                "                                           aaaaaaaaaaaaaaaa,\n"
939                "                                           aaaaaaaaaaaaaaaa,\n"
940                "                                           aaaaaaaaaaaaaaaa);\n"
941                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
942                "}",
943                NoBinPacking);
944   verifyFormat(
945       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
946       "                                          E = UnwrappedLines.end();\n"
947       "     I != E;\n"
948       "     ++I) {\n}",
949       NoBinPacking);
950 
951   FormatStyle AlignLeft = getLLVMStyle();
952   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
953   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
954 }
955 
956 TEST_F(FormatTest, RangeBasedForLoops) {
957   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
958                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
959   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
960                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
961   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
962                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
963   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
964                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
965 }
966 
967 TEST_F(FormatTest, ForEachLoops) {
968   verifyFormat("void f() {\n"
969                "  foreach (Item *item, itemlist) {}\n"
970                "  Q_FOREACH (Item *item, itemlist) {}\n"
971                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
972                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
973                "}");
974 
975   FormatStyle Style = getLLVMStyle();
976   Style.SpaceBeforeParens =
977       FormatStyle::SBPO_ControlStatementsExceptForEachMacros;
978   verifyFormat("void f() {\n"
979                "  foreach(Item *item, itemlist) {}\n"
980                "  Q_FOREACH(Item *item, itemlist) {}\n"
981                "  BOOST_FOREACH(Item *item, itemlist) {}\n"
982                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
983                "}",
984                Style);
985 
986   // As function-like macros.
987   verifyFormat("#define foreach(x, y)\n"
988                "#define Q_FOREACH(x, y)\n"
989                "#define BOOST_FOREACH(x, y)\n"
990                "#define UNKNOWN_FOREACH(x, y)\n");
991 
992   // Not as function-like macros.
993   verifyFormat("#define foreach (x, y)\n"
994                "#define Q_FOREACH (x, y)\n"
995                "#define BOOST_FOREACH (x, y)\n"
996                "#define UNKNOWN_FOREACH (x, y)\n");
997 }
998 
999 TEST_F(FormatTest, FormatsWhileLoop) {
1000   verifyFormat("while (true) {\n}");
1001   verifyFormat("while (true)\n"
1002                "  f();");
1003   verifyFormat("while () {\n}");
1004   verifyFormat("while () {\n"
1005                "  f();\n"
1006                "}");
1007 }
1008 
1009 TEST_F(FormatTest, FormatsDoWhile) {
1010   verifyFormat("do {\n"
1011                "  do_something();\n"
1012                "} while (something());");
1013   verifyFormat("do\n"
1014                "  do_something();\n"
1015                "while (something());");
1016 }
1017 
1018 TEST_F(FormatTest, FormatsSwitchStatement) {
1019   verifyFormat("switch (x) {\n"
1020                "case 1:\n"
1021                "  f();\n"
1022                "  break;\n"
1023                "case kFoo:\n"
1024                "case ns::kBar:\n"
1025                "case kBaz:\n"
1026                "  break;\n"
1027                "default:\n"
1028                "  g();\n"
1029                "  break;\n"
1030                "}");
1031   verifyFormat("switch (x) {\n"
1032                "case 1: {\n"
1033                "  f();\n"
1034                "  break;\n"
1035                "}\n"
1036                "case 2: {\n"
1037                "  break;\n"
1038                "}\n"
1039                "}");
1040   verifyFormat("switch (x) {\n"
1041                "case 1: {\n"
1042                "  f();\n"
1043                "  {\n"
1044                "    g();\n"
1045                "    h();\n"
1046                "  }\n"
1047                "  break;\n"
1048                "}\n"
1049                "}");
1050   verifyFormat("switch (x) {\n"
1051                "case 1: {\n"
1052                "  f();\n"
1053                "  if (foo) {\n"
1054                "    g();\n"
1055                "    h();\n"
1056                "  }\n"
1057                "  break;\n"
1058                "}\n"
1059                "}");
1060   verifyFormat("switch (x) {\n"
1061                "case 1: {\n"
1062                "  f();\n"
1063                "  g();\n"
1064                "} break;\n"
1065                "}");
1066   verifyFormat("switch (test)\n"
1067                "  ;");
1068   verifyFormat("switch (x) {\n"
1069                "default: {\n"
1070                "  // Do nothing.\n"
1071                "}\n"
1072                "}");
1073   verifyFormat("switch (x) {\n"
1074                "// comment\n"
1075                "// if 1, do f()\n"
1076                "case 1:\n"
1077                "  f();\n"
1078                "}");
1079   verifyFormat("switch (x) {\n"
1080                "case 1:\n"
1081                "  // Do amazing stuff\n"
1082                "  {\n"
1083                "    f();\n"
1084                "    g();\n"
1085                "  }\n"
1086                "  break;\n"
1087                "}");
1088   verifyFormat("#define A          \\\n"
1089                "  switch (x) {     \\\n"
1090                "  case a:          \\\n"
1091                "    foo = b;       \\\n"
1092                "  }",
1093                getLLVMStyleWithColumns(20));
1094   verifyFormat("#define OPERATION_CASE(name)           \\\n"
1095                "  case OP_name:                        \\\n"
1096                "    return operations::Operation##name\n",
1097                getLLVMStyleWithColumns(40));
1098   verifyFormat("switch (x) {\n"
1099                "case 1:;\n"
1100                "default:;\n"
1101                "  int i;\n"
1102                "}");
1103 
1104   verifyGoogleFormat("switch (x) {\n"
1105                      "  case 1:\n"
1106                      "    f();\n"
1107                      "    break;\n"
1108                      "  case kFoo:\n"
1109                      "  case ns::kBar:\n"
1110                      "  case kBaz:\n"
1111                      "    break;\n"
1112                      "  default:\n"
1113                      "    g();\n"
1114                      "    break;\n"
1115                      "}");
1116   verifyGoogleFormat("switch (x) {\n"
1117                      "  case 1: {\n"
1118                      "    f();\n"
1119                      "    break;\n"
1120                      "  }\n"
1121                      "}");
1122   verifyGoogleFormat("switch (test)\n"
1123                      "  ;");
1124 
1125   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
1126                      "  case OP_name:              \\\n"
1127                      "    return operations::Operation##name\n");
1128   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
1129                      "  // Get the correction operation class.\n"
1130                      "  switch (OpCode) {\n"
1131                      "    CASE(Add);\n"
1132                      "    CASE(Subtract);\n"
1133                      "    default:\n"
1134                      "      return operations::Unknown;\n"
1135                      "  }\n"
1136                      "#undef OPERATION_CASE\n"
1137                      "}");
1138   verifyFormat("DEBUG({\n"
1139                "  switch (x) {\n"
1140                "  case A:\n"
1141                "    f();\n"
1142                "    break;\n"
1143                "    // fallthrough\n"
1144                "  case B:\n"
1145                "    g();\n"
1146                "    break;\n"
1147                "  }\n"
1148                "});");
1149   EXPECT_EQ("DEBUG({\n"
1150             "  switch (x) {\n"
1151             "  case A:\n"
1152             "    f();\n"
1153             "    break;\n"
1154             "  // On B:\n"
1155             "  case B:\n"
1156             "    g();\n"
1157             "    break;\n"
1158             "  }\n"
1159             "});",
1160             format("DEBUG({\n"
1161                    "  switch (x) {\n"
1162                    "  case A:\n"
1163                    "    f();\n"
1164                    "    break;\n"
1165                    "  // On B:\n"
1166                    "  case B:\n"
1167                    "    g();\n"
1168                    "    break;\n"
1169                    "  }\n"
1170                    "});",
1171                    getLLVMStyle()));
1172   EXPECT_EQ("switch (n) {\n"
1173             "case 0: {\n"
1174             "  return false;\n"
1175             "}\n"
1176             "default: {\n"
1177             "  return true;\n"
1178             "}\n"
1179             "}",
1180             format("switch (n)\n"
1181                    "{\n"
1182                    "case 0: {\n"
1183                    "  return false;\n"
1184                    "}\n"
1185                    "default: {\n"
1186                    "  return true;\n"
1187                    "}\n"
1188                    "}",
1189                    getLLVMStyle()));
1190   verifyFormat("switch (a) {\n"
1191                "case (b):\n"
1192                "  return;\n"
1193                "}");
1194 
1195   verifyFormat("switch (a) {\n"
1196                "case some_namespace::\n"
1197                "    some_constant:\n"
1198                "  return;\n"
1199                "}",
1200                getLLVMStyleWithColumns(34));
1201 
1202   FormatStyle Style = getLLVMStyle();
1203   Style.IndentCaseLabels = true;
1204   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1205   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1206   Style.BraceWrapping.AfterCaseLabel = true;
1207   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1208   EXPECT_EQ("switch (n)\n"
1209             "{\n"
1210             "  case 0:\n"
1211             "  {\n"
1212             "    return false;\n"
1213             "  }\n"
1214             "  default:\n"
1215             "  {\n"
1216             "    return true;\n"
1217             "  }\n"
1218             "}",
1219             format("switch (n) {\n"
1220                    "  case 0: {\n"
1221                    "    return false;\n"
1222                    "  }\n"
1223                    "  default: {\n"
1224                    "    return true;\n"
1225                    "  }\n"
1226                    "}",
1227                    Style));
1228   Style.BraceWrapping.AfterCaseLabel = false;
1229   EXPECT_EQ("switch (n)\n"
1230             "{\n"
1231             "  case 0: {\n"
1232             "    return false;\n"
1233             "  }\n"
1234             "  default: {\n"
1235             "    return true;\n"
1236             "  }\n"
1237             "}",
1238             format("switch (n) {\n"
1239                    "  case 0:\n"
1240                    "  {\n"
1241                    "    return false;\n"
1242                    "  }\n"
1243                    "  default:\n"
1244                    "  {\n"
1245                    "    return true;\n"
1246                    "  }\n"
1247                    "}",
1248                    Style));
1249   Style.IndentCaseLabels = false;
1250   Style.IndentCaseBlocks = true;
1251   EXPECT_EQ("switch (n)\n"
1252             "{\n"
1253             "case 0:\n"
1254             "  {\n"
1255             "    return false;\n"
1256             "  }\n"
1257             "case 1:\n"
1258             "  break;\n"
1259             "default:\n"
1260             "  {\n"
1261             "    return true;\n"
1262             "  }\n"
1263             "}",
1264             format("switch (n) {\n"
1265                    "case 0: {\n"
1266                    "  return false;\n"
1267                    "}\n"
1268                    "case 1:\n"
1269                    "  break;\n"
1270                    "default: {\n"
1271                    "  return true;\n"
1272                    "}\n"
1273                    "}",
1274                    Style));
1275   Style.IndentCaseLabels = true;
1276   Style.IndentCaseBlocks = true;
1277   EXPECT_EQ("switch (n)\n"
1278             "{\n"
1279             "  case 0:\n"
1280             "    {\n"
1281             "      return false;\n"
1282             "    }\n"
1283             "  case 1:\n"
1284             "    break;\n"
1285             "  default:\n"
1286             "    {\n"
1287             "      return true;\n"
1288             "    }\n"
1289             "}",
1290             format("switch (n) {\n"
1291                    "case 0: {\n"
1292                    "  return false;\n"
1293                    "}\n"
1294                    "case 1:\n"
1295                    "  break;\n"
1296                    "default: {\n"
1297                    "  return true;\n"
1298                    "}\n"
1299                    "}",
1300                    Style));
1301 }
1302 
1303 TEST_F(FormatTest, CaseRanges) {
1304   verifyFormat("switch (x) {\n"
1305                "case 'A' ... 'Z':\n"
1306                "case 1 ... 5:\n"
1307                "case a ... b:\n"
1308                "  break;\n"
1309                "}");
1310 }
1311 
1312 TEST_F(FormatTest, ShortEnums) {
1313   FormatStyle Style = getLLVMStyle();
1314   Style.AllowShortEnumsOnASingleLine = true;
1315   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
1316   Style.AllowShortEnumsOnASingleLine = false;
1317   verifyFormat("enum\n"
1318                "{\n"
1319                "  A,\n"
1320                "  B,\n"
1321                "  C\n"
1322                "} ShortEnum1, ShortEnum2;",
1323                Style);
1324 }
1325 
1326 TEST_F(FormatTest, ShortCaseLabels) {
1327   FormatStyle Style = getLLVMStyle();
1328   Style.AllowShortCaseLabelsOnASingleLine = true;
1329   verifyFormat("switch (a) {\n"
1330                "case 1: x = 1; break;\n"
1331                "case 2: return;\n"
1332                "case 3:\n"
1333                "case 4:\n"
1334                "case 5: return;\n"
1335                "case 6: // comment\n"
1336                "  return;\n"
1337                "case 7:\n"
1338                "  // comment\n"
1339                "  return;\n"
1340                "case 8:\n"
1341                "  x = 8; // comment\n"
1342                "  break;\n"
1343                "default: y = 1; break;\n"
1344                "}",
1345                Style);
1346   verifyFormat("switch (a) {\n"
1347                "case 0: return; // comment\n"
1348                "case 1: break;  // comment\n"
1349                "case 2: return;\n"
1350                "// comment\n"
1351                "case 3: return;\n"
1352                "// comment 1\n"
1353                "// comment 2\n"
1354                "// comment 3\n"
1355                "case 4: break; /* comment */\n"
1356                "case 5:\n"
1357                "  // comment\n"
1358                "  break;\n"
1359                "case 6: /* comment */ x = 1; break;\n"
1360                "case 7: x = /* comment */ 1; break;\n"
1361                "case 8:\n"
1362                "  x = 1; /* comment */\n"
1363                "  break;\n"
1364                "case 9:\n"
1365                "  break; // comment line 1\n"
1366                "         // comment line 2\n"
1367                "}",
1368                Style);
1369   EXPECT_EQ("switch (a) {\n"
1370             "case 1:\n"
1371             "  x = 8;\n"
1372             "  // fall through\n"
1373             "case 2: x = 8;\n"
1374             "// comment\n"
1375             "case 3:\n"
1376             "  return; /* comment line 1\n"
1377             "           * comment line 2 */\n"
1378             "case 4: i = 8;\n"
1379             "// something else\n"
1380             "#if FOO\n"
1381             "case 5: break;\n"
1382             "#endif\n"
1383             "}",
1384             format("switch (a) {\n"
1385                    "case 1: x = 8;\n"
1386                    "  // fall through\n"
1387                    "case 2:\n"
1388                    "  x = 8;\n"
1389                    "// comment\n"
1390                    "case 3:\n"
1391                    "  return; /* comment line 1\n"
1392                    "           * comment line 2 */\n"
1393                    "case 4:\n"
1394                    "  i = 8;\n"
1395                    "// something else\n"
1396                    "#if FOO\n"
1397                    "case 5: break;\n"
1398                    "#endif\n"
1399                    "}",
1400                    Style));
1401   EXPECT_EQ("switch (a) {\n"
1402             "case 0:\n"
1403             "  return; // long long long long long long long long long long "
1404             "long long comment\n"
1405             "          // line\n"
1406             "}",
1407             format("switch (a) {\n"
1408                    "case 0: return; // long long long long long long long long "
1409                    "long long long long comment line\n"
1410                    "}",
1411                    Style));
1412   EXPECT_EQ("switch (a) {\n"
1413             "case 0:\n"
1414             "  return; /* long long long long long long long long long long "
1415             "long long comment\n"
1416             "             line */\n"
1417             "}",
1418             format("switch (a) {\n"
1419                    "case 0: return; /* long long long long long long long long "
1420                    "long long long long comment line */\n"
1421                    "}",
1422                    Style));
1423   verifyFormat("switch (a) {\n"
1424                "#if FOO\n"
1425                "case 0: return 0;\n"
1426                "#endif\n"
1427                "}",
1428                Style);
1429   verifyFormat("switch (a) {\n"
1430                "case 1: {\n"
1431                "}\n"
1432                "case 2: {\n"
1433                "  return;\n"
1434                "}\n"
1435                "case 3: {\n"
1436                "  x = 1;\n"
1437                "  return;\n"
1438                "}\n"
1439                "case 4:\n"
1440                "  if (x)\n"
1441                "    return;\n"
1442                "}",
1443                Style);
1444   Style.ColumnLimit = 21;
1445   verifyFormat("switch (a) {\n"
1446                "case 1: x = 1; break;\n"
1447                "case 2: return;\n"
1448                "case 3:\n"
1449                "case 4:\n"
1450                "case 5: return;\n"
1451                "default:\n"
1452                "  y = 1;\n"
1453                "  break;\n"
1454                "}",
1455                Style);
1456   Style.ColumnLimit = 80;
1457   Style.AllowShortCaseLabelsOnASingleLine = false;
1458   Style.IndentCaseLabels = true;
1459   EXPECT_EQ("switch (n) {\n"
1460             "  default /*comments*/:\n"
1461             "    return true;\n"
1462             "  case 0:\n"
1463             "    return false;\n"
1464             "}",
1465             format("switch (n) {\n"
1466                    "default/*comments*/:\n"
1467                    "  return true;\n"
1468                    "case 0:\n"
1469                    "  return false;\n"
1470                    "}",
1471                    Style));
1472   Style.AllowShortCaseLabelsOnASingleLine = true;
1473   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1474   Style.BraceWrapping.AfterCaseLabel = true;
1475   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1476   EXPECT_EQ("switch (n)\n"
1477             "{\n"
1478             "  case 0:\n"
1479             "  {\n"
1480             "    return false;\n"
1481             "  }\n"
1482             "  default:\n"
1483             "  {\n"
1484             "    return true;\n"
1485             "  }\n"
1486             "}",
1487             format("switch (n) {\n"
1488                    "  case 0: {\n"
1489                    "    return false;\n"
1490                    "  }\n"
1491                    "  default:\n"
1492                    "  {\n"
1493                    "    return true;\n"
1494                    "  }\n"
1495                    "}",
1496                    Style));
1497 }
1498 
1499 TEST_F(FormatTest, FormatsLabels) {
1500   verifyFormat("void f() {\n"
1501                "  some_code();\n"
1502                "test_label:\n"
1503                "  some_other_code();\n"
1504                "  {\n"
1505                "    some_more_code();\n"
1506                "  another_label:\n"
1507                "    some_more_code();\n"
1508                "  }\n"
1509                "}");
1510   verifyFormat("{\n"
1511                "  some_code();\n"
1512                "test_label:\n"
1513                "  some_other_code();\n"
1514                "}");
1515   verifyFormat("{\n"
1516                "  some_code();\n"
1517                "test_label:;\n"
1518                "  int i = 0;\n"
1519                "}");
1520   FormatStyle Style = getLLVMStyle();
1521   Style.IndentGotoLabels = false;
1522   verifyFormat("void f() {\n"
1523                "  some_code();\n"
1524                "test_label:\n"
1525                "  some_other_code();\n"
1526                "  {\n"
1527                "    some_more_code();\n"
1528                "another_label:\n"
1529                "    some_more_code();\n"
1530                "  }\n"
1531                "}",
1532                Style);
1533   verifyFormat("{\n"
1534                "  some_code();\n"
1535                "test_label:\n"
1536                "  some_other_code();\n"
1537                "}",
1538                Style);
1539   verifyFormat("{\n"
1540                "  some_code();\n"
1541                "test_label:;\n"
1542                "  int i = 0;\n"
1543                "}");
1544 }
1545 
1546 TEST_F(FormatTest, MultiLineControlStatements) {
1547   FormatStyle Style = getLLVMStyle();
1548   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
1549   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
1550   Style.ColumnLimit = 20;
1551   // Short lines should keep opening brace on same line.
1552   EXPECT_EQ("if (foo) {\n"
1553             "  bar();\n"
1554             "}",
1555             format("if(foo){bar();}", Style));
1556   EXPECT_EQ("if (foo) {\n"
1557             "  bar();\n"
1558             "} else {\n"
1559             "  baz();\n"
1560             "}",
1561             format("if(foo){bar();}else{baz();}", Style));
1562   EXPECT_EQ("if (foo && bar) {\n"
1563             "  baz();\n"
1564             "}",
1565             format("if(foo&&bar){baz();}", Style));
1566   EXPECT_EQ("if (foo) {\n"
1567             "  bar();\n"
1568             "} else if (baz) {\n"
1569             "  quux();\n"
1570             "}",
1571             format("if(foo){bar();}else if(baz){quux();}", Style));
1572   EXPECT_EQ(
1573       "if (foo) {\n"
1574       "  bar();\n"
1575       "} else if (baz) {\n"
1576       "  quux();\n"
1577       "} else {\n"
1578       "  foobar();\n"
1579       "}",
1580       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
1581   EXPECT_EQ("for (;;) {\n"
1582             "  foo();\n"
1583             "}",
1584             format("for(;;){foo();}"));
1585   EXPECT_EQ("while (1) {\n"
1586             "  foo();\n"
1587             "}",
1588             format("while(1){foo();}", Style));
1589   EXPECT_EQ("switch (foo) {\n"
1590             "case bar:\n"
1591             "  return;\n"
1592             "}",
1593             format("switch(foo){case bar:return;}", Style));
1594   EXPECT_EQ("try {\n"
1595             "  foo();\n"
1596             "} catch (...) {\n"
1597             "  bar();\n"
1598             "}",
1599             format("try{foo();}catch(...){bar();}", Style));
1600   EXPECT_EQ("do {\n"
1601             "  foo();\n"
1602             "} while (bar &&\n"
1603             "         baz);",
1604             format("do{foo();}while(bar&&baz);", Style));
1605   // Long lines should put opening brace on new line.
1606   EXPECT_EQ("if (foo && bar &&\n"
1607             "    baz)\n"
1608             "{\n"
1609             "  quux();\n"
1610             "}",
1611             format("if(foo&&bar&&baz){quux();}", Style));
1612   EXPECT_EQ("if (foo && bar &&\n"
1613             "    baz)\n"
1614             "{\n"
1615             "  quux();\n"
1616             "}",
1617             format("if (foo && bar &&\n"
1618                    "    baz) {\n"
1619                    "  quux();\n"
1620                    "}",
1621                    Style));
1622   EXPECT_EQ("if (foo) {\n"
1623             "  bar();\n"
1624             "} else if (baz ||\n"
1625             "           quux)\n"
1626             "{\n"
1627             "  foobar();\n"
1628             "}",
1629             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
1630   EXPECT_EQ(
1631       "if (foo) {\n"
1632       "  bar();\n"
1633       "} else if (baz ||\n"
1634       "           quux)\n"
1635       "{\n"
1636       "  foobar();\n"
1637       "} else {\n"
1638       "  barbaz();\n"
1639       "}",
1640       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
1641              Style));
1642   EXPECT_EQ("for (int i = 0;\n"
1643             "     i < 10; ++i)\n"
1644             "{\n"
1645             "  foo();\n"
1646             "}",
1647             format("for(int i=0;i<10;++i){foo();}", Style));
1648   EXPECT_EQ("while (foo || bar ||\n"
1649             "       baz)\n"
1650             "{\n"
1651             "  quux();\n"
1652             "}",
1653             format("while(foo||bar||baz){quux();}", Style));
1654   EXPECT_EQ("switch (\n"
1655             "    foo = barbaz)\n"
1656             "{\n"
1657             "case quux:\n"
1658             "  return;\n"
1659             "}",
1660             format("switch(foo=barbaz){case quux:return;}", Style));
1661   EXPECT_EQ("try {\n"
1662             "  foo();\n"
1663             "} catch (\n"
1664             "    Exception &bar)\n"
1665             "{\n"
1666             "  baz();\n"
1667             "}",
1668             format("try{foo();}catch(Exception&bar){baz();}", Style));
1669   Style.ColumnLimit =
1670       40; // to concentrate at brace wrapping, not line wrap due to column limit
1671   EXPECT_EQ("try {\n"
1672             "  foo();\n"
1673             "} catch (Exception &bar) {\n"
1674             "  baz();\n"
1675             "}",
1676             format("try{foo();}catch(Exception&bar){baz();}", Style));
1677   Style.ColumnLimit =
1678       20; // to concentrate at brace wrapping, not line wrap due to column limit
1679 
1680   Style.BraceWrapping.BeforeElse = true;
1681   EXPECT_EQ(
1682       "if (foo) {\n"
1683       "  bar();\n"
1684       "}\n"
1685       "else if (baz ||\n"
1686       "         quux)\n"
1687       "{\n"
1688       "  foobar();\n"
1689       "}\n"
1690       "else {\n"
1691       "  barbaz();\n"
1692       "}",
1693       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
1694              Style));
1695 
1696   Style.BraceWrapping.BeforeCatch = true;
1697   EXPECT_EQ("try {\n"
1698             "  foo();\n"
1699             "}\n"
1700             "catch (...) {\n"
1701             "  baz();\n"
1702             "}",
1703             format("try{foo();}catch(...){baz();}", Style));
1704 }
1705 
1706 //===----------------------------------------------------------------------===//
1707 // Tests for classes, namespaces, etc.
1708 //===----------------------------------------------------------------------===//
1709 
1710 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
1711   verifyFormat("class A {};");
1712 }
1713 
1714 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
1715   verifyFormat("class A {\n"
1716                "public:\n"
1717                "public: // comment\n"
1718                "protected:\n"
1719                "private:\n"
1720                "  void f() {}\n"
1721                "};");
1722   verifyFormat("export class A {\n"
1723                "public:\n"
1724                "public: // comment\n"
1725                "protected:\n"
1726                "private:\n"
1727                "  void f() {}\n"
1728                "};");
1729   verifyGoogleFormat("class A {\n"
1730                      " public:\n"
1731                      " protected:\n"
1732                      " private:\n"
1733                      "  void f() {}\n"
1734                      "};");
1735   verifyGoogleFormat("export class A {\n"
1736                      " public:\n"
1737                      " protected:\n"
1738                      " private:\n"
1739                      "  void f() {}\n"
1740                      "};");
1741   verifyFormat("class A {\n"
1742                "public slots:\n"
1743                "  void f1() {}\n"
1744                "public Q_SLOTS:\n"
1745                "  void f2() {}\n"
1746                "protected slots:\n"
1747                "  void f3() {}\n"
1748                "protected Q_SLOTS:\n"
1749                "  void f4() {}\n"
1750                "private slots:\n"
1751                "  void f5() {}\n"
1752                "private Q_SLOTS:\n"
1753                "  void f6() {}\n"
1754                "signals:\n"
1755                "  void g1();\n"
1756                "Q_SIGNALS:\n"
1757                "  void g2();\n"
1758                "};");
1759 
1760   // Don't interpret 'signals' the wrong way.
1761   verifyFormat("signals.set();");
1762   verifyFormat("for (Signals signals : f()) {\n}");
1763   verifyFormat("{\n"
1764                "  signals.set(); // This needs indentation.\n"
1765                "}");
1766   verifyFormat("void f() {\n"
1767                "label:\n"
1768                "  signals.baz();\n"
1769                "}");
1770 }
1771 
1772 TEST_F(FormatTest, SeparatesLogicalBlocks) {
1773   EXPECT_EQ("class A {\n"
1774             "public:\n"
1775             "  void f();\n"
1776             "\n"
1777             "private:\n"
1778             "  void g() {}\n"
1779             "  // test\n"
1780             "protected:\n"
1781             "  int h;\n"
1782             "};",
1783             format("class A {\n"
1784                    "public:\n"
1785                    "void f();\n"
1786                    "private:\n"
1787                    "void g() {}\n"
1788                    "// test\n"
1789                    "protected:\n"
1790                    "int h;\n"
1791                    "};"));
1792   EXPECT_EQ("class A {\n"
1793             "protected:\n"
1794             "public:\n"
1795             "  void f();\n"
1796             "};",
1797             format("class A {\n"
1798                    "protected:\n"
1799                    "\n"
1800                    "public:\n"
1801                    "\n"
1802                    "  void f();\n"
1803                    "};"));
1804 
1805   // Even ensure proper spacing inside macros.
1806   EXPECT_EQ("#define B     \\\n"
1807             "  class A {   \\\n"
1808             "   protected: \\\n"
1809             "   public:    \\\n"
1810             "    void f(); \\\n"
1811             "  };",
1812             format("#define B     \\\n"
1813                    "  class A {   \\\n"
1814                    "   protected: \\\n"
1815                    "              \\\n"
1816                    "   public:    \\\n"
1817                    "              \\\n"
1818                    "    void f(); \\\n"
1819                    "  };",
1820                    getGoogleStyle()));
1821   // But don't remove empty lines after macros ending in access specifiers.
1822   EXPECT_EQ("#define A private:\n"
1823             "\n"
1824             "int i;",
1825             format("#define A         private:\n"
1826                    "\n"
1827                    "int              i;"));
1828 }
1829 
1830 TEST_F(FormatTest, FormatsClasses) {
1831   verifyFormat("class A : public B {};");
1832   verifyFormat("class A : public ::B {};");
1833 
1834   verifyFormat(
1835       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1836       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1837   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
1838                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1839                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1840   verifyFormat(
1841       "class A : public B, public C, public D, public E, public F {};");
1842   verifyFormat("class AAAAAAAAAAAA : public B,\n"
1843                "                     public C,\n"
1844                "                     public D,\n"
1845                "                     public E,\n"
1846                "                     public F,\n"
1847                "                     public G {};");
1848 
1849   verifyFormat("class\n"
1850                "    ReallyReallyLongClassName {\n"
1851                "  int i;\n"
1852                "};",
1853                getLLVMStyleWithColumns(32));
1854   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
1855                "                           aaaaaaaaaaaaaaaa> {};");
1856   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
1857                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
1858                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
1859   verifyFormat("template <class R, class C>\n"
1860                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
1861                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
1862   verifyFormat("class ::A::B {};");
1863 }
1864 
1865 TEST_F(FormatTest, BreakInheritanceStyle) {
1866   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
1867   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
1868       FormatStyle::BILS_BeforeComma;
1869   verifyFormat("class MyClass : public X {};",
1870                StyleWithInheritanceBreakBeforeComma);
1871   verifyFormat("class MyClass\n"
1872                "    : public X\n"
1873                "    , public Y {};",
1874                StyleWithInheritanceBreakBeforeComma);
1875   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
1876                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
1877                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
1878                StyleWithInheritanceBreakBeforeComma);
1879   verifyFormat("struct aaaaaaaaaaaaa\n"
1880                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
1881                "          aaaaaaaaaaaaaaaa> {};",
1882                StyleWithInheritanceBreakBeforeComma);
1883 
1884   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
1885   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
1886       FormatStyle::BILS_AfterColon;
1887   verifyFormat("class MyClass : public X {};",
1888                StyleWithInheritanceBreakAfterColon);
1889   verifyFormat("class MyClass : public X, public Y {};",
1890                StyleWithInheritanceBreakAfterColon);
1891   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
1892                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1893                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
1894                StyleWithInheritanceBreakAfterColon);
1895   verifyFormat("struct aaaaaaaaaaaaa :\n"
1896                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
1897                "        aaaaaaaaaaaaaaaa> {};",
1898                StyleWithInheritanceBreakAfterColon);
1899 }
1900 
1901 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
1902   verifyFormat("class A {\n} a, b;");
1903   verifyFormat("struct A {\n} a, b;");
1904   verifyFormat("union A {\n} a;");
1905 }
1906 
1907 TEST_F(FormatTest, FormatsEnum) {
1908   verifyFormat("enum {\n"
1909                "  Zero,\n"
1910                "  One = 1,\n"
1911                "  Two = One + 1,\n"
1912                "  Three = (One + Two),\n"
1913                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1914                "  Five = (One, Two, Three, Four, 5)\n"
1915                "};");
1916   verifyGoogleFormat("enum {\n"
1917                      "  Zero,\n"
1918                      "  One = 1,\n"
1919                      "  Two = One + 1,\n"
1920                      "  Three = (One + Two),\n"
1921                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1922                      "  Five = (One, Two, Three, Four, 5)\n"
1923                      "};");
1924   verifyFormat("enum Enum {};");
1925   verifyFormat("enum {};");
1926   verifyFormat("enum X E {} d;");
1927   verifyFormat("enum __attribute__((...)) E {} d;");
1928   verifyFormat("enum __declspec__((...)) E {} d;");
1929   verifyFormat("enum {\n"
1930                "  Bar = Foo<int, int>::value\n"
1931                "};",
1932                getLLVMStyleWithColumns(30));
1933 
1934   verifyFormat("enum ShortEnum { A, B, C };");
1935   verifyGoogleFormat("enum ShortEnum { A, B, C };");
1936 
1937   EXPECT_EQ("enum KeepEmptyLines {\n"
1938             "  ONE,\n"
1939             "\n"
1940             "  TWO,\n"
1941             "\n"
1942             "  THREE\n"
1943             "}",
1944             format("enum KeepEmptyLines {\n"
1945                    "  ONE,\n"
1946                    "\n"
1947                    "  TWO,\n"
1948                    "\n"
1949                    "\n"
1950                    "  THREE\n"
1951                    "}"));
1952   verifyFormat("enum E { // comment\n"
1953                "  ONE,\n"
1954                "  TWO\n"
1955                "};\n"
1956                "int i;");
1957 
1958   FormatStyle EightIndent = getLLVMStyle();
1959   EightIndent.IndentWidth = 8;
1960   verifyFormat("enum {\n"
1961                "        VOID,\n"
1962                "        CHAR,\n"
1963                "        SHORT,\n"
1964                "        INT,\n"
1965                "        LONG,\n"
1966                "        SIGNED,\n"
1967                "        UNSIGNED,\n"
1968                "        BOOL,\n"
1969                "        FLOAT,\n"
1970                "        DOUBLE,\n"
1971                "        COMPLEX\n"
1972                "};",
1973                EightIndent);
1974 
1975   // Not enums.
1976   verifyFormat("enum X f() {\n"
1977                "  a();\n"
1978                "  return 42;\n"
1979                "}");
1980   verifyFormat("enum X Type::f() {\n"
1981                "  a();\n"
1982                "  return 42;\n"
1983                "}");
1984   verifyFormat("enum ::X f() {\n"
1985                "  a();\n"
1986                "  return 42;\n"
1987                "}");
1988   verifyFormat("enum ns::X f() {\n"
1989                "  a();\n"
1990                "  return 42;\n"
1991                "}");
1992 }
1993 
1994 TEST_F(FormatTest, FormatsEnumsWithErrors) {
1995   verifyFormat("enum Type {\n"
1996                "  One = 0; // These semicolons should be commas.\n"
1997                "  Two = 1;\n"
1998                "};");
1999   verifyFormat("namespace n {\n"
2000                "enum Type {\n"
2001                "  One,\n"
2002                "  Two, // missing };\n"
2003                "  int i;\n"
2004                "}\n"
2005                "void g() {}");
2006 }
2007 
2008 TEST_F(FormatTest, FormatsEnumStruct) {
2009   verifyFormat("enum struct {\n"
2010                "  Zero,\n"
2011                "  One = 1,\n"
2012                "  Two = One + 1,\n"
2013                "  Three = (One + Two),\n"
2014                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2015                "  Five = (One, Two, Three, Four, 5)\n"
2016                "};");
2017   verifyFormat("enum struct Enum {};");
2018   verifyFormat("enum struct {};");
2019   verifyFormat("enum struct X E {} d;");
2020   verifyFormat("enum struct __attribute__((...)) E {} d;");
2021   verifyFormat("enum struct __declspec__((...)) E {} d;");
2022   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
2023 }
2024 
2025 TEST_F(FormatTest, FormatsEnumClass) {
2026   verifyFormat("enum class {\n"
2027                "  Zero,\n"
2028                "  One = 1,\n"
2029                "  Two = One + 1,\n"
2030                "  Three = (One + Two),\n"
2031                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2032                "  Five = (One, Two, Three, Four, 5)\n"
2033                "};");
2034   verifyFormat("enum class Enum {};");
2035   verifyFormat("enum class {};");
2036   verifyFormat("enum class X E {} d;");
2037   verifyFormat("enum class __attribute__((...)) E {} d;");
2038   verifyFormat("enum class __declspec__((...)) E {} d;");
2039   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
2040 }
2041 
2042 TEST_F(FormatTest, FormatsEnumTypes) {
2043   verifyFormat("enum X : int {\n"
2044                "  A, // Force multiple lines.\n"
2045                "  B\n"
2046                "};");
2047   verifyFormat("enum X : int { A, B };");
2048   verifyFormat("enum X : std::uint32_t { A, B };");
2049 }
2050 
2051 TEST_F(FormatTest, FormatsTypedefEnum) {
2052   FormatStyle Style = getLLVMStyle();
2053   Style.ColumnLimit = 40;
2054   verifyFormat("typedef enum {} EmptyEnum;");
2055   verifyFormat("typedef enum { A, B, C } ShortEnum;");
2056   verifyFormat("typedef enum {\n"
2057                "  ZERO = 0,\n"
2058                "  ONE = 1,\n"
2059                "  TWO = 2,\n"
2060                "  THREE = 3\n"
2061                "} LongEnum;",
2062                Style);
2063   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2064   Style.BraceWrapping.AfterEnum = true;
2065   verifyFormat("typedef enum {} EmptyEnum;");
2066   verifyFormat("typedef enum { A, B, C } ShortEnum;");
2067   verifyFormat("typedef enum\n"
2068                "{\n"
2069                "  ZERO = 0,\n"
2070                "  ONE = 1,\n"
2071                "  TWO = 2,\n"
2072                "  THREE = 3\n"
2073                "} LongEnum;",
2074                Style);
2075 }
2076 
2077 TEST_F(FormatTest, FormatsNSEnums) {
2078   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
2079   verifyGoogleFormat(
2080       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
2081   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
2082                      "  // Information about someDecentlyLongValue.\n"
2083                      "  someDecentlyLongValue,\n"
2084                      "  // Information about anotherDecentlyLongValue.\n"
2085                      "  anotherDecentlyLongValue,\n"
2086                      "  // Information about aThirdDecentlyLongValue.\n"
2087                      "  aThirdDecentlyLongValue\n"
2088                      "};");
2089   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
2090                      "  // Information about someDecentlyLongValue.\n"
2091                      "  someDecentlyLongValue,\n"
2092                      "  // Information about anotherDecentlyLongValue.\n"
2093                      "  anotherDecentlyLongValue,\n"
2094                      "  // Information about aThirdDecentlyLongValue.\n"
2095                      "  aThirdDecentlyLongValue\n"
2096                      "};");
2097   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
2098                      "  a = 1,\n"
2099                      "  b = 2,\n"
2100                      "  c = 3,\n"
2101                      "};");
2102   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
2103                      "  a = 1,\n"
2104                      "  b = 2,\n"
2105                      "  c = 3,\n"
2106                      "};");
2107   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
2108                      "  a = 1,\n"
2109                      "  b = 2,\n"
2110                      "  c = 3,\n"
2111                      "};");
2112   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
2113                      "  a = 1,\n"
2114                      "  b = 2,\n"
2115                      "  c = 3,\n"
2116                      "};");
2117 }
2118 
2119 TEST_F(FormatTest, FormatsBitfields) {
2120   verifyFormat("struct Bitfields {\n"
2121                "  unsigned sClass : 8;\n"
2122                "  unsigned ValueKind : 2;\n"
2123                "};");
2124   verifyFormat("struct A {\n"
2125                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
2126                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
2127                "};");
2128   verifyFormat("struct MyStruct {\n"
2129                "  uchar data;\n"
2130                "  uchar : 8;\n"
2131                "  uchar : 8;\n"
2132                "  uchar other;\n"
2133                "};");
2134 }
2135 
2136 TEST_F(FormatTest, FormatsNamespaces) {
2137   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
2138   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
2139 
2140   verifyFormat("namespace some_namespace {\n"
2141                "class A {};\n"
2142                "void f() { f(); }\n"
2143                "}",
2144                LLVMWithNoNamespaceFix);
2145   verifyFormat("namespace N::inline D {\n"
2146                "class A {};\n"
2147                "void f() { f(); }\n"
2148                "}",
2149                LLVMWithNoNamespaceFix);
2150   verifyFormat("namespace N::inline D::E {\n"
2151                "class A {};\n"
2152                "void f() { f(); }\n"
2153                "}",
2154                LLVMWithNoNamespaceFix);
2155   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
2156                "class A {};\n"
2157                "void f() { f(); }\n"
2158                "}",
2159                LLVMWithNoNamespaceFix);
2160   verifyFormat("/* something */ namespace some_namespace {\n"
2161                "class A {};\n"
2162                "void f() { f(); }\n"
2163                "}",
2164                LLVMWithNoNamespaceFix);
2165   verifyFormat("namespace {\n"
2166                "class A {};\n"
2167                "void f() { f(); }\n"
2168                "}",
2169                LLVMWithNoNamespaceFix);
2170   verifyFormat("/* something */ namespace {\n"
2171                "class A {};\n"
2172                "void f() { f(); }\n"
2173                "}",
2174                LLVMWithNoNamespaceFix);
2175   verifyFormat("inline namespace X {\n"
2176                "class A {};\n"
2177                "void f() { f(); }\n"
2178                "}",
2179                LLVMWithNoNamespaceFix);
2180   verifyFormat("/* something */ inline namespace X {\n"
2181                "class A {};\n"
2182                "void f() { f(); }\n"
2183                "}",
2184                LLVMWithNoNamespaceFix);
2185   verifyFormat("export namespace X {\n"
2186                "class A {};\n"
2187                "void f() { f(); }\n"
2188                "}",
2189                LLVMWithNoNamespaceFix);
2190   verifyFormat("using namespace some_namespace;\n"
2191                "class A {};\n"
2192                "void f() { f(); }",
2193                LLVMWithNoNamespaceFix);
2194 
2195   // This code is more common than we thought; if we
2196   // layout this correctly the semicolon will go into
2197   // its own line, which is undesirable.
2198   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
2199   verifyFormat("namespace {\n"
2200                "class A {};\n"
2201                "};",
2202                LLVMWithNoNamespaceFix);
2203 
2204   verifyFormat("namespace {\n"
2205                "int SomeVariable = 0; // comment\n"
2206                "} // namespace",
2207                LLVMWithNoNamespaceFix);
2208   EXPECT_EQ("#ifndef HEADER_GUARD\n"
2209             "#define HEADER_GUARD\n"
2210             "namespace my_namespace {\n"
2211             "int i;\n"
2212             "} // my_namespace\n"
2213             "#endif // HEADER_GUARD",
2214             format("#ifndef HEADER_GUARD\n"
2215                    " #define HEADER_GUARD\n"
2216                    "   namespace my_namespace {\n"
2217                    "int i;\n"
2218                    "}    // my_namespace\n"
2219                    "#endif    // HEADER_GUARD",
2220                    LLVMWithNoNamespaceFix));
2221 
2222   EXPECT_EQ("namespace A::B {\n"
2223             "class C {};\n"
2224             "}",
2225             format("namespace A::B {\n"
2226                    "class C {};\n"
2227                    "}",
2228                    LLVMWithNoNamespaceFix));
2229 
2230   FormatStyle Style = getLLVMStyle();
2231   Style.NamespaceIndentation = FormatStyle::NI_All;
2232   EXPECT_EQ("namespace out {\n"
2233             "  int i;\n"
2234             "  namespace in {\n"
2235             "    int i;\n"
2236             "  } // namespace in\n"
2237             "} // namespace out",
2238             format("namespace out {\n"
2239                    "int i;\n"
2240                    "namespace in {\n"
2241                    "int i;\n"
2242                    "} // namespace in\n"
2243                    "} // namespace out",
2244                    Style));
2245 
2246   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2247   EXPECT_EQ("namespace out {\n"
2248             "int i;\n"
2249             "namespace in {\n"
2250             "  int i;\n"
2251             "} // namespace in\n"
2252             "} // namespace out",
2253             format("namespace out {\n"
2254                    "int i;\n"
2255                    "namespace in {\n"
2256                    "int i;\n"
2257                    "} // namespace in\n"
2258                    "} // namespace out",
2259                    Style));
2260 }
2261 
2262 TEST_F(FormatTest, NamespaceMacros) {
2263   FormatStyle Style = getLLVMStyle();
2264   Style.NamespaceMacros.push_back("TESTSUITE");
2265 
2266   verifyFormat("TESTSUITE(A) {\n"
2267                "int foo();\n"
2268                "} // TESTSUITE(A)",
2269                Style);
2270 
2271   verifyFormat("TESTSUITE(A, B) {\n"
2272                "int foo();\n"
2273                "} // TESTSUITE(A)",
2274                Style);
2275 
2276   // Properly indent according to NamespaceIndentation style
2277   Style.NamespaceIndentation = FormatStyle::NI_All;
2278   verifyFormat("TESTSUITE(A) {\n"
2279                "  int foo();\n"
2280                "} // TESTSUITE(A)",
2281                Style);
2282   verifyFormat("TESTSUITE(A) {\n"
2283                "  namespace B {\n"
2284                "    int foo();\n"
2285                "  } // namespace B\n"
2286                "} // TESTSUITE(A)",
2287                Style);
2288   verifyFormat("namespace A {\n"
2289                "  TESTSUITE(B) {\n"
2290                "    int foo();\n"
2291                "  } // TESTSUITE(B)\n"
2292                "} // namespace A",
2293                Style);
2294 
2295   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2296   verifyFormat("TESTSUITE(A) {\n"
2297                "TESTSUITE(B) {\n"
2298                "  int foo();\n"
2299                "} // TESTSUITE(B)\n"
2300                "} // TESTSUITE(A)",
2301                Style);
2302   verifyFormat("TESTSUITE(A) {\n"
2303                "namespace B {\n"
2304                "  int foo();\n"
2305                "} // namespace B\n"
2306                "} // TESTSUITE(A)",
2307                Style);
2308   verifyFormat("namespace A {\n"
2309                "TESTSUITE(B) {\n"
2310                "  int foo();\n"
2311                "} // TESTSUITE(B)\n"
2312                "} // namespace A",
2313                Style);
2314 
2315   // Properly merge namespace-macros blocks in CompactNamespaces mode
2316   Style.NamespaceIndentation = FormatStyle::NI_None;
2317   Style.CompactNamespaces = true;
2318   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
2319                "}} // TESTSUITE(A::B)",
2320                Style);
2321 
2322   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2323             "}} // TESTSUITE(out::in)",
2324             format("TESTSUITE(out) {\n"
2325                    "TESTSUITE(in) {\n"
2326                    "} // TESTSUITE(in)\n"
2327                    "} // TESTSUITE(out)",
2328                    Style));
2329 
2330   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2331             "}} // TESTSUITE(out::in)",
2332             format("TESTSUITE(out) {\n"
2333                    "TESTSUITE(in) {\n"
2334                    "} // TESTSUITE(in)\n"
2335                    "} // TESTSUITE(out)",
2336                    Style));
2337 
2338   // Do not merge different namespaces/macros
2339   EXPECT_EQ("namespace out {\n"
2340             "TESTSUITE(in) {\n"
2341             "} // TESTSUITE(in)\n"
2342             "} // namespace out",
2343             format("namespace out {\n"
2344                    "TESTSUITE(in) {\n"
2345                    "} // TESTSUITE(in)\n"
2346                    "} // namespace out",
2347                    Style));
2348   EXPECT_EQ("TESTSUITE(out) {\n"
2349             "namespace in {\n"
2350             "} // namespace in\n"
2351             "} // TESTSUITE(out)",
2352             format("TESTSUITE(out) {\n"
2353                    "namespace in {\n"
2354                    "} // namespace in\n"
2355                    "} // TESTSUITE(out)",
2356                    Style));
2357   Style.NamespaceMacros.push_back("FOOBAR");
2358   EXPECT_EQ("TESTSUITE(out) {\n"
2359             "FOOBAR(in) {\n"
2360             "} // FOOBAR(in)\n"
2361             "} // TESTSUITE(out)",
2362             format("TESTSUITE(out) {\n"
2363                    "FOOBAR(in) {\n"
2364                    "} // FOOBAR(in)\n"
2365                    "} // TESTSUITE(out)",
2366                    Style));
2367 }
2368 
2369 TEST_F(FormatTest, FormatsCompactNamespaces) {
2370   FormatStyle Style = getLLVMStyle();
2371   Style.CompactNamespaces = true;
2372   Style.NamespaceMacros.push_back("TESTSUITE");
2373 
2374   verifyFormat("namespace A { namespace B {\n"
2375                "}} // namespace A::B",
2376                Style);
2377 
2378   EXPECT_EQ("namespace out { namespace in {\n"
2379             "}} // namespace out::in",
2380             format("namespace out {\n"
2381                    "namespace in {\n"
2382                    "} // namespace in\n"
2383                    "} // namespace out",
2384                    Style));
2385 
2386   // Only namespaces which have both consecutive opening and end get compacted
2387   EXPECT_EQ("namespace out {\n"
2388             "namespace in1 {\n"
2389             "} // namespace in1\n"
2390             "namespace in2 {\n"
2391             "} // namespace in2\n"
2392             "} // namespace out",
2393             format("namespace out {\n"
2394                    "namespace in1 {\n"
2395                    "} // namespace in1\n"
2396                    "namespace in2 {\n"
2397                    "} // namespace in2\n"
2398                    "} // namespace out",
2399                    Style));
2400 
2401   EXPECT_EQ("namespace out {\n"
2402             "int i;\n"
2403             "namespace in {\n"
2404             "int j;\n"
2405             "} // namespace in\n"
2406             "int k;\n"
2407             "} // namespace out",
2408             format("namespace out { int i;\n"
2409                    "namespace in { int j; } // namespace in\n"
2410                    "int k; } // namespace out",
2411                    Style));
2412 
2413   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
2414             "}}} // namespace A::B::C\n",
2415             format("namespace A { namespace B {\n"
2416                    "namespace C {\n"
2417                    "}} // namespace B::C\n"
2418                    "} // namespace A\n",
2419                    Style));
2420 
2421   Style.ColumnLimit = 40;
2422   EXPECT_EQ("namespace aaaaaaaaaa {\n"
2423             "namespace bbbbbbbbbb {\n"
2424             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
2425             format("namespace aaaaaaaaaa {\n"
2426                    "namespace bbbbbbbbbb {\n"
2427                    "} // namespace bbbbbbbbbb\n"
2428                    "} // namespace aaaaaaaaaa",
2429                    Style));
2430 
2431   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
2432             "namespace cccccc {\n"
2433             "}}} // namespace aaaaaa::bbbbbb::cccccc",
2434             format("namespace aaaaaa {\n"
2435                    "namespace bbbbbb {\n"
2436                    "namespace cccccc {\n"
2437                    "} // namespace cccccc\n"
2438                    "} // namespace bbbbbb\n"
2439                    "} // namespace aaaaaa",
2440                    Style));
2441   Style.ColumnLimit = 80;
2442 
2443   // Extra semicolon after 'inner' closing brace prevents merging
2444   EXPECT_EQ("namespace out { namespace in {\n"
2445             "}; } // namespace out::in",
2446             format("namespace out {\n"
2447                    "namespace in {\n"
2448                    "}; // namespace in\n"
2449                    "} // namespace out",
2450                    Style));
2451 
2452   // Extra semicolon after 'outer' closing brace is conserved
2453   EXPECT_EQ("namespace out { namespace in {\n"
2454             "}}; // namespace out::in",
2455             format("namespace out {\n"
2456                    "namespace in {\n"
2457                    "} // namespace in\n"
2458                    "}; // namespace out",
2459                    Style));
2460 
2461   Style.NamespaceIndentation = FormatStyle::NI_All;
2462   EXPECT_EQ("namespace out { namespace in {\n"
2463             "  int i;\n"
2464             "}} // namespace out::in",
2465             format("namespace out {\n"
2466                    "namespace in {\n"
2467                    "int i;\n"
2468                    "} // namespace in\n"
2469                    "} // namespace out",
2470                    Style));
2471   EXPECT_EQ("namespace out { namespace mid {\n"
2472             "  namespace in {\n"
2473             "    int j;\n"
2474             "  } // namespace in\n"
2475             "  int k;\n"
2476             "}} // namespace out::mid",
2477             format("namespace out { namespace mid {\n"
2478                    "namespace in { int j; } // namespace in\n"
2479                    "int k; }} // namespace out::mid",
2480                    Style));
2481 
2482   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2483   EXPECT_EQ("namespace out { namespace in {\n"
2484             "  int i;\n"
2485             "}} // namespace out::in",
2486             format("namespace out {\n"
2487                    "namespace in {\n"
2488                    "int i;\n"
2489                    "} // namespace in\n"
2490                    "} // namespace out",
2491                    Style));
2492   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
2493             "  int i;\n"
2494             "}}} // namespace out::mid::in",
2495             format("namespace out {\n"
2496                    "namespace mid {\n"
2497                    "namespace in {\n"
2498                    "int i;\n"
2499                    "} // namespace in\n"
2500                    "} // namespace mid\n"
2501                    "} // namespace out",
2502                    Style));
2503 }
2504 
2505 TEST_F(FormatTest, FormatsExternC) {
2506   verifyFormat("extern \"C\" {\nint a;");
2507   verifyFormat("extern \"C\" {}");
2508   verifyFormat("extern \"C\" {\n"
2509                "int foo();\n"
2510                "}");
2511   verifyFormat("extern \"C\" int foo() {}");
2512   verifyFormat("extern \"C\" int foo();");
2513   verifyFormat("extern \"C\" int foo() {\n"
2514                "  int i = 42;\n"
2515                "  return i;\n"
2516                "}");
2517 
2518   FormatStyle Style = getLLVMStyle();
2519   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2520   Style.BraceWrapping.AfterFunction = true;
2521   verifyFormat("extern \"C\" int foo() {}", Style);
2522   verifyFormat("extern \"C\" int foo();", Style);
2523   verifyFormat("extern \"C\" int foo()\n"
2524                "{\n"
2525                "  int i = 42;\n"
2526                "  return i;\n"
2527                "}",
2528                Style);
2529 
2530   Style.BraceWrapping.AfterExternBlock = true;
2531   Style.BraceWrapping.SplitEmptyRecord = false;
2532   verifyFormat("extern \"C\"\n"
2533                "{}",
2534                Style);
2535   verifyFormat("extern \"C\"\n"
2536                "{\n"
2537                "  int foo();\n"
2538                "}",
2539                Style);
2540 }
2541 
2542 TEST_F(FormatTest, FormatsInlineASM) {
2543   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
2544   verifyFormat("asm(\"nop\" ::: \"memory\");");
2545   verifyFormat(
2546       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
2547       "    \"cpuid\\n\\t\"\n"
2548       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
2549       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
2550       "    : \"a\"(value));");
2551   EXPECT_EQ(
2552       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
2553       "  __asm {\n"
2554       "        mov     edx,[that] // vtable in edx\n"
2555       "        mov     eax,methodIndex\n"
2556       "        call    [edx][eax*4] // stdcall\n"
2557       "  }\n"
2558       "}",
2559       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
2560              "    __asm {\n"
2561              "        mov     edx,[that] // vtable in edx\n"
2562              "        mov     eax,methodIndex\n"
2563              "        call    [edx][eax*4] // stdcall\n"
2564              "    }\n"
2565              "}"));
2566   EXPECT_EQ("_asm {\n"
2567             "  xor eax, eax;\n"
2568             "  cpuid;\n"
2569             "}",
2570             format("_asm {\n"
2571                    "  xor eax, eax;\n"
2572                    "  cpuid;\n"
2573                    "}"));
2574   verifyFormat("void function() {\n"
2575                "  // comment\n"
2576                "  asm(\"\");\n"
2577                "}");
2578   EXPECT_EQ("__asm {\n"
2579             "}\n"
2580             "int i;",
2581             format("__asm   {\n"
2582                    "}\n"
2583                    "int   i;"));
2584 }
2585 
2586 TEST_F(FormatTest, FormatTryCatch) {
2587   verifyFormat("try {\n"
2588                "  throw a * b;\n"
2589                "} catch (int a) {\n"
2590                "  // Do nothing.\n"
2591                "} catch (...) {\n"
2592                "  exit(42);\n"
2593                "}");
2594 
2595   // Function-level try statements.
2596   verifyFormat("int f() try { return 4; } catch (...) {\n"
2597                "  return 5;\n"
2598                "}");
2599   verifyFormat("class A {\n"
2600                "  int a;\n"
2601                "  A() try : a(0) {\n"
2602                "  } catch (...) {\n"
2603                "    throw;\n"
2604                "  }\n"
2605                "};\n");
2606 
2607   // Incomplete try-catch blocks.
2608   verifyIncompleteFormat("try {} catch (");
2609 }
2610 
2611 TEST_F(FormatTest, FormatSEHTryCatch) {
2612   verifyFormat("__try {\n"
2613                "  int a = b * c;\n"
2614                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
2615                "  // Do nothing.\n"
2616                "}");
2617 
2618   verifyFormat("__try {\n"
2619                "  int a = b * c;\n"
2620                "} __finally {\n"
2621                "  // Do nothing.\n"
2622                "}");
2623 
2624   verifyFormat("DEBUG({\n"
2625                "  __try {\n"
2626                "  } __finally {\n"
2627                "  }\n"
2628                "});\n");
2629 }
2630 
2631 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
2632   verifyFormat("try {\n"
2633                "  f();\n"
2634                "} catch {\n"
2635                "  g();\n"
2636                "}");
2637   verifyFormat("try {\n"
2638                "  f();\n"
2639                "} catch (A a) MACRO(x) {\n"
2640                "  g();\n"
2641                "} catch (B b) MACRO(x) {\n"
2642                "  g();\n"
2643                "}");
2644 }
2645 
2646 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
2647   FormatStyle Style = getLLVMStyle();
2648   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
2649                           FormatStyle::BS_WebKit}) {
2650     Style.BreakBeforeBraces = BraceStyle;
2651     verifyFormat("try {\n"
2652                  "  // something\n"
2653                  "} catch (...) {\n"
2654                  "  // something\n"
2655                  "}",
2656                  Style);
2657   }
2658   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
2659   verifyFormat("try {\n"
2660                "  // something\n"
2661                "}\n"
2662                "catch (...) {\n"
2663                "  // something\n"
2664                "}",
2665                Style);
2666   verifyFormat("__try {\n"
2667                "  // something\n"
2668                "}\n"
2669                "__finally {\n"
2670                "  // something\n"
2671                "}",
2672                Style);
2673   verifyFormat("@try {\n"
2674                "  // something\n"
2675                "}\n"
2676                "@finally {\n"
2677                "  // something\n"
2678                "}",
2679                Style);
2680   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
2681   verifyFormat("try\n"
2682                "{\n"
2683                "  // something\n"
2684                "}\n"
2685                "catch (...)\n"
2686                "{\n"
2687                "  // something\n"
2688                "}",
2689                Style);
2690   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
2691   verifyFormat("try\n"
2692                "  {\n"
2693                "  // something white\n"
2694                "  }\n"
2695                "catch (...)\n"
2696                "  {\n"
2697                "  // something white\n"
2698                "  }",
2699                Style);
2700   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2701   verifyFormat("try\n"
2702                "  {\n"
2703                "    // something\n"
2704                "  }\n"
2705                "catch (...)\n"
2706                "  {\n"
2707                "    // something\n"
2708                "  }",
2709                Style);
2710   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2711   Style.BraceWrapping.BeforeCatch = true;
2712   verifyFormat("try {\n"
2713                "  // something\n"
2714                "}\n"
2715                "catch (...) {\n"
2716                "  // something\n"
2717                "}",
2718                Style);
2719 }
2720 
2721 TEST_F(FormatTest, StaticInitializers) {
2722   verifyFormat("static SomeClass SC = {1, 'a'};");
2723 
2724   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
2725                "    100000000, "
2726                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
2727 
2728   // Here, everything other than the "}" would fit on a line.
2729   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
2730                "    10000000000000000000000000};");
2731   EXPECT_EQ("S s = {a,\n"
2732             "\n"
2733             "       b};",
2734             format("S s = {\n"
2735                    "  a,\n"
2736                    "\n"
2737                    "  b\n"
2738                    "};"));
2739 
2740   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
2741   // line. However, the formatting looks a bit off and this probably doesn't
2742   // happen often in practice.
2743   verifyFormat("static int Variable[1] = {\n"
2744                "    {1000000000000000000000000000000000000}};",
2745                getLLVMStyleWithColumns(40));
2746 }
2747 
2748 TEST_F(FormatTest, DesignatedInitializers) {
2749   verifyFormat("const struct A a = {.a = 1, .b = 2};");
2750   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
2751                "                    .bbbbbbbbbb = 2,\n"
2752                "                    .cccccccccc = 3,\n"
2753                "                    .dddddddddd = 4,\n"
2754                "                    .eeeeeeeeee = 5};");
2755   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2756                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
2757                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
2758                "    .ccccccccccccccccccccccccccc = 3,\n"
2759                "    .ddddddddddddddddddddddddddd = 4,\n"
2760                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
2761 
2762   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
2763 
2764   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
2765   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
2766                "                    [2] = bbbbbbbbbb,\n"
2767                "                    [3] = cccccccccc,\n"
2768                "                    [4] = dddddddddd,\n"
2769                "                    [5] = eeeeeeeeee};");
2770   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2771                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2772                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
2773                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
2774                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
2775                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
2776 }
2777 
2778 TEST_F(FormatTest, NestedStaticInitializers) {
2779   verifyFormat("static A x = {{{}}};\n");
2780   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
2781                "               {init1, init2, init3, init4}}};",
2782                getLLVMStyleWithColumns(50));
2783 
2784   verifyFormat("somes Status::global_reps[3] = {\n"
2785                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2786                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2787                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
2788                getLLVMStyleWithColumns(60));
2789   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
2790                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2791                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2792                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
2793   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
2794                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
2795                "rect.fTop}};");
2796 
2797   verifyFormat(
2798       "SomeArrayOfSomeType a = {\n"
2799       "    {{1, 2, 3},\n"
2800       "     {1, 2, 3},\n"
2801       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
2802       "      333333333333333333333333333333},\n"
2803       "     {1, 2, 3},\n"
2804       "     {1, 2, 3}}};");
2805   verifyFormat(
2806       "SomeArrayOfSomeType a = {\n"
2807       "    {{1, 2, 3}},\n"
2808       "    {{1, 2, 3}},\n"
2809       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
2810       "      333333333333333333333333333333}},\n"
2811       "    {{1, 2, 3}},\n"
2812       "    {{1, 2, 3}}};");
2813 
2814   verifyFormat("struct {\n"
2815                "  unsigned bit;\n"
2816                "  const char *const name;\n"
2817                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
2818                "                 {kOsWin, \"Windows\"},\n"
2819                "                 {kOsLinux, \"Linux\"},\n"
2820                "                 {kOsCrOS, \"Chrome OS\"}};");
2821   verifyFormat("struct {\n"
2822                "  unsigned bit;\n"
2823                "  const char *const name;\n"
2824                "} kBitsToOs[] = {\n"
2825                "    {kOsMac, \"Mac\"},\n"
2826                "    {kOsWin, \"Windows\"},\n"
2827                "    {kOsLinux, \"Linux\"},\n"
2828                "    {kOsCrOS, \"Chrome OS\"},\n"
2829                "};");
2830 }
2831 
2832 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
2833   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
2834                "                      \\\n"
2835                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
2836 }
2837 
2838 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
2839   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
2840                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
2841 
2842   // Do break defaulted and deleted functions.
2843   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
2844                "    default;",
2845                getLLVMStyleWithColumns(40));
2846   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
2847                "    delete;",
2848                getLLVMStyleWithColumns(40));
2849 }
2850 
2851 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
2852   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
2853                getLLVMStyleWithColumns(40));
2854   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
2855                getLLVMStyleWithColumns(40));
2856   EXPECT_EQ("#define Q                              \\\n"
2857             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
2858             "  \"aaaaaaaa.cpp\"",
2859             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
2860                    getLLVMStyleWithColumns(40)));
2861 }
2862 
2863 TEST_F(FormatTest, UnderstandsLinePPDirective) {
2864   EXPECT_EQ("# 123 \"A string literal\"",
2865             format("   #     123    \"A string literal\""));
2866 }
2867 
2868 TEST_F(FormatTest, LayoutUnknownPPDirective) {
2869   EXPECT_EQ("#;", format("#;"));
2870   verifyFormat("#\n;\n;\n;");
2871 }
2872 
2873 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
2874   EXPECT_EQ("#line 42 \"test\"\n",
2875             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
2876   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
2877                                     getLLVMStyleWithColumns(12)));
2878 }
2879 
2880 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
2881   EXPECT_EQ("#line 42 \"test\"",
2882             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
2883   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
2884 }
2885 
2886 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
2887   verifyFormat("#define A \\x20");
2888   verifyFormat("#define A \\ x20");
2889   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
2890   verifyFormat("#define A ''");
2891   verifyFormat("#define A ''qqq");
2892   verifyFormat("#define A `qqq");
2893   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
2894   EXPECT_EQ("const char *c = STRINGIFY(\n"
2895             "\\na : b);",
2896             format("const char * c = STRINGIFY(\n"
2897                    "\\na : b);"));
2898 
2899   verifyFormat("a\r\\");
2900   verifyFormat("a\v\\");
2901   verifyFormat("a\f\\");
2902 }
2903 
2904 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
2905   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
2906   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
2907   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
2908   // FIXME: We never break before the macro name.
2909   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
2910 
2911   verifyFormat("#define A A\n#define A A");
2912   verifyFormat("#define A(X) A\n#define A A");
2913 
2914   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
2915   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
2916 }
2917 
2918 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
2919   EXPECT_EQ("// somecomment\n"
2920             "#include \"a.h\"\n"
2921             "#define A(  \\\n"
2922             "    A, B)\n"
2923             "#include \"b.h\"\n"
2924             "// somecomment\n",
2925             format("  // somecomment\n"
2926                    "  #include \"a.h\"\n"
2927                    "#define A(A,\\\n"
2928                    "    B)\n"
2929                    "    #include \"b.h\"\n"
2930                    " // somecomment\n",
2931                    getLLVMStyleWithColumns(13)));
2932 }
2933 
2934 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
2935 
2936 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
2937   EXPECT_EQ("#define A    \\\n"
2938             "  c;         \\\n"
2939             "  e;\n"
2940             "f;",
2941             format("#define A c; e;\n"
2942                    "f;",
2943                    getLLVMStyleWithColumns(14)));
2944 }
2945 
2946 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
2947 
2948 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
2949   EXPECT_EQ("int x,\n"
2950             "#define A\n"
2951             "    y;",
2952             format("int x,\n#define A\ny;"));
2953 }
2954 
2955 TEST_F(FormatTest, HashInMacroDefinition) {
2956   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
2957   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
2958   verifyFormat("#define A  \\\n"
2959                "  {        \\\n"
2960                "    f(#c); \\\n"
2961                "  }",
2962                getLLVMStyleWithColumns(11));
2963 
2964   verifyFormat("#define A(X)         \\\n"
2965                "  void function##X()",
2966                getLLVMStyleWithColumns(22));
2967 
2968   verifyFormat("#define A(a, b, c)   \\\n"
2969                "  void a##b##c()",
2970                getLLVMStyleWithColumns(22));
2971 
2972   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
2973 }
2974 
2975 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
2976   EXPECT_EQ("#define A (x)", format("#define A (x)"));
2977   EXPECT_EQ("#define A(x)", format("#define A(x)"));
2978 
2979   FormatStyle Style = getLLVMStyle();
2980   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
2981   verifyFormat("#define true ((foo)1)", Style);
2982   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
2983   verifyFormat("#define false((foo)0)", Style);
2984 }
2985 
2986 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
2987   EXPECT_EQ("#define A b;", format("#define A \\\n"
2988                                    "          \\\n"
2989                                    "  b;",
2990                                    getLLVMStyleWithColumns(25)));
2991   EXPECT_EQ("#define A \\\n"
2992             "          \\\n"
2993             "  a;      \\\n"
2994             "  b;",
2995             format("#define A \\\n"
2996                    "          \\\n"
2997                    "  a;      \\\n"
2998                    "  b;",
2999                    getLLVMStyleWithColumns(11)));
3000   EXPECT_EQ("#define A \\\n"
3001             "  a;      \\\n"
3002             "          \\\n"
3003             "  b;",
3004             format("#define A \\\n"
3005                    "  a;      \\\n"
3006                    "          \\\n"
3007                    "  b;",
3008                    getLLVMStyleWithColumns(11)));
3009 }
3010 
3011 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
3012   verifyIncompleteFormat("#define A :");
3013   verifyFormat("#define SOMECASES  \\\n"
3014                "  case 1:          \\\n"
3015                "  case 2\n",
3016                getLLVMStyleWithColumns(20));
3017   verifyFormat("#define MACRO(a) \\\n"
3018                "  if (a)         \\\n"
3019                "    f();         \\\n"
3020                "  else           \\\n"
3021                "    g()",
3022                getLLVMStyleWithColumns(18));
3023   verifyFormat("#define A template <typename T>");
3024   verifyIncompleteFormat("#define STR(x) #x\n"
3025                          "f(STR(this_is_a_string_literal{));");
3026   verifyFormat("#pragma omp threadprivate( \\\n"
3027                "    y)), // expected-warning",
3028                getLLVMStyleWithColumns(28));
3029   verifyFormat("#d, = };");
3030   verifyFormat("#if \"a");
3031   verifyIncompleteFormat("({\n"
3032                          "#define b     \\\n"
3033                          "  }           \\\n"
3034                          "  a\n"
3035                          "a",
3036                          getLLVMStyleWithColumns(15));
3037   verifyFormat("#define A     \\\n"
3038                "  {           \\\n"
3039                "    {\n"
3040                "#define B     \\\n"
3041                "  }           \\\n"
3042                "  }",
3043                getLLVMStyleWithColumns(15));
3044   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
3045   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
3046   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
3047   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
3048 }
3049 
3050 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
3051   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
3052   EXPECT_EQ("class A : public QObject {\n"
3053             "  Q_OBJECT\n"
3054             "\n"
3055             "  A() {}\n"
3056             "};",
3057             format("class A  :  public QObject {\n"
3058                    "     Q_OBJECT\n"
3059                    "\n"
3060                    "  A() {\n}\n"
3061                    "}  ;"));
3062   EXPECT_EQ("MACRO\n"
3063             "/*static*/ int i;",
3064             format("MACRO\n"
3065                    " /*static*/ int   i;"));
3066   EXPECT_EQ("SOME_MACRO\n"
3067             "namespace {\n"
3068             "void f();\n"
3069             "} // namespace",
3070             format("SOME_MACRO\n"
3071                    "  namespace    {\n"
3072                    "void   f(  );\n"
3073                    "} // namespace"));
3074   // Only if the identifier contains at least 5 characters.
3075   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
3076   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
3077   // Only if everything is upper case.
3078   EXPECT_EQ("class A : public QObject {\n"
3079             "  Q_Object A() {}\n"
3080             "};",
3081             format("class A  :  public QObject {\n"
3082                    "     Q_Object\n"
3083                    "  A() {\n}\n"
3084                    "}  ;"));
3085 
3086   // Only if the next line can actually start an unwrapped line.
3087   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
3088             format("SOME_WEIRD_LOG_MACRO\n"
3089                    "<< SomeThing;"));
3090 
3091   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
3092                "(n, buffers))\n",
3093                getChromiumStyle(FormatStyle::LK_Cpp));
3094 
3095   // See PR41483
3096   EXPECT_EQ("/**/ FOO(a)\n"
3097             "FOO(b)",
3098             format("/**/ FOO(a)\n"
3099                    "FOO(b)"));
3100 }
3101 
3102 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
3103   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
3104             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
3105             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
3106             "class X {};\n"
3107             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
3108             "int *createScopDetectionPass() { return 0; }",
3109             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
3110                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
3111                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
3112                    "  class X {};\n"
3113                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
3114                    "  int *createScopDetectionPass() { return 0; }"));
3115   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
3116   // braces, so that inner block is indented one level more.
3117   EXPECT_EQ("int q() {\n"
3118             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3119             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3120             "  IPC_END_MESSAGE_MAP()\n"
3121             "}",
3122             format("int q() {\n"
3123                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3124                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3125                    "  IPC_END_MESSAGE_MAP()\n"
3126                    "}"));
3127 
3128   // Same inside macros.
3129   EXPECT_EQ("#define LIST(L) \\\n"
3130             "  L(A)          \\\n"
3131             "  L(B)          \\\n"
3132             "  L(C)",
3133             format("#define LIST(L) \\\n"
3134                    "  L(A) \\\n"
3135                    "  L(B) \\\n"
3136                    "  L(C)",
3137                    getGoogleStyle()));
3138 
3139   // These must not be recognized as macros.
3140   EXPECT_EQ("int q() {\n"
3141             "  f(x);\n"
3142             "  f(x) {}\n"
3143             "  f(x)->g();\n"
3144             "  f(x)->*g();\n"
3145             "  f(x).g();\n"
3146             "  f(x) = x;\n"
3147             "  f(x) += x;\n"
3148             "  f(x) -= x;\n"
3149             "  f(x) *= x;\n"
3150             "  f(x) /= x;\n"
3151             "  f(x) %= x;\n"
3152             "  f(x) &= x;\n"
3153             "  f(x) |= x;\n"
3154             "  f(x) ^= x;\n"
3155             "  f(x) >>= x;\n"
3156             "  f(x) <<= x;\n"
3157             "  f(x)[y].z();\n"
3158             "  LOG(INFO) << x;\n"
3159             "  ifstream(x) >> x;\n"
3160             "}\n",
3161             format("int q() {\n"
3162                    "  f(x)\n;\n"
3163                    "  f(x)\n {}\n"
3164                    "  f(x)\n->g();\n"
3165                    "  f(x)\n->*g();\n"
3166                    "  f(x)\n.g();\n"
3167                    "  f(x)\n = x;\n"
3168                    "  f(x)\n += x;\n"
3169                    "  f(x)\n -= x;\n"
3170                    "  f(x)\n *= x;\n"
3171                    "  f(x)\n /= x;\n"
3172                    "  f(x)\n %= x;\n"
3173                    "  f(x)\n &= x;\n"
3174                    "  f(x)\n |= x;\n"
3175                    "  f(x)\n ^= x;\n"
3176                    "  f(x)\n >>= x;\n"
3177                    "  f(x)\n <<= x;\n"
3178                    "  f(x)\n[y].z();\n"
3179                    "  LOG(INFO)\n << x;\n"
3180                    "  ifstream(x)\n >> x;\n"
3181                    "}\n"));
3182   EXPECT_EQ("int q() {\n"
3183             "  F(x)\n"
3184             "  if (1) {\n"
3185             "  }\n"
3186             "  F(x)\n"
3187             "  while (1) {\n"
3188             "  }\n"
3189             "  F(x)\n"
3190             "  G(x);\n"
3191             "  F(x)\n"
3192             "  try {\n"
3193             "    Q();\n"
3194             "  } catch (...) {\n"
3195             "  }\n"
3196             "}\n",
3197             format("int q() {\n"
3198                    "F(x)\n"
3199                    "if (1) {}\n"
3200                    "F(x)\n"
3201                    "while (1) {}\n"
3202                    "F(x)\n"
3203                    "G(x);\n"
3204                    "F(x)\n"
3205                    "try { Q(); } catch (...) {}\n"
3206                    "}\n"));
3207   EXPECT_EQ("class A {\n"
3208             "  A() : t(0) {}\n"
3209             "  A(int i) noexcept() : {}\n"
3210             "  A(X x)\n" // FIXME: function-level try blocks are broken.
3211             "  try : t(0) {\n"
3212             "  } catch (...) {\n"
3213             "  }\n"
3214             "};",
3215             format("class A {\n"
3216                    "  A()\n : t(0) {}\n"
3217                    "  A(int i)\n noexcept() : {}\n"
3218                    "  A(X x)\n"
3219                    "  try : t(0) {} catch (...) {}\n"
3220                    "};"));
3221   FormatStyle Style = getLLVMStyle();
3222   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3223   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
3224   Style.BraceWrapping.AfterFunction = true;
3225   EXPECT_EQ("void f()\n"
3226             "try\n"
3227             "{\n"
3228             "}",
3229             format("void f() try {\n"
3230                    "}",
3231                    Style));
3232   EXPECT_EQ("class SomeClass {\n"
3233             "public:\n"
3234             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3235             "};",
3236             format("class SomeClass {\n"
3237                    "public:\n"
3238                    "  SomeClass()\n"
3239                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3240                    "};"));
3241   EXPECT_EQ("class SomeClass {\n"
3242             "public:\n"
3243             "  SomeClass()\n"
3244             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3245             "};",
3246             format("class SomeClass {\n"
3247                    "public:\n"
3248                    "  SomeClass()\n"
3249                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3250                    "};",
3251                    getLLVMStyleWithColumns(40)));
3252 
3253   verifyFormat("MACRO(>)");
3254 
3255   // Some macros contain an implicit semicolon.
3256   Style = getLLVMStyle();
3257   Style.StatementMacros.push_back("FOO");
3258   verifyFormat("FOO(a) int b = 0;");
3259   verifyFormat("FOO(a)\n"
3260                "int b = 0;",
3261                Style);
3262   verifyFormat("FOO(a);\n"
3263                "int b = 0;",
3264                Style);
3265   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
3266                "int b = 0;",
3267                Style);
3268   verifyFormat("FOO()\n"
3269                "int b = 0;",
3270                Style);
3271   verifyFormat("FOO\n"
3272                "int b = 0;",
3273                Style);
3274   verifyFormat("void f() {\n"
3275                "  FOO(a)\n"
3276                "  return a;\n"
3277                "}",
3278                Style);
3279   verifyFormat("FOO(a)\n"
3280                "FOO(b)",
3281                Style);
3282   verifyFormat("int a = 0;\n"
3283                "FOO(b)\n"
3284                "int c = 0;",
3285                Style);
3286   verifyFormat("int a = 0;\n"
3287                "int x = FOO(a)\n"
3288                "int b = 0;",
3289                Style);
3290   verifyFormat("void foo(int a) { FOO(a) }\n"
3291                "uint32_t bar() {}",
3292                Style);
3293 }
3294 
3295 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
3296   verifyFormat("#define A \\\n"
3297                "  f({     \\\n"
3298                "    g();  \\\n"
3299                "  });",
3300                getLLVMStyleWithColumns(11));
3301 }
3302 
3303 TEST_F(FormatTest, IndentPreprocessorDirectives) {
3304   FormatStyle Style = getLLVMStyle();
3305   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
3306   Style.ColumnLimit = 40;
3307   verifyFormat("#ifdef _WIN32\n"
3308                "#define A 0\n"
3309                "#ifdef VAR2\n"
3310                "#define B 1\n"
3311                "#include <someheader.h>\n"
3312                "#define MACRO                          \\\n"
3313                "  some_very_long_func_aaaaaaaaaa();\n"
3314                "#endif\n"
3315                "#else\n"
3316                "#define A 1\n"
3317                "#endif",
3318                Style);
3319   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
3320   verifyFormat("#ifdef _WIN32\n"
3321                "#  define A 0\n"
3322                "#  ifdef VAR2\n"
3323                "#    define B 1\n"
3324                "#    include <someheader.h>\n"
3325                "#    define MACRO                      \\\n"
3326                "      some_very_long_func_aaaaaaaaaa();\n"
3327                "#  endif\n"
3328                "#else\n"
3329                "#  define A 1\n"
3330                "#endif",
3331                Style);
3332   verifyFormat("#if A\n"
3333                "#  define MACRO                        \\\n"
3334                "    void a(int x) {                    \\\n"
3335                "      b();                             \\\n"
3336                "      c();                             \\\n"
3337                "      d();                             \\\n"
3338                "      e();                             \\\n"
3339                "      f();                             \\\n"
3340                "    }\n"
3341                "#endif",
3342                Style);
3343   // Comments before include guard.
3344   verifyFormat("// file comment\n"
3345                "// file comment\n"
3346                "#ifndef HEADER_H\n"
3347                "#define HEADER_H\n"
3348                "code();\n"
3349                "#endif",
3350                Style);
3351   // Test with include guards.
3352   verifyFormat("#ifndef HEADER_H\n"
3353                "#define HEADER_H\n"
3354                "code();\n"
3355                "#endif",
3356                Style);
3357   // Include guards must have a #define with the same variable immediately
3358   // after #ifndef.
3359   verifyFormat("#ifndef NOT_GUARD\n"
3360                "#  define FOO\n"
3361                "code();\n"
3362                "#endif",
3363                Style);
3364 
3365   // Include guards must cover the entire file.
3366   verifyFormat("code();\n"
3367                "code();\n"
3368                "#ifndef NOT_GUARD\n"
3369                "#  define NOT_GUARD\n"
3370                "code();\n"
3371                "#endif",
3372                Style);
3373   verifyFormat("#ifndef NOT_GUARD\n"
3374                "#  define NOT_GUARD\n"
3375                "code();\n"
3376                "#endif\n"
3377                "code();",
3378                Style);
3379   // Test with trailing blank lines.
3380   verifyFormat("#ifndef HEADER_H\n"
3381                "#define HEADER_H\n"
3382                "code();\n"
3383                "#endif\n",
3384                Style);
3385   // Include guards don't have #else.
3386   verifyFormat("#ifndef NOT_GUARD\n"
3387                "#  define NOT_GUARD\n"
3388                "code();\n"
3389                "#else\n"
3390                "#endif",
3391                Style);
3392   verifyFormat("#ifndef NOT_GUARD\n"
3393                "#  define NOT_GUARD\n"
3394                "code();\n"
3395                "#elif FOO\n"
3396                "#endif",
3397                Style);
3398   // Non-identifier #define after potential include guard.
3399   verifyFormat("#ifndef FOO\n"
3400                "#  define 1\n"
3401                "#endif\n",
3402                Style);
3403   // #if closes past last non-preprocessor line.
3404   verifyFormat("#ifndef FOO\n"
3405                "#define FOO\n"
3406                "#if 1\n"
3407                "int i;\n"
3408                "#  define A 0\n"
3409                "#endif\n"
3410                "#endif\n",
3411                Style);
3412   // Don't crash if there is an #elif directive without a condition.
3413   verifyFormat("#if 1\n"
3414                "int x;\n"
3415                "#elif\n"
3416                "int y;\n"
3417                "#else\n"
3418                "int z;\n"
3419                "#endif",
3420                Style);
3421   // FIXME: This doesn't handle the case where there's code between the
3422   // #ifndef and #define but all other conditions hold. This is because when
3423   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
3424   // previous code line yet, so we can't detect it.
3425   EXPECT_EQ("#ifndef NOT_GUARD\n"
3426             "code();\n"
3427             "#define NOT_GUARD\n"
3428             "code();\n"
3429             "#endif",
3430             format("#ifndef NOT_GUARD\n"
3431                    "code();\n"
3432                    "#  define NOT_GUARD\n"
3433                    "code();\n"
3434                    "#endif",
3435                    Style));
3436   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
3437   // be outside an include guard. Examples are #pragma once and
3438   // #pragma GCC diagnostic, or anything else that does not change the meaning
3439   // of the file if it's included multiple times.
3440   EXPECT_EQ("#ifdef WIN32\n"
3441             "#  pragma once\n"
3442             "#endif\n"
3443             "#ifndef HEADER_H\n"
3444             "#  define HEADER_H\n"
3445             "code();\n"
3446             "#endif",
3447             format("#ifdef WIN32\n"
3448                    "#  pragma once\n"
3449                    "#endif\n"
3450                    "#ifndef HEADER_H\n"
3451                    "#define HEADER_H\n"
3452                    "code();\n"
3453                    "#endif",
3454                    Style));
3455   // FIXME: This does not detect when there is a single non-preprocessor line
3456   // in front of an include-guard-like structure where other conditions hold
3457   // because ScopedLineState hides the line.
3458   EXPECT_EQ("code();\n"
3459             "#ifndef HEADER_H\n"
3460             "#define HEADER_H\n"
3461             "code();\n"
3462             "#endif",
3463             format("code();\n"
3464                    "#ifndef HEADER_H\n"
3465                    "#  define HEADER_H\n"
3466                    "code();\n"
3467                    "#endif",
3468                    Style));
3469   // Keep comments aligned with #, otherwise indent comments normally. These
3470   // tests cannot use verifyFormat because messUp manipulates leading
3471   // whitespace.
3472   {
3473     const char *Expected = ""
3474                            "void f() {\n"
3475                            "#if 1\n"
3476                            "// Preprocessor aligned.\n"
3477                            "#  define A 0\n"
3478                            "  // Code. Separated by blank line.\n"
3479                            "\n"
3480                            "#  define B 0\n"
3481                            "  // Code. Not aligned with #\n"
3482                            "#  define C 0\n"
3483                            "#endif";
3484     const char *ToFormat = ""
3485                            "void f() {\n"
3486                            "#if 1\n"
3487                            "// Preprocessor aligned.\n"
3488                            "#  define A 0\n"
3489                            "// Code. Separated by blank line.\n"
3490                            "\n"
3491                            "#  define B 0\n"
3492                            "   // Code. Not aligned with #\n"
3493                            "#  define C 0\n"
3494                            "#endif";
3495     EXPECT_EQ(Expected, format(ToFormat, Style));
3496     EXPECT_EQ(Expected, format(Expected, Style));
3497   }
3498   // Keep block quotes aligned.
3499   {
3500     const char *Expected = ""
3501                            "void f() {\n"
3502                            "#if 1\n"
3503                            "/* Preprocessor aligned. */\n"
3504                            "#  define A 0\n"
3505                            "  /* Code. Separated by blank line. */\n"
3506                            "\n"
3507                            "#  define B 0\n"
3508                            "  /* Code. Not aligned with # */\n"
3509                            "#  define C 0\n"
3510                            "#endif";
3511     const char *ToFormat = ""
3512                            "void f() {\n"
3513                            "#if 1\n"
3514                            "/* Preprocessor aligned. */\n"
3515                            "#  define A 0\n"
3516                            "/* Code. Separated by blank line. */\n"
3517                            "\n"
3518                            "#  define B 0\n"
3519                            "   /* Code. Not aligned with # */\n"
3520                            "#  define C 0\n"
3521                            "#endif";
3522     EXPECT_EQ(Expected, format(ToFormat, Style));
3523     EXPECT_EQ(Expected, format(Expected, Style));
3524   }
3525   // Keep comments aligned with un-indented directives.
3526   {
3527     const char *Expected = ""
3528                            "void f() {\n"
3529                            "// Preprocessor aligned.\n"
3530                            "#define A 0\n"
3531                            "  // Code. Separated by blank line.\n"
3532                            "\n"
3533                            "#define B 0\n"
3534                            "  // Code. Not aligned with #\n"
3535                            "#define C 0\n";
3536     const char *ToFormat = ""
3537                            "void f() {\n"
3538                            "// Preprocessor aligned.\n"
3539                            "#define A 0\n"
3540                            "// Code. Separated by blank line.\n"
3541                            "\n"
3542                            "#define B 0\n"
3543                            "   // Code. Not aligned with #\n"
3544                            "#define C 0\n";
3545     EXPECT_EQ(Expected, format(ToFormat, Style));
3546     EXPECT_EQ(Expected, format(Expected, Style));
3547   }
3548   // Test AfterHash with tabs.
3549   {
3550     FormatStyle Tabbed = Style;
3551     Tabbed.UseTab = FormatStyle::UT_Always;
3552     Tabbed.IndentWidth = 8;
3553     Tabbed.TabWidth = 8;
3554     verifyFormat("#ifdef _WIN32\n"
3555                  "#\tdefine A 0\n"
3556                  "#\tifdef VAR2\n"
3557                  "#\t\tdefine B 1\n"
3558                  "#\t\tinclude <someheader.h>\n"
3559                  "#\t\tdefine MACRO          \\\n"
3560                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
3561                  "#\tendif\n"
3562                  "#else\n"
3563                  "#\tdefine A 1\n"
3564                  "#endif",
3565                  Tabbed);
3566   }
3567 
3568   // Regression test: Multiline-macro inside include guards.
3569   verifyFormat("#ifndef HEADER_H\n"
3570                "#define HEADER_H\n"
3571                "#define A()        \\\n"
3572                "  int i;           \\\n"
3573                "  int j;\n"
3574                "#endif // HEADER_H",
3575                getLLVMStyleWithColumns(20));
3576 
3577   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
3578   // Basic before hash indent tests
3579   verifyFormat("#ifdef _WIN32\n"
3580                "  #define A 0\n"
3581                "  #ifdef VAR2\n"
3582                "    #define B 1\n"
3583                "    #include <someheader.h>\n"
3584                "    #define MACRO                      \\\n"
3585                "      some_very_long_func_aaaaaaaaaa();\n"
3586                "  #endif\n"
3587                "#else\n"
3588                "  #define A 1\n"
3589                "#endif",
3590                Style);
3591   verifyFormat("#if A\n"
3592                "  #define MACRO                        \\\n"
3593                "    void a(int x) {                    \\\n"
3594                "      b();                             \\\n"
3595                "      c();                             \\\n"
3596                "      d();                             \\\n"
3597                "      e();                             \\\n"
3598                "      f();                             \\\n"
3599                "    }\n"
3600                "#endif",
3601                Style);
3602   // Keep comments aligned with indented directives. These
3603   // tests cannot use verifyFormat because messUp manipulates leading
3604   // whitespace.
3605   {
3606     const char *Expected = "void f() {\n"
3607                            "// Aligned to preprocessor.\n"
3608                            "#if 1\n"
3609                            "  // Aligned to code.\n"
3610                            "  int a;\n"
3611                            "  #if 1\n"
3612                            "    // Aligned to preprocessor.\n"
3613                            "    #define A 0\n"
3614                            "  // Aligned to code.\n"
3615                            "  int b;\n"
3616                            "  #endif\n"
3617                            "#endif\n"
3618                            "}";
3619     const char *ToFormat = "void f() {\n"
3620                            "// Aligned to preprocessor.\n"
3621                            "#if 1\n"
3622                            "// Aligned to code.\n"
3623                            "int a;\n"
3624                            "#if 1\n"
3625                            "// Aligned to preprocessor.\n"
3626                            "#define A 0\n"
3627                            "// Aligned to code.\n"
3628                            "int b;\n"
3629                            "#endif\n"
3630                            "#endif\n"
3631                            "}";
3632     EXPECT_EQ(Expected, format(ToFormat, Style));
3633     EXPECT_EQ(Expected, format(Expected, Style));
3634   }
3635   {
3636     const char *Expected = "void f() {\n"
3637                            "/* Aligned to preprocessor. */\n"
3638                            "#if 1\n"
3639                            "  /* Aligned to code. */\n"
3640                            "  int a;\n"
3641                            "  #if 1\n"
3642                            "    /* Aligned to preprocessor. */\n"
3643                            "    #define A 0\n"
3644                            "  /* Aligned to code. */\n"
3645                            "  int b;\n"
3646                            "  #endif\n"
3647                            "#endif\n"
3648                            "}";
3649     const char *ToFormat = "void f() {\n"
3650                            "/* Aligned to preprocessor. */\n"
3651                            "#if 1\n"
3652                            "/* Aligned to code. */\n"
3653                            "int a;\n"
3654                            "#if 1\n"
3655                            "/* Aligned to preprocessor. */\n"
3656                            "#define A 0\n"
3657                            "/* Aligned to code. */\n"
3658                            "int b;\n"
3659                            "#endif\n"
3660                            "#endif\n"
3661                            "}";
3662     EXPECT_EQ(Expected, format(ToFormat, Style));
3663     EXPECT_EQ(Expected, format(Expected, Style));
3664   }
3665 
3666   // Test single comment before preprocessor
3667   verifyFormat("// Comment\n"
3668                "\n"
3669                "#if 1\n"
3670                "#endif",
3671                Style);
3672 }
3673 
3674 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
3675   verifyFormat("{\n  { a #c; }\n}");
3676 }
3677 
3678 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
3679   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
3680             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
3681   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
3682             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
3683 }
3684 
3685 TEST_F(FormatTest, EscapedNewlines) {
3686   FormatStyle Narrow = getLLVMStyleWithColumns(11);
3687   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
3688             format("#define A \\\nint i;\\\n  int j;", Narrow));
3689   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
3690   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3691   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
3692   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
3693 
3694   FormatStyle AlignLeft = getLLVMStyle();
3695   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
3696   EXPECT_EQ("#define MACRO(x) \\\n"
3697             "private:         \\\n"
3698             "  int x(int a);\n",
3699             format("#define MACRO(x) \\\n"
3700                    "private:         \\\n"
3701                    "  int x(int a);\n",
3702                    AlignLeft));
3703 
3704   // CRLF line endings
3705   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
3706             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
3707   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
3708   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3709   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
3710   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
3711   EXPECT_EQ("#define MACRO(x) \\\r\n"
3712             "private:         \\\r\n"
3713             "  int x(int a);\r\n",
3714             format("#define MACRO(x) \\\r\n"
3715                    "private:         \\\r\n"
3716                    "  int x(int a);\r\n",
3717                    AlignLeft));
3718 
3719   FormatStyle DontAlign = getLLVMStyle();
3720   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
3721   DontAlign.MaxEmptyLinesToKeep = 3;
3722   // FIXME: can't use verifyFormat here because the newline before
3723   // "public:" is not inserted the first time it's reformatted
3724   EXPECT_EQ("#define A \\\n"
3725             "  class Foo { \\\n"
3726             "    void bar(); \\\n"
3727             "\\\n"
3728             "\\\n"
3729             "\\\n"
3730             "  public: \\\n"
3731             "    void baz(); \\\n"
3732             "  };",
3733             format("#define A \\\n"
3734                    "  class Foo { \\\n"
3735                    "    void bar(); \\\n"
3736                    "\\\n"
3737                    "\\\n"
3738                    "\\\n"
3739                    "  public: \\\n"
3740                    "    void baz(); \\\n"
3741                    "  };",
3742                    DontAlign));
3743 }
3744 
3745 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
3746   verifyFormat("#define A \\\n"
3747                "  int v(  \\\n"
3748                "      a); \\\n"
3749                "  int i;",
3750                getLLVMStyleWithColumns(11));
3751 }
3752 
3753 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
3754   EXPECT_EQ(
3755       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3756       "                      \\\n"
3757       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3758       "\n"
3759       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3760       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
3761       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
3762              "\\\n"
3763              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3764              "  \n"
3765              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3766              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
3767 }
3768 
3769 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
3770   EXPECT_EQ("int\n"
3771             "#define A\n"
3772             "    a;",
3773             format("int\n#define A\na;"));
3774   verifyFormat("functionCallTo(\n"
3775                "    someOtherFunction(\n"
3776                "        withSomeParameters, whichInSequence,\n"
3777                "        areLongerThanALine(andAnotherCall,\n"
3778                "#define A B\n"
3779                "                           withMoreParamters,\n"
3780                "                           whichStronglyInfluenceTheLayout),\n"
3781                "        andMoreParameters),\n"
3782                "    trailing);",
3783                getLLVMStyleWithColumns(69));
3784   verifyFormat("Foo::Foo()\n"
3785                "#ifdef BAR\n"
3786                "    : baz(0)\n"
3787                "#endif\n"
3788                "{\n"
3789                "}");
3790   verifyFormat("void f() {\n"
3791                "  if (true)\n"
3792                "#ifdef A\n"
3793                "    f(42);\n"
3794                "  x();\n"
3795                "#else\n"
3796                "    g();\n"
3797                "  x();\n"
3798                "#endif\n"
3799                "}");
3800   verifyFormat("void f(param1, param2,\n"
3801                "       param3,\n"
3802                "#ifdef A\n"
3803                "       param4(param5,\n"
3804                "#ifdef A1\n"
3805                "              param6,\n"
3806                "#ifdef A2\n"
3807                "              param7),\n"
3808                "#else\n"
3809                "              param8),\n"
3810                "       param9,\n"
3811                "#endif\n"
3812                "       param10,\n"
3813                "#endif\n"
3814                "       param11)\n"
3815                "#else\n"
3816                "       param12)\n"
3817                "#endif\n"
3818                "{\n"
3819                "  x();\n"
3820                "}",
3821                getLLVMStyleWithColumns(28));
3822   verifyFormat("#if 1\n"
3823                "int i;");
3824   verifyFormat("#if 1\n"
3825                "#endif\n"
3826                "#if 1\n"
3827                "#else\n"
3828                "#endif\n");
3829   verifyFormat("DEBUG({\n"
3830                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
3831                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
3832                "});\n"
3833                "#if a\n"
3834                "#else\n"
3835                "#endif");
3836 
3837   verifyIncompleteFormat("void f(\n"
3838                          "#if A\n"
3839                          ");\n"
3840                          "#else\n"
3841                          "#endif");
3842 }
3843 
3844 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
3845   verifyFormat("#endif\n"
3846                "#if B");
3847 }
3848 
3849 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
3850   FormatStyle SingleLine = getLLVMStyle();
3851   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
3852   verifyFormat("#if 0\n"
3853                "#elif 1\n"
3854                "#endif\n"
3855                "void foo() {\n"
3856                "  if (test) foo2();\n"
3857                "}",
3858                SingleLine);
3859 }
3860 
3861 TEST_F(FormatTest, LayoutBlockInsideParens) {
3862   verifyFormat("functionCall({ int i; });");
3863   verifyFormat("functionCall({\n"
3864                "  int i;\n"
3865                "  int j;\n"
3866                "});");
3867   verifyFormat("functionCall(\n"
3868                "    {\n"
3869                "      int i;\n"
3870                "      int j;\n"
3871                "    },\n"
3872                "    aaaa, bbbb, cccc);");
3873   verifyFormat("functionA(functionB({\n"
3874                "            int i;\n"
3875                "            int j;\n"
3876                "          }),\n"
3877                "          aaaa, bbbb, cccc);");
3878   verifyFormat("functionCall(\n"
3879                "    {\n"
3880                "      int i;\n"
3881                "      int j;\n"
3882                "    },\n"
3883                "    aaaa, bbbb, // comment\n"
3884                "    cccc);");
3885   verifyFormat("functionA(functionB({\n"
3886                "            int i;\n"
3887                "            int j;\n"
3888                "          }),\n"
3889                "          aaaa, bbbb, // comment\n"
3890                "          cccc);");
3891   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
3892   verifyFormat("functionCall(aaaa, bbbb, {\n"
3893                "  int i;\n"
3894                "  int j;\n"
3895                "});");
3896   verifyFormat(
3897       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
3898       "    {\n"
3899       "      int i; // break\n"
3900       "    },\n"
3901       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
3902       "                                     ccccccccccccccccc));");
3903   verifyFormat("DEBUG({\n"
3904                "  if (a)\n"
3905                "    f();\n"
3906                "});");
3907 }
3908 
3909 TEST_F(FormatTest, LayoutBlockInsideStatement) {
3910   EXPECT_EQ("SOME_MACRO { int i; }\n"
3911             "int i;",
3912             format("  SOME_MACRO  {int i;}  int i;"));
3913 }
3914 
3915 TEST_F(FormatTest, LayoutNestedBlocks) {
3916   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
3917                "  struct s {\n"
3918                "    int i;\n"
3919                "  };\n"
3920                "  s kBitsToOs[] = {{10}};\n"
3921                "  for (int i = 0; i < 10; ++i)\n"
3922                "    return;\n"
3923                "}");
3924   verifyFormat("call(parameter, {\n"
3925                "  something();\n"
3926                "  // Comment using all columns.\n"
3927                "  somethingelse();\n"
3928                "});",
3929                getLLVMStyleWithColumns(40));
3930   verifyFormat("DEBUG( //\n"
3931                "    { f(); }, a);");
3932   verifyFormat("DEBUG( //\n"
3933                "    {\n"
3934                "      f(); //\n"
3935                "    },\n"
3936                "    a);");
3937 
3938   EXPECT_EQ("call(parameter, {\n"
3939             "  something();\n"
3940             "  // Comment too\n"
3941             "  // looooooooooong.\n"
3942             "  somethingElse();\n"
3943             "});",
3944             format("call(parameter, {\n"
3945                    "  something();\n"
3946                    "  // Comment too looooooooooong.\n"
3947                    "  somethingElse();\n"
3948                    "});",
3949                    getLLVMStyleWithColumns(29)));
3950   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
3951   EXPECT_EQ("DEBUG({ // comment\n"
3952             "  int i;\n"
3953             "});",
3954             format("DEBUG({ // comment\n"
3955                    "int  i;\n"
3956                    "});"));
3957   EXPECT_EQ("DEBUG({\n"
3958             "  int i;\n"
3959             "\n"
3960             "  // comment\n"
3961             "  int j;\n"
3962             "});",
3963             format("DEBUG({\n"
3964                    "  int  i;\n"
3965                    "\n"
3966                    "  // comment\n"
3967                    "  int  j;\n"
3968                    "});"));
3969 
3970   verifyFormat("DEBUG({\n"
3971                "  if (a)\n"
3972                "    return;\n"
3973                "});");
3974   verifyGoogleFormat("DEBUG({\n"
3975                      "  if (a) return;\n"
3976                      "});");
3977   FormatStyle Style = getGoogleStyle();
3978   Style.ColumnLimit = 45;
3979   verifyFormat("Debug(\n"
3980                "    aaaaa,\n"
3981                "    {\n"
3982                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
3983                "    },\n"
3984                "    a);",
3985                Style);
3986 
3987   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
3988 
3989   verifyNoCrash("^{v^{a}}");
3990 }
3991 
3992 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
3993   EXPECT_EQ("#define MACRO()                     \\\n"
3994             "  Debug(aaa, /* force line break */ \\\n"
3995             "        {                           \\\n"
3996             "          int i;                    \\\n"
3997             "          int j;                    \\\n"
3998             "        })",
3999             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
4000                    "          {  int   i;  int  j;   })",
4001                    getGoogleStyle()));
4002 
4003   EXPECT_EQ("#define A                                       \\\n"
4004             "  [] {                                          \\\n"
4005             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
4006             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
4007             "  }",
4008             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
4009                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
4010                    getGoogleStyle()));
4011 }
4012 
4013 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
4014   EXPECT_EQ("{}", format("{}"));
4015   verifyFormat("enum E {};");
4016   verifyFormat("enum E {}");
4017   FormatStyle Style = getLLVMStyle();
4018   Style.SpaceInEmptyBlock = true;
4019   EXPECT_EQ("void f() { }", format("void f() {}", Style));
4020   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
4021   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
4022 }
4023 
4024 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
4025   FormatStyle Style = getLLVMStyle();
4026   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
4027   Style.MacroBlockEnd = "^[A-Z_]+_END$";
4028   verifyFormat("FOO_BEGIN\n"
4029                "  FOO_ENTRY\n"
4030                "FOO_END",
4031                Style);
4032   verifyFormat("FOO_BEGIN\n"
4033                "  NESTED_FOO_BEGIN\n"
4034                "    NESTED_FOO_ENTRY\n"
4035                "  NESTED_FOO_END\n"
4036                "FOO_END",
4037                Style);
4038   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
4039                "  int x;\n"
4040                "  x = 1;\n"
4041                "FOO_END(Baz)",
4042                Style);
4043 }
4044 
4045 //===----------------------------------------------------------------------===//
4046 // Line break tests.
4047 //===----------------------------------------------------------------------===//
4048 
4049 TEST_F(FormatTest, PreventConfusingIndents) {
4050   verifyFormat(
4051       "void f() {\n"
4052       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
4053       "                         parameter, parameter, parameter)),\n"
4054       "                     SecondLongCall(parameter));\n"
4055       "}");
4056   verifyFormat(
4057       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4058       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4059       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4060       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
4061   verifyFormat(
4062       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4063       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
4064       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
4065       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
4066   verifyFormat(
4067       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
4068       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
4069       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
4070       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
4071   verifyFormat("int a = bbbb && ccc &&\n"
4072                "        fffff(\n"
4073                "#define A Just forcing a new line\n"
4074                "            ddd);");
4075 }
4076 
4077 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
4078   verifyFormat(
4079       "bool aaaaaaa =\n"
4080       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
4081       "    bbbbbbbb();");
4082   verifyFormat(
4083       "bool aaaaaaa =\n"
4084       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
4085       "    bbbbbbbb();");
4086 
4087   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
4088                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
4089                "    ccccccccc == ddddddddddd;");
4090   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
4091                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
4092                "    ccccccccc == ddddddddddd;");
4093   verifyFormat(
4094       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
4095       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
4096       "    ccccccccc == ddddddddddd;");
4097 
4098   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
4099                "                 aaaaaa) &&\n"
4100                "         bbbbbb && cccccc;");
4101   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
4102                "                 aaaaaa) >>\n"
4103                "         bbbbbb;");
4104   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
4105                "    SourceMgr.getSpellingColumnNumber(\n"
4106                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
4107                "    1);");
4108 
4109   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4110                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
4111                "    cccccc) {\n}");
4112   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4113                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
4114                "              cccccc) {\n}");
4115   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4116                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
4117                "              cccccc) {\n}");
4118   verifyFormat("b = a &&\n"
4119                "    // Comment\n"
4120                "    b.c && d;");
4121 
4122   // If the LHS of a comparison is not a binary expression itself, the
4123   // additional linebreak confuses many people.
4124   verifyFormat(
4125       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4126       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
4127       "}");
4128   verifyFormat(
4129       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4130       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4131       "}");
4132   verifyFormat(
4133       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
4134       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4135       "}");
4136   verifyFormat(
4137       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4138       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
4139       "}");
4140   // Even explicit parentheses stress the precedence enough to make the
4141   // additional break unnecessary.
4142   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4143                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4144                "}");
4145   // This cases is borderline, but with the indentation it is still readable.
4146   verifyFormat(
4147       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4148       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4149       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
4150       "}",
4151       getLLVMStyleWithColumns(75));
4152 
4153   // If the LHS is a binary expression, we should still use the additional break
4154   // as otherwise the formatting hides the operator precedence.
4155   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4156                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4157                "    5) {\n"
4158                "}");
4159   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4160                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
4161                "    5) {\n"
4162                "}");
4163 
4164   FormatStyle OnePerLine = getLLVMStyle();
4165   OnePerLine.BinPackParameters = false;
4166   verifyFormat(
4167       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4168       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4169       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
4170       OnePerLine);
4171 
4172   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
4173                "                .aaa(aaaaaaaaaaaaa) *\n"
4174                "            aaaaaaa +\n"
4175                "        aaaaaaa;",
4176                getLLVMStyleWithColumns(40));
4177 }
4178 
4179 TEST_F(FormatTest, ExpressionIndentation) {
4180   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4181                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4182                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4183                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4184                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
4185                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
4186                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4187                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
4188                "                 ccccccccccccccccccccccccccccccccccccccccc;");
4189   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4190                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4191                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4192                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4193   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4194                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4195                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4196                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4197   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4198                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4199                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4200                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4201   verifyFormat("if () {\n"
4202                "} else if (aaaaa && bbbbb > // break\n"
4203                "                        ccccc) {\n"
4204                "}");
4205   verifyFormat("if () {\n"
4206                "} else if constexpr (aaaaa && bbbbb > // break\n"
4207                "                                  ccccc) {\n"
4208                "}");
4209   verifyFormat("if () {\n"
4210                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
4211                "                                  ccccc) {\n"
4212                "}");
4213   verifyFormat("if () {\n"
4214                "} else if (aaaaa &&\n"
4215                "           bbbbb > // break\n"
4216                "               ccccc &&\n"
4217                "           ddddd) {\n"
4218                "}");
4219 
4220   // Presence of a trailing comment used to change indentation of b.
4221   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
4222                "       b;\n"
4223                "return aaaaaaaaaaaaaaaaaaa +\n"
4224                "       b; //",
4225                getLLVMStyleWithColumns(30));
4226 }
4227 
4228 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
4229   // Not sure what the best system is here. Like this, the LHS can be found
4230   // immediately above an operator (everything with the same or a higher
4231   // indent). The RHS is aligned right of the operator and so compasses
4232   // everything until something with the same indent as the operator is found.
4233   // FIXME: Is this a good system?
4234   FormatStyle Style = getLLVMStyle();
4235   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
4236   verifyFormat(
4237       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4238       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4239       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4240       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4241       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4242       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4243       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4244       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4245       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
4246       Style);
4247   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4248                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4249                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4250                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4251                Style);
4252   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4253                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4254                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4255                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4256                Style);
4257   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4258                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4259                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4260                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4261                Style);
4262   verifyFormat("if () {\n"
4263                "} else if (aaaaa\n"
4264                "           && bbbbb // break\n"
4265                "                  > ccccc) {\n"
4266                "}",
4267                Style);
4268   verifyFormat("return (a)\n"
4269                "       // comment\n"
4270                "       + b;",
4271                Style);
4272   verifyFormat(
4273       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4274       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4275       "             + cc;",
4276       Style);
4277 
4278   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4279                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4280                Style);
4281 
4282   // Forced by comments.
4283   verifyFormat(
4284       "unsigned ContentSize =\n"
4285       "    sizeof(int16_t)   // DWARF ARange version number\n"
4286       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4287       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4288       "    + sizeof(int8_t); // Segment Size (in bytes)");
4289 
4290   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
4291                "       == boost::fusion::at_c<1>(iiii).second;",
4292                Style);
4293 
4294   Style.ColumnLimit = 60;
4295   verifyFormat("zzzzzzzzzz\n"
4296                "    = bbbbbbbbbbbbbbbbb\n"
4297                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
4298                Style);
4299 
4300   Style.ColumnLimit = 80;
4301   Style.IndentWidth = 4;
4302   Style.TabWidth = 4;
4303   Style.UseTab = FormatStyle::UT_Always;
4304   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4305   Style.AlignOperands = false;
4306   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
4307             "\t&& (someOtherLongishConditionPart1\n"
4308             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
4309             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
4310                    "(someOtherLongishConditionPart1 || "
4311                    "someOtherEvenLongerNestedConditionPart2);",
4312                    Style));
4313 }
4314 
4315 TEST_F(FormatTest, EnforcedOperatorWraps) {
4316   // Here we'd like to wrap after the || operators, but a comment is forcing an
4317   // earlier wrap.
4318   verifyFormat("bool x = aaaaa //\n"
4319                "         || bbbbb\n"
4320                "         //\n"
4321                "         || cccc;");
4322 }
4323 
4324 TEST_F(FormatTest, NoOperandAlignment) {
4325   FormatStyle Style = getLLVMStyle();
4326   Style.AlignOperands = false;
4327   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
4328                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4329                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4330                Style);
4331   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4332   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4333                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4334                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4335                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4336                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4337                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4338                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4339                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4340                "        > ccccccccccccccccccccccccccccccccccccccccc;",
4341                Style);
4342 
4343   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4344                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4345                "    + cc;",
4346                Style);
4347   verifyFormat("int a = aa\n"
4348                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4349                "        * cccccccccccccccccccccccccccccccccccc;\n",
4350                Style);
4351 
4352   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4353   verifyFormat("return (a > b\n"
4354                "    // comment1\n"
4355                "    // comment2\n"
4356                "    || c);",
4357                Style);
4358 }
4359 
4360 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
4361   FormatStyle Style = getLLVMStyle();
4362   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4363   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
4364                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4365                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4366                Style);
4367 }
4368 
4369 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
4370   FormatStyle Style = getLLVMStyle();
4371   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4372   Style.BinPackArguments = false;
4373   Style.ColumnLimit = 40;
4374   verifyFormat("void test() {\n"
4375                "  someFunction(\n"
4376                "      this + argument + is + quite\n"
4377                "      + long + so + it + gets + wrapped\n"
4378                "      + but + remains + bin - packed);\n"
4379                "}",
4380                Style);
4381   verifyFormat("void test() {\n"
4382                "  someFunction(arg1,\n"
4383                "               this + argument + is\n"
4384                "                   + quite + long + so\n"
4385                "                   + it + gets + wrapped\n"
4386                "                   + but + remains + bin\n"
4387                "                   - packed,\n"
4388                "               arg3);\n"
4389                "}",
4390                Style);
4391   verifyFormat("void test() {\n"
4392                "  someFunction(\n"
4393                "      arg1,\n"
4394                "      this + argument + has\n"
4395                "          + anotherFunc(nested,\n"
4396                "                        calls + whose\n"
4397                "                            + arguments\n"
4398                "                            + are + also\n"
4399                "                            + wrapped,\n"
4400                "                        in + addition)\n"
4401                "          + to + being + bin - packed,\n"
4402                "      arg3);\n"
4403                "}",
4404                Style);
4405 
4406   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
4407   verifyFormat("void test() {\n"
4408                "  someFunction(\n"
4409                "      arg1,\n"
4410                "      this + argument + has +\n"
4411                "          anotherFunc(nested,\n"
4412                "                      calls + whose +\n"
4413                "                          arguments +\n"
4414                "                          are + also +\n"
4415                "                          wrapped,\n"
4416                "                      in + addition) +\n"
4417                "          to + being + bin - packed,\n"
4418                "      arg3);\n"
4419                "}",
4420                Style);
4421 }
4422 
4423 TEST_F(FormatTest, ConstructorInitializers) {
4424   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
4425   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
4426                getLLVMStyleWithColumns(45));
4427   verifyFormat("Constructor()\n"
4428                "    : Inttializer(FitsOnTheLine) {}",
4429                getLLVMStyleWithColumns(44));
4430   verifyFormat("Constructor()\n"
4431                "    : Inttializer(FitsOnTheLine) {}",
4432                getLLVMStyleWithColumns(43));
4433 
4434   verifyFormat("template <typename T>\n"
4435                "Constructor() : Initializer(FitsOnTheLine) {}",
4436                getLLVMStyleWithColumns(45));
4437 
4438   verifyFormat(
4439       "SomeClass::Constructor()\n"
4440       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
4441 
4442   verifyFormat(
4443       "SomeClass::Constructor()\n"
4444       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4445       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
4446   verifyFormat(
4447       "SomeClass::Constructor()\n"
4448       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4449       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
4450   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4451                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4452                "    : aaaaaaaaaa(aaaaaa) {}");
4453 
4454   verifyFormat("Constructor()\n"
4455                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4456                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4457                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4458                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
4459 
4460   verifyFormat("Constructor()\n"
4461                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4462                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4463 
4464   verifyFormat("Constructor(int Parameter = 0)\n"
4465                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
4466                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
4467   verifyFormat("Constructor()\n"
4468                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
4469                "}",
4470                getLLVMStyleWithColumns(60));
4471   verifyFormat("Constructor()\n"
4472                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4473                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
4474 
4475   // Here a line could be saved by splitting the second initializer onto two
4476   // lines, but that is not desirable.
4477   verifyFormat("Constructor()\n"
4478                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
4479                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
4480                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4481 
4482   FormatStyle OnePerLine = getLLVMStyle();
4483   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4484   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
4485   verifyFormat("SomeClass::Constructor()\n"
4486                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4487                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4488                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4489                OnePerLine);
4490   verifyFormat("SomeClass::Constructor()\n"
4491                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
4492                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4493                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4494                OnePerLine);
4495   verifyFormat("MyClass::MyClass(int var)\n"
4496                "    : some_var_(var),            // 4 space indent\n"
4497                "      some_other_var_(var + 1) { // lined up\n"
4498                "}",
4499                OnePerLine);
4500   verifyFormat("Constructor()\n"
4501                "    : aaaaa(aaaaaa),\n"
4502                "      aaaaa(aaaaaa),\n"
4503                "      aaaaa(aaaaaa),\n"
4504                "      aaaaa(aaaaaa),\n"
4505                "      aaaaa(aaaaaa) {}",
4506                OnePerLine);
4507   verifyFormat("Constructor()\n"
4508                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
4509                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
4510                OnePerLine);
4511   OnePerLine.BinPackParameters = false;
4512   verifyFormat(
4513       "Constructor()\n"
4514       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4515       "          aaaaaaaaaaa().aaa(),\n"
4516       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4517       OnePerLine);
4518   OnePerLine.ColumnLimit = 60;
4519   verifyFormat("Constructor()\n"
4520                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4521                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
4522                OnePerLine);
4523 
4524   EXPECT_EQ("Constructor()\n"
4525             "    : // Comment forcing unwanted break.\n"
4526             "      aaaa(aaaa) {}",
4527             format("Constructor() :\n"
4528                    "    // Comment forcing unwanted break.\n"
4529                    "    aaaa(aaaa) {}"));
4530 }
4531 
4532 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
4533   FormatStyle Style = getLLVMStyle();
4534   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4535   Style.ColumnLimit = 60;
4536   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4537   Style.AllowAllConstructorInitializersOnNextLine = true;
4538   Style.BinPackParameters = false;
4539 
4540   for (int i = 0; i < 4; ++i) {
4541     // Test all combinations of parameters that should not have an effect.
4542     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
4543     Style.AllowAllArgumentsOnNextLine = i & 2;
4544 
4545     Style.AllowAllConstructorInitializersOnNextLine = true;
4546     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4547     verifyFormat("Constructor()\n"
4548                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4549                  Style);
4550     verifyFormat("Constructor() : a(a), b(b) {}", Style);
4551 
4552     Style.AllowAllConstructorInitializersOnNextLine = false;
4553     verifyFormat("Constructor()\n"
4554                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4555                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4556                  Style);
4557     verifyFormat("Constructor() : a(a), b(b) {}", Style);
4558 
4559     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
4560     Style.AllowAllConstructorInitializersOnNextLine = true;
4561     verifyFormat("Constructor()\n"
4562                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4563                  Style);
4564 
4565     Style.AllowAllConstructorInitializersOnNextLine = false;
4566     verifyFormat("Constructor()\n"
4567                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4568                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4569                  Style);
4570 
4571     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4572     Style.AllowAllConstructorInitializersOnNextLine = true;
4573     verifyFormat("Constructor() :\n"
4574                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4575                  Style);
4576 
4577     Style.AllowAllConstructorInitializersOnNextLine = false;
4578     verifyFormat("Constructor() :\n"
4579                  "    aaaaaaaaaaaaaaaaaa(a),\n"
4580                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4581                  Style);
4582   }
4583 
4584   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
4585   // AllowAllConstructorInitializersOnNextLine in all
4586   // BreakConstructorInitializers modes
4587   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4588   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4589   Style.AllowAllConstructorInitializersOnNextLine = false;
4590   verifyFormat("SomeClassWithALongName::Constructor(\n"
4591                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
4592                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4593                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4594                Style);
4595 
4596   Style.AllowAllConstructorInitializersOnNextLine = true;
4597   verifyFormat("SomeClassWithALongName::Constructor(\n"
4598                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4599                "    int bbbbbbbbbbbbb,\n"
4600                "    int cccccccccccccccc)\n"
4601                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4602                Style);
4603 
4604   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4605   Style.AllowAllConstructorInitializersOnNextLine = false;
4606   verifyFormat("SomeClassWithALongName::Constructor(\n"
4607                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4608                "    int bbbbbbbbbbbbb)\n"
4609                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4610                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4611                Style);
4612 
4613   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
4614 
4615   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4616   verifyFormat("SomeClassWithALongName::Constructor(\n"
4617                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
4618                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4619                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4620                Style);
4621 
4622   Style.AllowAllConstructorInitializersOnNextLine = true;
4623   verifyFormat("SomeClassWithALongName::Constructor(\n"
4624                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4625                "    int bbbbbbbbbbbbb,\n"
4626                "    int cccccccccccccccc)\n"
4627                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4628                Style);
4629 
4630   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4631   Style.AllowAllConstructorInitializersOnNextLine = false;
4632   verifyFormat("SomeClassWithALongName::Constructor(\n"
4633                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4634                "    int bbbbbbbbbbbbb)\n"
4635                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4636                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4637                Style);
4638 
4639   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4640   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4641   verifyFormat("SomeClassWithALongName::Constructor(\n"
4642                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
4643                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
4644                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4645                Style);
4646 
4647   Style.AllowAllConstructorInitializersOnNextLine = true;
4648   verifyFormat("SomeClassWithALongName::Constructor(\n"
4649                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4650                "    int bbbbbbbbbbbbb,\n"
4651                "    int cccccccccccccccc) :\n"
4652                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4653                Style);
4654 
4655   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4656   Style.AllowAllConstructorInitializersOnNextLine = false;
4657   verifyFormat("SomeClassWithALongName::Constructor(\n"
4658                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4659                "    int bbbbbbbbbbbbb) :\n"
4660                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
4661                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4662                Style);
4663 }
4664 
4665 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
4666   FormatStyle Style = getLLVMStyle();
4667   Style.ColumnLimit = 60;
4668   Style.BinPackArguments = false;
4669   for (int i = 0; i < 4; ++i) {
4670     // Test all combinations of parameters that should not have an effect.
4671     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
4672     Style.AllowAllConstructorInitializersOnNextLine = i & 2;
4673 
4674     Style.AllowAllArgumentsOnNextLine = true;
4675     verifyFormat("void foo() {\n"
4676                  "  FunctionCallWithReallyLongName(\n"
4677                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
4678                  "}",
4679                  Style);
4680     Style.AllowAllArgumentsOnNextLine = false;
4681     verifyFormat("void foo() {\n"
4682                  "  FunctionCallWithReallyLongName(\n"
4683                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4684                  "      bbbbbbbbbbbb);\n"
4685                  "}",
4686                  Style);
4687 
4688     Style.AllowAllArgumentsOnNextLine = true;
4689     verifyFormat("void foo() {\n"
4690                  "  auto VariableWithReallyLongName = {\n"
4691                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
4692                  "}",
4693                  Style);
4694     Style.AllowAllArgumentsOnNextLine = false;
4695     verifyFormat("void foo() {\n"
4696                  "  auto VariableWithReallyLongName = {\n"
4697                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4698                  "      bbbbbbbbbbbb};\n"
4699                  "}",
4700                  Style);
4701   }
4702 
4703   // This parameter should not affect declarations.
4704   Style.BinPackParameters = false;
4705   Style.AllowAllArgumentsOnNextLine = false;
4706   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4707   verifyFormat("void FunctionCallWithReallyLongName(\n"
4708                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
4709                Style);
4710   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4711   verifyFormat("void FunctionCallWithReallyLongName(\n"
4712                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
4713                "    int bbbbbbbbbbbb);",
4714                Style);
4715 }
4716 
4717 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
4718   FormatStyle Style = getLLVMStyle();
4719   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4720 
4721   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
4722   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
4723                getStyleWithColumns(Style, 45));
4724   verifyFormat("Constructor() :\n"
4725                "    Initializer(FitsOnTheLine) {}",
4726                getStyleWithColumns(Style, 44));
4727   verifyFormat("Constructor() :\n"
4728                "    Initializer(FitsOnTheLine) {}",
4729                getStyleWithColumns(Style, 43));
4730 
4731   verifyFormat("template <typename T>\n"
4732                "Constructor() : Initializer(FitsOnTheLine) {}",
4733                getStyleWithColumns(Style, 50));
4734   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4735   verifyFormat(
4736       "SomeClass::Constructor() :\n"
4737       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
4738       Style);
4739 
4740   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
4741   verifyFormat(
4742       "SomeClass::Constructor() :\n"
4743       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
4744       Style);
4745 
4746   verifyFormat(
4747       "SomeClass::Constructor() :\n"
4748       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4749       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4750       Style);
4751   verifyFormat(
4752       "SomeClass::Constructor() :\n"
4753       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4754       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
4755       Style);
4756   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4757                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
4758                "    aaaaaaaaaa(aaaaaa) {}",
4759                Style);
4760 
4761   verifyFormat("Constructor() :\n"
4762                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4763                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4764                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4765                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
4766                Style);
4767 
4768   verifyFormat("Constructor() :\n"
4769                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4770                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4771                Style);
4772 
4773   verifyFormat("Constructor(int Parameter = 0) :\n"
4774                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
4775                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
4776                Style);
4777   verifyFormat("Constructor() :\n"
4778                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
4779                "}",
4780                getStyleWithColumns(Style, 60));
4781   verifyFormat("Constructor() :\n"
4782                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4783                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
4784                Style);
4785 
4786   // Here a line could be saved by splitting the second initializer onto two
4787   // lines, but that is not desirable.
4788   verifyFormat("Constructor() :\n"
4789                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
4790                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
4791                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4792                Style);
4793 
4794   FormatStyle OnePerLine = Style;
4795   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4796   OnePerLine.AllowAllConstructorInitializersOnNextLine = false;
4797   verifyFormat("SomeClass::Constructor() :\n"
4798                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4799                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4800                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4801                OnePerLine);
4802   verifyFormat("SomeClass::Constructor() :\n"
4803                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
4804                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4805                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4806                OnePerLine);
4807   verifyFormat("MyClass::MyClass(int var) :\n"
4808                "    some_var_(var),            // 4 space indent\n"
4809                "    some_other_var_(var + 1) { // lined up\n"
4810                "}",
4811                OnePerLine);
4812   verifyFormat("Constructor() :\n"
4813                "    aaaaa(aaaaaa),\n"
4814                "    aaaaa(aaaaaa),\n"
4815                "    aaaaa(aaaaaa),\n"
4816                "    aaaaa(aaaaaa),\n"
4817                "    aaaaa(aaaaaa) {}",
4818                OnePerLine);
4819   verifyFormat("Constructor() :\n"
4820                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
4821                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
4822                OnePerLine);
4823   OnePerLine.BinPackParameters = false;
4824   verifyFormat("Constructor() :\n"
4825                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4826                "        aaaaaaaaaaa().aaa(),\n"
4827                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4828                OnePerLine);
4829   OnePerLine.ColumnLimit = 60;
4830   verifyFormat("Constructor() :\n"
4831                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
4832                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
4833                OnePerLine);
4834 
4835   EXPECT_EQ("Constructor() :\n"
4836             "    // Comment forcing unwanted break.\n"
4837             "    aaaa(aaaa) {}",
4838             format("Constructor() :\n"
4839                    "    // Comment forcing unwanted break.\n"
4840                    "    aaaa(aaaa) {}",
4841                    Style));
4842 
4843   Style.ColumnLimit = 0;
4844   verifyFormat("SomeClass::Constructor() :\n"
4845                "    a(a) {}",
4846                Style);
4847   verifyFormat("SomeClass::Constructor() noexcept :\n"
4848                "    a(a) {}",
4849                Style);
4850   verifyFormat("SomeClass::Constructor() :\n"
4851                "    a(a), b(b), c(c) {}",
4852                Style);
4853   verifyFormat("SomeClass::Constructor() :\n"
4854                "    a(a) {\n"
4855                "  foo();\n"
4856                "  bar();\n"
4857                "}",
4858                Style);
4859 
4860   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
4861   verifyFormat("SomeClass::Constructor() :\n"
4862                "    a(a), b(b), c(c) {\n"
4863                "}",
4864                Style);
4865   verifyFormat("SomeClass::Constructor() :\n"
4866                "    a(a) {\n"
4867                "}",
4868                Style);
4869 
4870   Style.ColumnLimit = 80;
4871   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
4872   Style.ConstructorInitializerIndentWidth = 2;
4873   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
4874   verifyFormat("SomeClass::Constructor() :\n"
4875                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4876                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
4877                Style);
4878 
4879   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
4880   // well
4881   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
4882   verifyFormat(
4883       "class SomeClass\n"
4884       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4885       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
4886       Style);
4887   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
4888   verifyFormat(
4889       "class SomeClass\n"
4890       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4891       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
4892       Style);
4893   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
4894   verifyFormat(
4895       "class SomeClass :\n"
4896       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4897       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
4898       Style);
4899 }
4900 
4901 #ifndef EXPENSIVE_CHECKS
4902 // Expensive checks enables libstdc++ checking which includes validating the
4903 // state of ranges used in std::priority_queue - this blows out the
4904 // runtime/scalability of the function and makes this test unacceptably slow.
4905 TEST_F(FormatTest, MemoizationTests) {
4906   // This breaks if the memoization lookup does not take \c Indent and
4907   // \c LastSpace into account.
4908   verifyFormat(
4909       "extern CFRunLoopTimerRef\n"
4910       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
4911       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
4912       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
4913       "                     CFRunLoopTimerContext *context) {}");
4914 
4915   // Deep nesting somewhat works around our memoization.
4916   verifyFormat(
4917       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
4918       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
4919       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
4920       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
4921       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
4922       getLLVMStyleWithColumns(65));
4923   verifyFormat(
4924       "aaaaa(\n"
4925       "    aaaaa,\n"
4926       "    aaaaa(\n"
4927       "        aaaaa,\n"
4928       "        aaaaa(\n"
4929       "            aaaaa,\n"
4930       "            aaaaa(\n"
4931       "                aaaaa,\n"
4932       "                aaaaa(\n"
4933       "                    aaaaa,\n"
4934       "                    aaaaa(\n"
4935       "                        aaaaa,\n"
4936       "                        aaaaa(\n"
4937       "                            aaaaa,\n"
4938       "                            aaaaa(\n"
4939       "                                aaaaa,\n"
4940       "                                aaaaa(\n"
4941       "                                    aaaaa,\n"
4942       "                                    aaaaa(\n"
4943       "                                        aaaaa,\n"
4944       "                                        aaaaa(\n"
4945       "                                            aaaaa,\n"
4946       "                                            aaaaa(\n"
4947       "                                                aaaaa,\n"
4948       "                                                aaaaa))))))))))));",
4949       getLLVMStyleWithColumns(65));
4950   verifyFormat(
4951       "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"
4952       "                                  a),\n"
4953       "                                a),\n"
4954       "                              a),\n"
4955       "                            a),\n"
4956       "                          a),\n"
4957       "                        a),\n"
4958       "                      a),\n"
4959       "                    a),\n"
4960       "                  a),\n"
4961       "                a),\n"
4962       "              a),\n"
4963       "            a),\n"
4964       "          a),\n"
4965       "        a),\n"
4966       "      a),\n"
4967       "    a),\n"
4968       "  a)",
4969       getLLVMStyleWithColumns(65));
4970 
4971   // This test takes VERY long when memoization is broken.
4972   FormatStyle OnePerLine = getLLVMStyle();
4973   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4974   OnePerLine.BinPackParameters = false;
4975   std::string input = "Constructor()\n"
4976                       "    : aaaa(a,\n";
4977   for (unsigned i = 0, e = 80; i != e; ++i) {
4978     input += "           a,\n";
4979   }
4980   input += "           a) {}";
4981   verifyFormat(input, OnePerLine);
4982 }
4983 #endif
4984 
4985 TEST_F(FormatTest, BreaksAsHighAsPossible) {
4986   verifyFormat(
4987       "void f() {\n"
4988       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
4989       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
4990       "    f();\n"
4991       "}");
4992   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
4993                "    Intervals[i - 1].getRange().getLast()) {\n}");
4994 }
4995 
4996 TEST_F(FormatTest, BreaksFunctionDeclarations) {
4997   // Principially, we break function declarations in a certain order:
4998   // 1) break amongst arguments.
4999   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
5000                "                              Cccccccccccccc cccccccccccccc);");
5001   verifyFormat("template <class TemplateIt>\n"
5002                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
5003                "                            TemplateIt *stop) {}");
5004 
5005   // 2) break after return type.
5006   verifyFormat(
5007       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5008       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
5009       getGoogleStyle());
5010 
5011   // 3) break after (.
5012   verifyFormat(
5013       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
5014       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
5015       getGoogleStyle());
5016 
5017   // 4) break before after nested name specifiers.
5018   verifyFormat(
5019       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5020       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
5021       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
5022       getGoogleStyle());
5023 
5024   // However, there are exceptions, if a sufficient amount of lines can be
5025   // saved.
5026   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
5027   // more adjusting.
5028   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
5029                "                                  Cccccccccccccc cccccccccc,\n"
5030                "                                  Cccccccccccccc cccccccccc,\n"
5031                "                                  Cccccccccccccc cccccccccc,\n"
5032                "                                  Cccccccccccccc cccccccccc);");
5033   verifyFormat(
5034       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5035       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5036       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5037       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
5038       getGoogleStyle());
5039   verifyFormat(
5040       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
5041       "                                          Cccccccccccccc cccccccccc,\n"
5042       "                                          Cccccccccccccc cccccccccc,\n"
5043       "                                          Cccccccccccccc cccccccccc,\n"
5044       "                                          Cccccccccccccc cccccccccc,\n"
5045       "                                          Cccccccccccccc cccccccccc,\n"
5046       "                                          Cccccccccccccc cccccccccc);");
5047   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5048                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5049                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5050                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5051                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
5052 
5053   // Break after multi-line parameters.
5054   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5055                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5056                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5057                "    bbbb bbbb);");
5058   verifyFormat("void SomeLoooooooooooongFunction(\n"
5059                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
5060                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5061                "    int bbbbbbbbbbbbb);");
5062 
5063   // Treat overloaded operators like other functions.
5064   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5065                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
5066   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5067                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
5068   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5069                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
5070   verifyGoogleFormat(
5071       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
5072       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
5073   verifyGoogleFormat(
5074       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
5075       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
5076   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5077                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
5078   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
5079                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
5080   verifyGoogleFormat(
5081       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
5082       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5083       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
5084   verifyGoogleFormat("template <typename T>\n"
5085                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5086                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
5087                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
5088 
5089   FormatStyle Style = getLLVMStyle();
5090   Style.PointerAlignment = FormatStyle::PAS_Left;
5091   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5092                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
5093                Style);
5094   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
5095                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5096                Style);
5097 }
5098 
5099 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
5100   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
5101   // Prefer keeping `::` followed by `operator` together.
5102   EXPECT_EQ("const aaaa::bbbbbbb &\n"
5103             "ccccccccc::operator++() {\n"
5104             "  stuff();\n"
5105             "}",
5106             format("const aaaa::bbbbbbb\n"
5107                    "&ccccccccc::operator++() { stuff(); }",
5108                    getLLVMStyleWithColumns(40)));
5109 }
5110 
5111 TEST_F(FormatTest, TrailingReturnType) {
5112   verifyFormat("auto foo() -> int;\n");
5113   // correct trailing return type spacing
5114   verifyFormat("auto operator->() -> int;\n");
5115   verifyFormat("auto operator++(int) -> int;\n");
5116 
5117   verifyFormat("struct S {\n"
5118                "  auto bar() const -> int;\n"
5119                "};");
5120   verifyFormat("template <size_t Order, typename T>\n"
5121                "auto load_img(const std::string &filename)\n"
5122                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
5123   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
5124                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
5125   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
5126   verifyFormat("template <typename T>\n"
5127                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
5128                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
5129 
5130   // Not trailing return types.
5131   verifyFormat("void f() { auto a = b->c(); }");
5132 }
5133 
5134 TEST_F(FormatTest, DeductionGuides) {
5135   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
5136   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
5137   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
5138   verifyFormat(
5139       "template <class... T>\n"
5140       "array(T &&... t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
5141   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
5142   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
5143   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
5144   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
5145   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
5146   verifyFormat("template <class T> x() -> x<1>;");
5147   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
5148 
5149   // Ensure not deduction guides.
5150   verifyFormat("c()->f<int>();");
5151   verifyFormat("x()->foo<1>;");
5152   verifyFormat("x = p->foo<3>();");
5153   verifyFormat("x()->x<1>();");
5154   verifyFormat("x()->x<1>;");
5155 }
5156 
5157 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
5158   // Avoid breaking before trailing 'const' or other trailing annotations, if
5159   // they are not function-like.
5160   FormatStyle Style = getGoogleStyle();
5161   Style.ColumnLimit = 47;
5162   verifyFormat("void someLongFunction(\n"
5163                "    int someLoooooooooooooongParameter) const {\n}",
5164                getLLVMStyleWithColumns(47));
5165   verifyFormat("LoooooongReturnType\n"
5166                "someLoooooooongFunction() const {}",
5167                getLLVMStyleWithColumns(47));
5168   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
5169                "    const {}",
5170                Style);
5171   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5172                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
5173   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5174                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
5175   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5176                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
5177   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
5178                "                   aaaaaaaaaaa aaaaa) const override;");
5179   verifyGoogleFormat(
5180       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5181       "    const override;");
5182 
5183   // Even if the first parameter has to be wrapped.
5184   verifyFormat("void someLongFunction(\n"
5185                "    int someLongParameter) const {}",
5186                getLLVMStyleWithColumns(46));
5187   verifyFormat("void someLongFunction(\n"
5188                "    int someLongParameter) const {}",
5189                Style);
5190   verifyFormat("void someLongFunction(\n"
5191                "    int someLongParameter) override {}",
5192                Style);
5193   verifyFormat("void someLongFunction(\n"
5194                "    int someLongParameter) OVERRIDE {}",
5195                Style);
5196   verifyFormat("void someLongFunction(\n"
5197                "    int someLongParameter) final {}",
5198                Style);
5199   verifyFormat("void someLongFunction(\n"
5200                "    int someLongParameter) FINAL {}",
5201                Style);
5202   verifyFormat("void someLongFunction(\n"
5203                "    int parameter) const override {}",
5204                Style);
5205 
5206   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
5207   verifyFormat("void someLongFunction(\n"
5208                "    int someLongParameter) const\n"
5209                "{\n"
5210                "}",
5211                Style);
5212 
5213   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
5214   verifyFormat("void someLongFunction(\n"
5215                "    int someLongParameter) const\n"
5216                "  {\n"
5217                "  }",
5218                Style);
5219 
5220   // Unless these are unknown annotations.
5221   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
5222                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5223                "    LONG_AND_UGLY_ANNOTATION;");
5224 
5225   // Breaking before function-like trailing annotations is fine to keep them
5226   // close to their arguments.
5227   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5228                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5229   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5230                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5231   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5232                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
5233   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
5234                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
5235   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
5236 
5237   verifyFormat(
5238       "void aaaaaaaaaaaaaaaaaa()\n"
5239       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
5240       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
5241   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5242                "    __attribute__((unused));");
5243   verifyGoogleFormat(
5244       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5245       "    GUARDED_BY(aaaaaaaaaaaa);");
5246   verifyGoogleFormat(
5247       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5248       "    GUARDED_BY(aaaaaaaaaaaa);");
5249   verifyGoogleFormat(
5250       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
5251       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5252   verifyGoogleFormat(
5253       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
5254       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
5255 }
5256 
5257 TEST_F(FormatTest, FunctionAnnotations) {
5258   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5259                "int OldFunction(const string &parameter) {}");
5260   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5261                "string OldFunction(const string &parameter) {}");
5262   verifyFormat("template <typename T>\n"
5263                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5264                "string OldFunction(const string &parameter) {}");
5265 
5266   // Not function annotations.
5267   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5268                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
5269   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
5270                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
5271   verifyFormat("MACRO(abc).function() // wrap\n"
5272                "    << abc;");
5273   verifyFormat("MACRO(abc)->function() // wrap\n"
5274                "    << abc;");
5275   verifyFormat("MACRO(abc)::function() // wrap\n"
5276                "    << abc;");
5277 }
5278 
5279 TEST_F(FormatTest, BreaksDesireably) {
5280   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
5281                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
5282                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
5283   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5284                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
5285                "}");
5286 
5287   verifyFormat(
5288       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5289       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5290 
5291   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5292                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5293                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5294 
5295   verifyFormat(
5296       "aaaaaaaa(aaaaaaaaaaaaa,\n"
5297       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5298       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
5299       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5300       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
5301 
5302   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5303                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5304 
5305   verifyFormat(
5306       "void f() {\n"
5307       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
5308       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5309       "}");
5310   verifyFormat(
5311       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5312       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5313   verifyFormat(
5314       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5315       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5316   verifyFormat(
5317       "aaaaaa(aaa,\n"
5318       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5319       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5320       "       aaaa);");
5321   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5322                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5323                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5324 
5325   // Indent consistently independent of call expression and unary operator.
5326   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5327                "    dddddddddddddddddddddddddddddd));");
5328   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5329                "    dddddddddddddddddddddddddddddd));");
5330   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
5331                "    dddddddddddddddddddddddddddddd));");
5332 
5333   // This test case breaks on an incorrect memoization, i.e. an optimization not
5334   // taking into account the StopAt value.
5335   verifyFormat(
5336       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5337       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5338       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5339       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5340 
5341   verifyFormat("{\n  {\n    {\n"
5342                "      Annotation.SpaceRequiredBefore =\n"
5343                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
5344                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
5345                "    }\n  }\n}");
5346 
5347   // Break on an outer level if there was a break on an inner level.
5348   EXPECT_EQ("f(g(h(a, // comment\n"
5349             "      b, c),\n"
5350             "    d, e),\n"
5351             "  x, y);",
5352             format("f(g(h(a, // comment\n"
5353                    "    b, c), d, e), x, y);"));
5354 
5355   // Prefer breaking similar line breaks.
5356   verifyFormat(
5357       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
5358       "                             NSTrackingMouseEnteredAndExited |\n"
5359       "                             NSTrackingActiveAlways;");
5360 }
5361 
5362 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
5363   FormatStyle NoBinPacking = getGoogleStyle();
5364   NoBinPacking.BinPackParameters = false;
5365   NoBinPacking.BinPackArguments = true;
5366   verifyFormat("void f() {\n"
5367                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
5368                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5369                "}",
5370                NoBinPacking);
5371   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
5372                "       int aaaaaaaaaaaaaaaaaaaa,\n"
5373                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5374                NoBinPacking);
5375 
5376   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
5377   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5378                "                        vector<int> bbbbbbbbbbbbbbb);",
5379                NoBinPacking);
5380   // FIXME: This behavior difference is probably not wanted. However, currently
5381   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
5382   // template arguments from BreakBeforeParameter being set because of the
5383   // one-per-line formatting.
5384   verifyFormat(
5385       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
5386       "                                             aaaaaaaaaa> aaaaaaaaaa);",
5387       NoBinPacking);
5388   verifyFormat(
5389       "void fffffffffff(\n"
5390       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
5391       "        aaaaaaaaaa);");
5392 }
5393 
5394 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
5395   FormatStyle NoBinPacking = getGoogleStyle();
5396   NoBinPacking.BinPackParameters = false;
5397   NoBinPacking.BinPackArguments = false;
5398   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
5399                "  aaaaaaaaaaaaaaaaaaaa,\n"
5400                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
5401                NoBinPacking);
5402   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
5403                "        aaaaaaaaaaaaa,\n"
5404                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
5405                NoBinPacking);
5406   verifyFormat(
5407       "aaaaaaaa(aaaaaaaaaaaaa,\n"
5408       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5409       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
5410       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5411       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
5412       NoBinPacking);
5413   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
5414                "    .aaaaaaaaaaaaaaaaaa();",
5415                NoBinPacking);
5416   verifyFormat("void f() {\n"
5417                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5418                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
5419                "}",
5420                NoBinPacking);
5421 
5422   verifyFormat(
5423       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5424       "             aaaaaaaaaaaa,\n"
5425       "             aaaaaaaaaaaa);",
5426       NoBinPacking);
5427   verifyFormat(
5428       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
5429       "                               ddddddddddddddddddddddddddddd),\n"
5430       "             test);",
5431       NoBinPacking);
5432 
5433   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
5434                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
5435                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
5436                "    aaaaaaaaaaaaaaaaaa;",
5437                NoBinPacking);
5438   verifyFormat("a(\"a\"\n"
5439                "  \"a\",\n"
5440                "  a);");
5441 
5442   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
5443   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
5444                "                aaaaaaaaa,\n"
5445                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5446                NoBinPacking);
5447   verifyFormat(
5448       "void f() {\n"
5449       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
5450       "      .aaaaaaa();\n"
5451       "}",
5452       NoBinPacking);
5453   verifyFormat(
5454       "template <class SomeType, class SomeOtherType>\n"
5455       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
5456       NoBinPacking);
5457 }
5458 
5459 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
5460   FormatStyle Style = getLLVMStyleWithColumns(15);
5461   Style.ExperimentalAutoDetectBinPacking = true;
5462   EXPECT_EQ("aaa(aaaa,\n"
5463             "    aaaa,\n"
5464             "    aaaa);\n"
5465             "aaa(aaaa,\n"
5466             "    aaaa,\n"
5467             "    aaaa);",
5468             format("aaa(aaaa,\n" // one-per-line
5469                    "  aaaa,\n"
5470                    "    aaaa  );\n"
5471                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
5472                    Style));
5473   EXPECT_EQ("aaa(aaaa, aaaa,\n"
5474             "    aaaa);\n"
5475             "aaa(aaaa, aaaa,\n"
5476             "    aaaa);",
5477             format("aaa(aaaa,  aaaa,\n" // bin-packed
5478                    "    aaaa  );\n"
5479                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
5480                    Style));
5481 }
5482 
5483 TEST_F(FormatTest, FormatsBuilderPattern) {
5484   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
5485                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
5486                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
5487                "    .StartsWith(\".init\", ORDER_INIT)\n"
5488                "    .StartsWith(\".fini\", ORDER_FINI)\n"
5489                "    .StartsWith(\".hash\", ORDER_HASH)\n"
5490                "    .Default(ORDER_TEXT);\n");
5491 
5492   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
5493                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
5494   verifyFormat("aaaaaaa->aaaaaaa\n"
5495                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5496                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5497                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
5498   verifyFormat(
5499       "aaaaaaa->aaaaaaa\n"
5500       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5501       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
5502   verifyFormat(
5503       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
5504       "    aaaaaaaaaaaaaa);");
5505   verifyFormat(
5506       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
5507       "    aaaaaa->aaaaaaaaaaaa()\n"
5508       "        ->aaaaaaaaaaaaaaaa(\n"
5509       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5510       "        ->aaaaaaaaaaaaaaaaa();");
5511   verifyGoogleFormat(
5512       "void f() {\n"
5513       "  someo->Add((new util::filetools::Handler(dir))\n"
5514       "                 ->OnEvent1(NewPermanentCallback(\n"
5515       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
5516       "                 ->OnEvent2(NewPermanentCallback(\n"
5517       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
5518       "                 ->OnEvent3(NewPermanentCallback(\n"
5519       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
5520       "                 ->OnEvent5(NewPermanentCallback(\n"
5521       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
5522       "                 ->OnEvent6(NewPermanentCallback(\n"
5523       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
5524       "}");
5525 
5526   verifyFormat(
5527       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
5528   verifyFormat("aaaaaaaaaaaaaaa()\n"
5529                "    .aaaaaaaaaaaaaaa()\n"
5530                "    .aaaaaaaaaaaaaaa()\n"
5531                "    .aaaaaaaaaaaaaaa()\n"
5532                "    .aaaaaaaaaaaaaaa();");
5533   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5534                "    .aaaaaaaaaaaaaaa()\n"
5535                "    .aaaaaaaaaaaaaaa()\n"
5536                "    .aaaaaaaaaaaaaaa();");
5537   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5538                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5539                "    .aaaaaaaaaaaaaaa();");
5540   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
5541                "    ->aaaaaaaaaaaaaae(0)\n"
5542                "    ->aaaaaaaaaaaaaaa();");
5543 
5544   // Don't linewrap after very short segments.
5545   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5546                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5547                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5548   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5549                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5550                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5551   verifyFormat("aaa()\n"
5552                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5553                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5554                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5555 
5556   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
5557                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5558                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
5559   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
5560                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5561                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
5562 
5563   // Prefer not to break after empty parentheses.
5564   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
5565                "    First->LastNewlineOffset);");
5566 
5567   // Prefer not to create "hanging" indents.
5568   verifyFormat(
5569       "return !soooooooooooooome_map\n"
5570       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5571       "            .second;");
5572   verifyFormat(
5573       "return aaaaaaaaaaaaaaaa\n"
5574       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
5575       "    .aaaa(aaaaaaaaaaaaaa);");
5576   // No hanging indent here.
5577   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
5578                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5579   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
5580                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5581   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
5582                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5583                getLLVMStyleWithColumns(60));
5584   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
5585                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
5586                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5587                getLLVMStyleWithColumns(59));
5588   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5589                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5590                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5591 
5592   // Dont break if only closing statements before member call
5593   verifyFormat("test() {\n"
5594                "  ([]() -> {\n"
5595                "    int b = 32;\n"
5596                "    return 3;\n"
5597                "  }).foo();\n"
5598                "}");
5599   verifyFormat("test() {\n"
5600                "  (\n"
5601                "      []() -> {\n"
5602                "        int b = 32;\n"
5603                "        return 3;\n"
5604                "      },\n"
5605                "      foo, bar)\n"
5606                "      .foo();\n"
5607                "}");
5608   verifyFormat("test() {\n"
5609                "  ([]() -> {\n"
5610                "    int b = 32;\n"
5611                "    return 3;\n"
5612                "  })\n"
5613                "      .foo()\n"
5614                "      .bar();\n"
5615                "}");
5616   verifyFormat("test() {\n"
5617                "  ([]() -> {\n"
5618                "    int b = 32;\n"
5619                "    return 3;\n"
5620                "  })\n"
5621                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
5622                "           \"bbbb\");\n"
5623                "}",
5624                getLLVMStyleWithColumns(30));
5625 }
5626 
5627 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
5628   verifyFormat(
5629       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5630       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
5631   verifyFormat(
5632       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
5633       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
5634 
5635   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
5636                "    ccccccccccccccccccccccccc) {\n}");
5637   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
5638                "    ccccccccccccccccccccccccc) {\n}");
5639 
5640   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
5641                "    ccccccccccccccccccccccccc) {\n}");
5642   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
5643                "    ccccccccccccccccccccccccc) {\n}");
5644 
5645   verifyFormat(
5646       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
5647       "    ccccccccccccccccccccccccc) {\n}");
5648   verifyFormat(
5649       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
5650       "    ccccccccccccccccccccccccc) {\n}");
5651 
5652   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
5653                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
5654                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
5655                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
5656   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
5657                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
5658                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
5659                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
5660 
5661   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
5662                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
5663                "    aaaaaaaaaaaaaaa != aa) {\n}");
5664   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
5665                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
5666                "    aaaaaaaaaaaaaaa != aa) {\n}");
5667 }
5668 
5669 TEST_F(FormatTest, BreaksAfterAssignments) {
5670   verifyFormat(
5671       "unsigned Cost =\n"
5672       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
5673       "                        SI->getPointerAddressSpaceee());\n");
5674   verifyFormat(
5675       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
5676       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
5677 
5678   verifyFormat(
5679       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
5680       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
5681   verifyFormat("unsigned OriginalStartColumn =\n"
5682                "    SourceMgr.getSpellingColumnNumber(\n"
5683                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
5684                "    1;");
5685 }
5686 
5687 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
5688   FormatStyle Style = getLLVMStyle();
5689   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
5690                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
5691                Style);
5692 
5693   Style.PenaltyBreakAssignment = 20;
5694   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
5695                "                                 cccccccccccccccccccccccccc;",
5696                Style);
5697 }
5698 
5699 TEST_F(FormatTest, AlignsAfterAssignments) {
5700   verifyFormat(
5701       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5702       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
5703   verifyFormat(
5704       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5705       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
5706   verifyFormat(
5707       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5708       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
5709   verifyFormat(
5710       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5711       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
5712   verifyFormat(
5713       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
5714       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
5715       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
5716 }
5717 
5718 TEST_F(FormatTest, AlignsAfterReturn) {
5719   verifyFormat(
5720       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5721       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
5722   verifyFormat(
5723       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5724       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
5725   verifyFormat(
5726       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
5727       "       aaaaaaaaaaaaaaaaaaaaaa();");
5728   verifyFormat(
5729       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
5730       "        aaaaaaaaaaaaaaaaaaaaaa());");
5731   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5732                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5733   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5734                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
5735                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5736   verifyFormat("return\n"
5737                "    // true if code is one of a or b.\n"
5738                "    code == a || code == b;");
5739 }
5740 
5741 TEST_F(FormatTest, AlignsAfterOpenBracket) {
5742   verifyFormat(
5743       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
5744       "                                                aaaaaaaaa aaaaaaa) {}");
5745   verifyFormat(
5746       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
5747       "                                               aaaaaaaaaaa aaaaaaaaa);");
5748   verifyFormat(
5749       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
5750       "                                             aaaaaaaaaaaaaaaaaaaaa));");
5751   FormatStyle Style = getLLVMStyle();
5752   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5753   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5754                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
5755                Style);
5756   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
5757                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
5758                Style);
5759   verifyFormat("SomeLongVariableName->someFunction(\n"
5760                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
5761                Style);
5762   verifyFormat(
5763       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
5764       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5765       Style);
5766   verifyFormat(
5767       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
5768       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5769       Style);
5770   verifyFormat(
5771       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
5772       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
5773       Style);
5774 
5775   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
5776                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
5777                "        b));",
5778                Style);
5779 
5780   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
5781   Style.BinPackArguments = false;
5782   Style.BinPackParameters = false;
5783   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5784                "    aaaaaaaaaaa aaaaaaaa,\n"
5785                "    aaaaaaaaa aaaaaaa,\n"
5786                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5787                Style);
5788   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
5789                "    aaaaaaaaaaa aaaaaaaaa,\n"
5790                "    aaaaaaaaaaa aaaaaaaaa,\n"
5791                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5792                Style);
5793   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
5794                "    aaaaaaaaaaaaaaa,\n"
5795                "    aaaaaaaaaaaaaaaaaaaaa,\n"
5796                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
5797                Style);
5798   verifyFormat(
5799       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
5800       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
5801       Style);
5802   verifyFormat(
5803       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
5804       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
5805       Style);
5806   verifyFormat(
5807       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5808       "    aaaaaaaaaaaaaaaaaaaaa(\n"
5809       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
5810       "    aaaaaaaaaaaaaaaa);",
5811       Style);
5812   verifyFormat(
5813       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5814       "    aaaaaaaaaaaaaaaaaaaaa(\n"
5815       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
5816       "    aaaaaaaaaaaaaaaa);",
5817       Style);
5818 }
5819 
5820 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
5821   FormatStyle Style = getLLVMStyleWithColumns(40);
5822   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
5823                "          bbbbbbbbbbbbbbbbbbbbbb);",
5824                Style);
5825   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
5826   Style.AlignOperands = false;
5827   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
5828                "          bbbbbbbbbbbbbbbbbbbbbb);",
5829                Style);
5830   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5831   Style.AlignOperands = true;
5832   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
5833                "          bbbbbbbbbbbbbbbbbbbbbb);",
5834                Style);
5835   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5836   Style.AlignOperands = false;
5837   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
5838                "    bbbbbbbbbbbbbbbbbbbbbb);",
5839                Style);
5840 }
5841 
5842 TEST_F(FormatTest, BreaksConditionalExpressions) {
5843   verifyFormat(
5844       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5845       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5846       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5847   verifyFormat(
5848       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
5849       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5850       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5851   verifyFormat(
5852       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5853       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5854   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
5855                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5856                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5857   verifyFormat(
5858       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
5859       "                                                    : aaaaaaaaaaaaa);");
5860   verifyFormat(
5861       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5862       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5863       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5864       "                   aaaaaaaaaaaaa);");
5865   verifyFormat(
5866       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5867       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5868       "                   aaaaaaaaaaaaa);");
5869   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5870                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5871                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5872                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5873                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5874   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5875                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5876                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5877                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5878                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5879                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5880                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5881   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5882                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5883                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5884                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5885                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5886   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5887                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5888                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5889   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
5890                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5891                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5892                "        : aaaaaaaaaaaaaaaa;");
5893   verifyFormat(
5894       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5895       "    ? aaaaaaaaaaaaaaa\n"
5896       "    : aaaaaaaaaaaaaaa;");
5897   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
5898                "          aaaaaaaaa\n"
5899                "      ? b\n"
5900                "      : c);");
5901   verifyFormat("return aaaa == bbbb\n"
5902                "           // comment\n"
5903                "           ? aaaa\n"
5904                "           : bbbb;");
5905   verifyFormat("unsigned Indent =\n"
5906                "    format(TheLine.First,\n"
5907                "           IndentForLevel[TheLine.Level] >= 0\n"
5908                "               ? IndentForLevel[TheLine.Level]\n"
5909                "               : TheLine * 2,\n"
5910                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
5911                getLLVMStyleWithColumns(60));
5912   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
5913                "                  ? aaaaaaaaaaaaaaa\n"
5914                "                  : bbbbbbbbbbbbbbb //\n"
5915                "                        ? ccccccccccccccc\n"
5916                "                        : ddddddddddddddd;");
5917   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
5918                "                  ? aaaaaaaaaaaaaaa\n"
5919                "                  : (bbbbbbbbbbbbbbb //\n"
5920                "                         ? ccccccccccccccc\n"
5921                "                         : ddddddddddddddd);");
5922   verifyFormat(
5923       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5924       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5925       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
5926       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
5927       "                                      : aaaaaaaaaa;");
5928   verifyFormat(
5929       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5930       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
5931       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5932 
5933   FormatStyle NoBinPacking = getLLVMStyle();
5934   NoBinPacking.BinPackArguments = false;
5935   verifyFormat(
5936       "void f() {\n"
5937       "  g(aaa,\n"
5938       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
5939       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5940       "        ? aaaaaaaaaaaaaaa\n"
5941       "        : aaaaaaaaaaaaaaa);\n"
5942       "}",
5943       NoBinPacking);
5944   verifyFormat(
5945       "void f() {\n"
5946       "  g(aaa,\n"
5947       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
5948       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5949       "        ?: aaaaaaaaaaaaaaa);\n"
5950       "}",
5951       NoBinPacking);
5952 
5953   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
5954                "             // comment.\n"
5955                "             ccccccccccccccccccccccccccccccccccccccc\n"
5956                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5957                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
5958 
5959   // Assignments in conditional expressions. Apparently not uncommon :-(.
5960   verifyFormat("return a != b\n"
5961                "           // comment\n"
5962                "           ? a = b\n"
5963                "           : a = b;");
5964   verifyFormat("return a != b\n"
5965                "           // comment\n"
5966                "           ? a = a != b\n"
5967                "                     // comment\n"
5968                "                     ? a = b\n"
5969                "                     : a\n"
5970                "           : a;\n");
5971   verifyFormat("return a != b\n"
5972                "           // comment\n"
5973                "           ? a\n"
5974                "           : a = a != b\n"
5975                "                     // comment\n"
5976                "                     ? a = b\n"
5977                "                     : a;");
5978 }
5979 
5980 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
5981   FormatStyle Style = getLLVMStyle();
5982   Style.BreakBeforeTernaryOperators = false;
5983   Style.ColumnLimit = 70;
5984   verifyFormat(
5985       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
5986       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
5987       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5988       Style);
5989   verifyFormat(
5990       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
5991       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
5992       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5993       Style);
5994   verifyFormat(
5995       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
5996       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5997       Style);
5998   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
5999                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6000                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6001                Style);
6002   verifyFormat(
6003       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
6004       "                                                      aaaaaaaaaaaaa);",
6005       Style);
6006   verifyFormat(
6007       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6008       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6009       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6010       "                   aaaaaaaaaaaaa);",
6011       Style);
6012   verifyFormat(
6013       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6014       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6015       "                   aaaaaaaaaaaaa);",
6016       Style);
6017   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6018                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6019                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6020                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6021                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6022                Style);
6023   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6024                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6025                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6026                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6027                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6028                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6029                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6030                Style);
6031   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6032                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
6033                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6034                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6035                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6036                Style);
6037   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6038                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6039                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6040                Style);
6041   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
6042                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6043                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6044                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6045                Style);
6046   verifyFormat(
6047       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6048       "    aaaaaaaaaaaaaaa :\n"
6049       "    aaaaaaaaaaaaaaa;",
6050       Style);
6051   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
6052                "          aaaaaaaaa ?\n"
6053                "      b :\n"
6054                "      c);",
6055                Style);
6056   verifyFormat("unsigned Indent =\n"
6057                "    format(TheLine.First,\n"
6058                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
6059                "               IndentForLevel[TheLine.Level] :\n"
6060                "               TheLine * 2,\n"
6061                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
6062                Style);
6063   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6064                "                  aaaaaaaaaaaaaaa :\n"
6065                "                  bbbbbbbbbbbbbbb ? //\n"
6066                "                      ccccccccccccccc :\n"
6067                "                      ddddddddddddddd;",
6068                Style);
6069   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6070                "                  aaaaaaaaaaaaaaa :\n"
6071                "                  (bbbbbbbbbbbbbbb ? //\n"
6072                "                       ccccccccccccccc :\n"
6073                "                       ddddddddddddddd);",
6074                Style);
6075   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6076                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
6077                "            ccccccccccccccccccccccccccc;",
6078                Style);
6079   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6080                "           aaaaa :\n"
6081                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
6082                Style);
6083 }
6084 
6085 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
6086   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
6087                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
6088   verifyFormat("bool a = true, b = false;");
6089 
6090   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6091                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
6092                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
6093                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
6094   verifyFormat(
6095       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6096       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
6097       "     d = e && f;");
6098   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
6099                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
6100   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
6101                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
6102   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
6103                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
6104 
6105   FormatStyle Style = getGoogleStyle();
6106   Style.PointerAlignment = FormatStyle::PAS_Left;
6107   Style.DerivePointerAlignment = false;
6108   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6109                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
6110                "    *b = bbbbbbbbbbbbbbbbbbb;",
6111                Style);
6112   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
6113                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
6114                Style);
6115   verifyFormat("vector<int*> a, b;", Style);
6116   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
6117 }
6118 
6119 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
6120   verifyFormat("arr[foo ? bar : baz];");
6121   verifyFormat("f()[foo ? bar : baz];");
6122   verifyFormat("(a + b)[foo ? bar : baz];");
6123   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
6124 }
6125 
6126 TEST_F(FormatTest, AlignsStringLiterals) {
6127   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
6128                "                                      \"short literal\");");
6129   verifyFormat(
6130       "looooooooooooooooooooooooongFunction(\n"
6131       "    \"short literal\"\n"
6132       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
6133   verifyFormat("someFunction(\"Always break between multi-line\"\n"
6134                "             \" string literals\",\n"
6135                "             and, other, parameters);");
6136   EXPECT_EQ("fun + \"1243\" /* comment */\n"
6137             "      \"5678\";",
6138             format("fun + \"1243\" /* comment */\n"
6139                    "    \"5678\";",
6140                    getLLVMStyleWithColumns(28)));
6141   EXPECT_EQ(
6142       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
6143       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
6144       "         \"aaaaaaaaaaaaaaaa\";",
6145       format("aaaaaa ="
6146              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
6147              "aaaaaaaaaaaaaaaaaaaaa\" "
6148              "\"aaaaaaaaaaaaaaaa\";"));
6149   verifyFormat("a = a + \"a\"\n"
6150                "        \"a\"\n"
6151                "        \"a\";");
6152   verifyFormat("f(\"a\", \"b\"\n"
6153                "       \"c\");");
6154 
6155   verifyFormat(
6156       "#define LL_FORMAT \"ll\"\n"
6157       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
6158       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
6159 
6160   verifyFormat("#define A(X)          \\\n"
6161                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
6162                "  \"ccccc\"",
6163                getLLVMStyleWithColumns(23));
6164   verifyFormat("#define A \"def\"\n"
6165                "f(\"abc\" A \"ghi\"\n"
6166                "  \"jkl\");");
6167 
6168   verifyFormat("f(L\"a\"\n"
6169                "  L\"b\");");
6170   verifyFormat("#define A(X)            \\\n"
6171                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
6172                "  L\"ccccc\"",
6173                getLLVMStyleWithColumns(25));
6174 
6175   verifyFormat("f(@\"a\"\n"
6176                "  @\"b\");");
6177   verifyFormat("NSString s = @\"a\"\n"
6178                "             @\"b\"\n"
6179                "             @\"c\";");
6180   verifyFormat("NSString s = @\"a\"\n"
6181                "              \"b\"\n"
6182                "              \"c\";");
6183 }
6184 
6185 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
6186   FormatStyle Style = getLLVMStyle();
6187   // No declarations or definitions should be moved to own line.
6188   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
6189   verifyFormat("class A {\n"
6190                "  int f() { return 1; }\n"
6191                "  int g();\n"
6192                "};\n"
6193                "int f() { return 1; }\n"
6194                "int g();\n",
6195                Style);
6196 
6197   // All declarations and definitions should have the return type moved to its
6198   // own
6199   // line.
6200   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
6201   verifyFormat("class E {\n"
6202                "  int\n"
6203                "  f() {\n"
6204                "    return 1;\n"
6205                "  }\n"
6206                "  int\n"
6207                "  g();\n"
6208                "};\n"
6209                "int\n"
6210                "f() {\n"
6211                "  return 1;\n"
6212                "}\n"
6213                "int\n"
6214                "g();\n",
6215                Style);
6216 
6217   // Top-level definitions, and no kinds of declarations should have the
6218   // return type moved to its own line.
6219   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
6220   verifyFormat("class B {\n"
6221                "  int f() { return 1; }\n"
6222                "  int g();\n"
6223                "};\n"
6224                "int\n"
6225                "f() {\n"
6226                "  return 1;\n"
6227                "}\n"
6228                "int g();\n",
6229                Style);
6230 
6231   // Top-level definitions and declarations should have the return type moved
6232   // to its own line.
6233   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
6234   verifyFormat("class C {\n"
6235                "  int f() { return 1; }\n"
6236                "  int g();\n"
6237                "};\n"
6238                "int\n"
6239                "f() {\n"
6240                "  return 1;\n"
6241                "}\n"
6242                "int\n"
6243                "g();\n",
6244                Style);
6245 
6246   // All definitions should have the return type moved to its own line, but no
6247   // kinds of declarations.
6248   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
6249   verifyFormat("class D {\n"
6250                "  int\n"
6251                "  f() {\n"
6252                "    return 1;\n"
6253                "  }\n"
6254                "  int g();\n"
6255                "};\n"
6256                "int\n"
6257                "f() {\n"
6258                "  return 1;\n"
6259                "}\n"
6260                "int g();\n",
6261                Style);
6262   verifyFormat("const char *\n"
6263                "f(void) {\n" // Break here.
6264                "  return \"\";\n"
6265                "}\n"
6266                "const char *bar(void);\n", // No break here.
6267                Style);
6268   verifyFormat("template <class T>\n"
6269                "T *\n"
6270                "f(T &c) {\n" // Break here.
6271                "  return NULL;\n"
6272                "}\n"
6273                "template <class T> T *f(T &c);\n", // No break here.
6274                Style);
6275   verifyFormat("class C {\n"
6276                "  int\n"
6277                "  operator+() {\n"
6278                "    return 1;\n"
6279                "  }\n"
6280                "  int\n"
6281                "  operator()() {\n"
6282                "    return 1;\n"
6283                "  }\n"
6284                "};\n",
6285                Style);
6286   verifyFormat("void\n"
6287                "A::operator()() {}\n"
6288                "void\n"
6289                "A::operator>>() {}\n"
6290                "void\n"
6291                "A::operator+() {}\n"
6292                "void\n"
6293                "A::operator*() {}\n"
6294                "void\n"
6295                "A::operator->() {}\n"
6296                "void\n"
6297                "A::operator void *() {}\n"
6298                "void\n"
6299                "A::operator void &() {}\n"
6300                "void\n"
6301                "A::operator void &&() {}\n"
6302                "void\n"
6303                "A::operator char *() {}\n"
6304                "void\n"
6305                "A::operator[]() {}\n"
6306                "void\n"
6307                "A::operator!() {}\n"
6308                "void\n"
6309                "A::operator**() {}\n"
6310                "void\n"
6311                "A::operator<Foo> *() {}\n"
6312                "void\n"
6313                "A::operator<Foo> **() {}\n"
6314                "void\n"
6315                "A::operator<Foo> &() {}\n"
6316                "void\n"
6317                "A::operator void **() {}\n",
6318                Style);
6319   verifyFormat("constexpr auto\n"
6320                "operator()() const -> reference {}\n"
6321                "constexpr auto\n"
6322                "operator>>() const -> reference {}\n"
6323                "constexpr auto\n"
6324                "operator+() const -> reference {}\n"
6325                "constexpr auto\n"
6326                "operator*() const -> reference {}\n"
6327                "constexpr auto\n"
6328                "operator->() const -> reference {}\n"
6329                "constexpr auto\n"
6330                "operator++() const -> reference {}\n"
6331                "constexpr auto\n"
6332                "operator void *() const -> reference {}\n"
6333                "constexpr auto\n"
6334                "operator void **() const -> reference {}\n"
6335                "constexpr auto\n"
6336                "operator void *() const -> reference {}\n"
6337                "constexpr auto\n"
6338                "operator void &() const -> reference {}\n"
6339                "constexpr auto\n"
6340                "operator void &&() const -> reference {}\n"
6341                "constexpr auto\n"
6342                "operator char *() const -> reference {}\n"
6343                "constexpr auto\n"
6344                "operator!() const -> reference {}\n"
6345                "constexpr auto\n"
6346                "operator[]() const -> reference {}\n",
6347                Style);
6348   verifyFormat("void *operator new(std::size_t s);", // No break here.
6349                Style);
6350   verifyFormat("void *\n"
6351                "operator new(std::size_t s) {}",
6352                Style);
6353   verifyFormat("void *\n"
6354                "operator delete[](void *ptr) {}",
6355                Style);
6356   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
6357   verifyFormat("const char *\n"
6358                "f(void)\n" // Break here.
6359                "{\n"
6360                "  return \"\";\n"
6361                "}\n"
6362                "const char *bar(void);\n", // No break here.
6363                Style);
6364   verifyFormat("template <class T>\n"
6365                "T *\n"     // Problem here: no line break
6366                "f(T &c)\n" // Break here.
6367                "{\n"
6368                "  return NULL;\n"
6369                "}\n"
6370                "template <class T> T *f(T &c);\n", // No break here.
6371                Style);
6372   verifyFormat("int\n"
6373                "foo(A<bool> a)\n"
6374                "{\n"
6375                "  return a;\n"
6376                "}\n",
6377                Style);
6378   verifyFormat("int\n"
6379                "foo(A<8> a)\n"
6380                "{\n"
6381                "  return a;\n"
6382                "}\n",
6383                Style);
6384   verifyFormat("int\n"
6385                "foo(A<B<bool>, 8> a)\n"
6386                "{\n"
6387                "  return a;\n"
6388                "}\n",
6389                Style);
6390   verifyFormat("int\n"
6391                "foo(A<B<8>, bool> a)\n"
6392                "{\n"
6393                "  return a;\n"
6394                "}\n",
6395                Style);
6396   verifyFormat("int\n"
6397                "foo(A<B<bool>, bool> a)\n"
6398                "{\n"
6399                "  return a;\n"
6400                "}\n",
6401                Style);
6402   verifyFormat("int\n"
6403                "foo(A<B<8>, 8> a)\n"
6404                "{\n"
6405                "  return a;\n"
6406                "}\n",
6407                Style);
6408 
6409   Style = getGNUStyle();
6410 
6411   // Test for comments at the end of function declarations.
6412   verifyFormat("void\n"
6413                "foo (int a, /*abc*/ int b) // def\n"
6414                "{\n"
6415                "}\n",
6416                Style);
6417 
6418   verifyFormat("void\n"
6419                "foo (int a, /* abc */ int b) /* def */\n"
6420                "{\n"
6421                "}\n",
6422                Style);
6423 
6424   // Definitions that should not break after return type
6425   verifyFormat("void foo (int a, int b); // def\n", Style);
6426   verifyFormat("void foo (int a, int b); /* def */\n", Style);
6427   verifyFormat("void foo (int a, int b);\n", Style);
6428 }
6429 
6430 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
6431   FormatStyle NoBreak = getLLVMStyle();
6432   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
6433   FormatStyle Break = getLLVMStyle();
6434   Break.AlwaysBreakBeforeMultilineStrings = true;
6435   verifyFormat("aaaa = \"bbbb\"\n"
6436                "       \"cccc\";",
6437                NoBreak);
6438   verifyFormat("aaaa =\n"
6439                "    \"bbbb\"\n"
6440                "    \"cccc\";",
6441                Break);
6442   verifyFormat("aaaa(\"bbbb\"\n"
6443                "     \"cccc\");",
6444                NoBreak);
6445   verifyFormat("aaaa(\n"
6446                "    \"bbbb\"\n"
6447                "    \"cccc\");",
6448                Break);
6449   verifyFormat("aaaa(qqq, \"bbbb\"\n"
6450                "          \"cccc\");",
6451                NoBreak);
6452   verifyFormat("aaaa(qqq,\n"
6453                "     \"bbbb\"\n"
6454                "     \"cccc\");",
6455                Break);
6456   verifyFormat("aaaa(qqq,\n"
6457                "     L\"bbbb\"\n"
6458                "     L\"cccc\");",
6459                Break);
6460   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
6461                "                      \"bbbb\"));",
6462                Break);
6463   verifyFormat("string s = someFunction(\n"
6464                "    \"abc\"\n"
6465                "    \"abc\");",
6466                Break);
6467 
6468   // As we break before unary operators, breaking right after them is bad.
6469   verifyFormat("string foo = abc ? \"x\"\n"
6470                "                   \"blah blah blah blah blah blah\"\n"
6471                "                 : \"y\";",
6472                Break);
6473 
6474   // Don't break if there is no column gain.
6475   verifyFormat("f(\"aaaa\"\n"
6476                "  \"bbbb\");",
6477                Break);
6478 
6479   // Treat literals with escaped newlines like multi-line string literals.
6480   EXPECT_EQ("x = \"a\\\n"
6481             "b\\\n"
6482             "c\";",
6483             format("x = \"a\\\n"
6484                    "b\\\n"
6485                    "c\";",
6486                    NoBreak));
6487   EXPECT_EQ("xxxx =\n"
6488             "    \"a\\\n"
6489             "b\\\n"
6490             "c\";",
6491             format("xxxx = \"a\\\n"
6492                    "b\\\n"
6493                    "c\";",
6494                    Break));
6495 
6496   EXPECT_EQ("NSString *const kString =\n"
6497             "    @\"aaaa\"\n"
6498             "    @\"bbbb\";",
6499             format("NSString *const kString = @\"aaaa\"\n"
6500                    "@\"bbbb\";",
6501                    Break));
6502 
6503   Break.ColumnLimit = 0;
6504   verifyFormat("const char *hello = \"hello llvm\";", Break);
6505 }
6506 
6507 TEST_F(FormatTest, AlignsPipes) {
6508   verifyFormat(
6509       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6510       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6511       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6512   verifyFormat(
6513       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
6514       "                     << aaaaaaaaaaaaaaaaaaaa;");
6515   verifyFormat(
6516       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6517       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6518   verifyFormat(
6519       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
6520       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6521   verifyFormat(
6522       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
6523       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
6524       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
6525   verifyFormat(
6526       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6527       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6528       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6529   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6530                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6531                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6532                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
6533   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
6534                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
6535   verifyFormat(
6536       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6537       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6538   verifyFormat(
6539       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
6540       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
6541 
6542   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
6543                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
6544   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6545                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6546                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
6547                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
6548   verifyFormat("LOG_IF(aaa == //\n"
6549                "       bbb)\n"
6550                "    << a << b;");
6551 
6552   // But sometimes, breaking before the first "<<" is desirable.
6553   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
6554                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
6555   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
6556                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6557                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6558   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
6559                "    << BEF << IsTemplate << Description << E->getType();");
6560   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
6561                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6562                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6563   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
6564                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6565                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6566                "    << aaa;");
6567 
6568   verifyFormat(
6569       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6570       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6571 
6572   // Incomplete string literal.
6573   EXPECT_EQ("llvm::errs() << \"\n"
6574             "             << a;",
6575             format("llvm::errs() << \"\n<<a;"));
6576 
6577   verifyFormat("void f() {\n"
6578                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
6579                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
6580                "}");
6581 
6582   // Handle 'endl'.
6583   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
6584                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
6585   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
6586 
6587   // Handle '\n'.
6588   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
6589                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
6590   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
6591                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
6592   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
6593                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
6594   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
6595 }
6596 
6597 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
6598   verifyFormat("return out << \"somepacket = {\\n\"\n"
6599                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
6600                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
6601                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
6602                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
6603                "           << \"}\";");
6604 
6605   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
6606                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
6607                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
6608   verifyFormat(
6609       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
6610       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
6611       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
6612       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
6613       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
6614   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
6615                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
6616   verifyFormat(
6617       "void f() {\n"
6618       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
6619       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
6620       "}");
6621 
6622   // Breaking before the first "<<" is generally not desirable.
6623   verifyFormat(
6624       "llvm::errs()\n"
6625       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6626       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6627       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6628       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6629       getLLVMStyleWithColumns(70));
6630   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
6631                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6632                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
6633                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6634                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
6635                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6636                getLLVMStyleWithColumns(70));
6637 
6638   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
6639                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
6640                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
6641   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
6642                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
6643                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
6644   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
6645                "           (aaaa + aaaa);",
6646                getLLVMStyleWithColumns(40));
6647   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
6648                "                  (aaaaaaa + aaaaa));",
6649                getLLVMStyleWithColumns(40));
6650   verifyFormat(
6651       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
6652       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
6653       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
6654 }
6655 
6656 TEST_F(FormatTest, UnderstandsEquals) {
6657   verifyFormat(
6658       "aaaaaaaaaaaaaaaaa =\n"
6659       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6660   verifyFormat(
6661       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6662       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
6663   verifyFormat(
6664       "if (a) {\n"
6665       "  f();\n"
6666       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6667       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
6668       "}");
6669 
6670   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6671                "        100000000 + 10000000) {\n}");
6672 }
6673 
6674 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
6675   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
6676                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
6677 
6678   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
6679                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
6680 
6681   verifyFormat(
6682       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
6683       "                                                          Parameter2);");
6684 
6685   verifyFormat(
6686       "ShortObject->shortFunction(\n"
6687       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
6688       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
6689 
6690   verifyFormat("loooooooooooooongFunction(\n"
6691                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
6692 
6693   verifyFormat(
6694       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
6695       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
6696 
6697   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
6698                "    .WillRepeatedly(Return(SomeValue));");
6699   verifyFormat("void f() {\n"
6700                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
6701                "      .Times(2)\n"
6702                "      .WillRepeatedly(Return(SomeValue));\n"
6703                "}");
6704   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
6705                "    ccccccccccccccccccccccc);");
6706   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6707                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6708                "          .aaaaa(aaaaa),\n"
6709                "      aaaaaaaaaaaaaaaaaaaaa);");
6710   verifyFormat("void f() {\n"
6711                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6712                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
6713                "}");
6714   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6715                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6716                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6717                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6718                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
6719   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6720                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6721                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6722                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
6723                "}");
6724 
6725   // Here, it is not necessary to wrap at "." or "->".
6726   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
6727                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
6728   verifyFormat(
6729       "aaaaaaaaaaa->aaaaaaaaa(\n"
6730       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6731       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
6732 
6733   verifyFormat(
6734       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6735       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
6736   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
6737                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
6738   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
6739                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
6740 
6741   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6742                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6743                "    .a();");
6744 
6745   FormatStyle NoBinPacking = getLLVMStyle();
6746   NoBinPacking.BinPackParameters = false;
6747   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
6748                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
6749                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
6750                "                         aaaaaaaaaaaaaaaaaaa,\n"
6751                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6752                NoBinPacking);
6753 
6754   // If there is a subsequent call, change to hanging indentation.
6755   verifyFormat(
6756       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6757       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
6758       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6759   verifyFormat(
6760       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6761       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
6762   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6763                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6764                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6765   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6766                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6767                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
6768 }
6769 
6770 TEST_F(FormatTest, WrapsTemplateDeclarations) {
6771   verifyFormat("template <typename T>\n"
6772                "virtual void loooooooooooongFunction(int Param1, int Param2);");
6773   verifyFormat("template <typename T>\n"
6774                "// T should be one of {A, B}.\n"
6775                "virtual void loooooooooooongFunction(int Param1, int Param2);");
6776   verifyFormat(
6777       "template <typename T>\n"
6778       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
6779   verifyFormat("template <typename T>\n"
6780                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
6781                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
6782   verifyFormat(
6783       "template <typename T>\n"
6784       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
6785       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
6786   verifyFormat(
6787       "template <typename T>\n"
6788       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
6789       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
6790       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6791   verifyFormat("template <typename T>\n"
6792                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6793                "    int aaaaaaaaaaaaaaaaaaaaaa);");
6794   verifyFormat(
6795       "template <typename T1, typename T2 = char, typename T3 = char,\n"
6796       "          typename T4 = char>\n"
6797       "void f();");
6798   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
6799                "          template <typename> class cccccccccccccccccccccc,\n"
6800                "          typename ddddddddddddd>\n"
6801                "class C {};");
6802   verifyFormat(
6803       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
6804       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6805 
6806   verifyFormat("void f() {\n"
6807                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
6808                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
6809                "}");
6810 
6811   verifyFormat("template <typename T> class C {};");
6812   verifyFormat("template <typename T> void f();");
6813   verifyFormat("template <typename T> void f() {}");
6814   verifyFormat(
6815       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
6816       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6817       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
6818       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
6819       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6820       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
6821       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
6822       getLLVMStyleWithColumns(72));
6823   EXPECT_EQ("static_cast<A< //\n"
6824             "    B> *>(\n"
6825             "\n"
6826             ");",
6827             format("static_cast<A<//\n"
6828                    "    B>*>(\n"
6829                    "\n"
6830                    "    );"));
6831   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6832                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
6833 
6834   FormatStyle AlwaysBreak = getLLVMStyle();
6835   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
6836   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
6837   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
6838   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
6839   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6840                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
6841                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
6842   verifyFormat("template <template <typename> class Fooooooo,\n"
6843                "          template <typename> class Baaaaaaar>\n"
6844                "struct C {};",
6845                AlwaysBreak);
6846   verifyFormat("template <typename T> // T can be A, B or C.\n"
6847                "struct C {};",
6848                AlwaysBreak);
6849   verifyFormat("template <enum E> class A {\n"
6850                "public:\n"
6851                "  E *f();\n"
6852                "};");
6853 
6854   FormatStyle NeverBreak = getLLVMStyle();
6855   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
6856   verifyFormat("template <typename T> class C {};", NeverBreak);
6857   verifyFormat("template <typename T> void f();", NeverBreak);
6858   verifyFormat("template <typename T> void f() {}", NeverBreak);
6859   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
6860                "bbbbbbbbbbbbbbbbbbbb) {}",
6861                NeverBreak);
6862   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6863                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
6864                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
6865                NeverBreak);
6866   verifyFormat("template <template <typename> class Fooooooo,\n"
6867                "          template <typename> class Baaaaaaar>\n"
6868                "struct C {};",
6869                NeverBreak);
6870   verifyFormat("template <typename T> // T can be A, B or C.\n"
6871                "struct C {};",
6872                NeverBreak);
6873   verifyFormat("template <enum E> class A {\n"
6874                "public:\n"
6875                "  E *f();\n"
6876                "};",
6877                NeverBreak);
6878   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
6879   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
6880                "bbbbbbbbbbbbbbbbbbbb) {}",
6881                NeverBreak);
6882 }
6883 
6884 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
6885   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
6886   Style.ColumnLimit = 60;
6887   EXPECT_EQ("// Baseline - no comments.\n"
6888             "template <\n"
6889             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
6890             "void f() {}",
6891             format("// Baseline - no comments.\n"
6892                    "template <\n"
6893                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
6894                    "void f() {}",
6895                    Style));
6896 
6897   EXPECT_EQ("template <\n"
6898             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
6899             "void f() {}",
6900             format("template <\n"
6901                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
6902                    "void f() {}",
6903                    Style));
6904 
6905   EXPECT_EQ(
6906       "template <\n"
6907       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
6908       "void f() {}",
6909       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
6910              "void f() {}",
6911              Style));
6912 
6913   EXPECT_EQ(
6914       "template <\n"
6915       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
6916       "                                               // multiline\n"
6917       "void f() {}",
6918       format("template <\n"
6919              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
6920              "                                              // multiline\n"
6921              "void f() {}",
6922              Style));
6923 
6924   EXPECT_EQ(
6925       "template <typename aaaaaaaaaa<\n"
6926       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
6927       "void f() {}",
6928       format(
6929           "template <\n"
6930           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
6931           "void f() {}",
6932           Style));
6933 }
6934 
6935 TEST_F(FormatTest, WrapsTemplateParameters) {
6936   FormatStyle Style = getLLVMStyle();
6937   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6938   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6939   verifyFormat(
6940       "template <typename... a> struct q {};\n"
6941       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
6942       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
6943       "    y;",
6944       Style);
6945   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6946   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6947   verifyFormat(
6948       "template <typename... a> struct r {};\n"
6949       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
6950       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
6951       "    y;",
6952       Style);
6953   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6954   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
6955   verifyFormat("template <typename... a> struct s {};\n"
6956                "extern s<\n"
6957                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
6958                "aaaaaaaaaaaaaaaaaaaaaa,\n"
6959                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
6960                "aaaaaaaaaaaaaaaaaaaaaa>\n"
6961                "    y;",
6962                Style);
6963   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6964   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
6965   verifyFormat("template <typename... a> struct t {};\n"
6966                "extern t<\n"
6967                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
6968                "aaaaaaaaaaaaaaaaaaaaaa,\n"
6969                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
6970                "aaaaaaaaaaaaaaaaaaaaaa>\n"
6971                "    y;",
6972                Style);
6973 }
6974 
6975 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
6976   verifyFormat(
6977       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
6978       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6979   verifyFormat(
6980       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
6981       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6982       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
6983 
6984   // FIXME: Should we have the extra indent after the second break?
6985   verifyFormat(
6986       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
6987       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
6988       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
6989 
6990   verifyFormat(
6991       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
6992       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
6993 
6994   // Breaking at nested name specifiers is generally not desirable.
6995   verifyFormat(
6996       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6997       "    aaaaaaaaaaaaaaaaaaaaaaa);");
6998 
6999   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
7000                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7001                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7002                "                   aaaaaaaaaaaaaaaaaaaaa);",
7003                getLLVMStyleWithColumns(74));
7004 
7005   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7006                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7007                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7008 }
7009 
7010 TEST_F(FormatTest, UnderstandsTemplateParameters) {
7011   verifyFormat("A<int> a;");
7012   verifyFormat("A<A<A<int>>> a;");
7013   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
7014   verifyFormat("bool x = a < 1 || 2 > a;");
7015   verifyFormat("bool x = 5 < f<int>();");
7016   verifyFormat("bool x = f<int>() > 5;");
7017   verifyFormat("bool x = 5 < a<int>::x;");
7018   verifyFormat("bool x = a < 4 ? a > 2 : false;");
7019   verifyFormat("bool x = f() ? a < 2 : a > 2;");
7020 
7021   verifyGoogleFormat("A<A<int>> a;");
7022   verifyGoogleFormat("A<A<A<int>>> a;");
7023   verifyGoogleFormat("A<A<A<A<int>>>> a;");
7024   verifyGoogleFormat("A<A<int> > a;");
7025   verifyGoogleFormat("A<A<A<int> > > a;");
7026   verifyGoogleFormat("A<A<A<A<int> > > > a;");
7027   verifyGoogleFormat("A<::A<int>> a;");
7028   verifyGoogleFormat("A<::A> a;");
7029   verifyGoogleFormat("A< ::A> a;");
7030   verifyGoogleFormat("A< ::A<int> > a;");
7031   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
7032   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
7033   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
7034   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
7035   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
7036             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
7037 
7038   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
7039 
7040   // template closer followed by a token that starts with > or =
7041   verifyFormat("bool b = a<1> > 1;");
7042   verifyFormat("bool b = a<1> >= 1;");
7043   verifyFormat("int i = a<1> >> 1;");
7044   FormatStyle Style = getLLVMStyle();
7045   Style.SpaceBeforeAssignmentOperators = false;
7046   verifyFormat("bool b= a<1> == 1;", Style);
7047   verifyFormat("a<int> = 1;", Style);
7048   verifyFormat("a<int> >>= 1;", Style);
7049 
7050   verifyFormat("test >> a >> b;");
7051   verifyFormat("test << a >> b;");
7052 
7053   verifyFormat("f<int>();");
7054   verifyFormat("template <typename T> void f() {}");
7055   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
7056   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
7057                "sizeof(char)>::type>;");
7058   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
7059   verifyFormat("f(a.operator()<A>());");
7060   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7061                "      .template operator()<A>());",
7062                getLLVMStyleWithColumns(35));
7063 
7064   // Not template parameters.
7065   verifyFormat("return a < b && c > d;");
7066   verifyFormat("void f() {\n"
7067                "  while (a < b && c > d) {\n"
7068                "  }\n"
7069                "}");
7070   verifyFormat("template <typename... Types>\n"
7071                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
7072 
7073   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7074                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
7075                getLLVMStyleWithColumns(60));
7076   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
7077   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
7078   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
7079 }
7080 
7081 TEST_F(FormatTest, BitshiftOperatorWidth) {
7082   EXPECT_EQ("int a = 1 << 2; /* foo\n"
7083             "                   bar */",
7084             format("int    a=1<<2;  /* foo\n"
7085                    "                   bar */"));
7086 
7087   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
7088             "                     bar */",
7089             format("int  b  =256>>1 ;  /* foo\n"
7090                    "                      bar */"));
7091 }
7092 
7093 TEST_F(FormatTest, UnderstandsBinaryOperators) {
7094   verifyFormat("COMPARE(a, ==, b);");
7095   verifyFormat("auto s = sizeof...(Ts) - 1;");
7096 }
7097 
7098 TEST_F(FormatTest, UnderstandsPointersToMembers) {
7099   verifyFormat("int A::*x;");
7100   verifyFormat("int (S::*func)(void *);");
7101   verifyFormat("void f() { int (S::*func)(void *); }");
7102   verifyFormat("typedef bool *(Class::*Member)() const;");
7103   verifyFormat("void f() {\n"
7104                "  (a->*f)();\n"
7105                "  a->*x;\n"
7106                "  (a.*f)();\n"
7107                "  ((*a).*f)();\n"
7108                "  a.*x;\n"
7109                "}");
7110   verifyFormat("void f() {\n"
7111                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
7112                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
7113                "}");
7114   verifyFormat(
7115       "(aaaaaaaaaa->*bbbbbbb)(\n"
7116       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7117   FormatStyle Style = getLLVMStyle();
7118   Style.PointerAlignment = FormatStyle::PAS_Left;
7119   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
7120 }
7121 
7122 TEST_F(FormatTest, UnderstandsUnaryOperators) {
7123   verifyFormat("int a = -2;");
7124   verifyFormat("f(-1, -2, -3);");
7125   verifyFormat("a[-1] = 5;");
7126   verifyFormat("int a = 5 + -2;");
7127   verifyFormat("if (i == -1) {\n}");
7128   verifyFormat("if (i != -1) {\n}");
7129   verifyFormat("if (i > -1) {\n}");
7130   verifyFormat("if (i < -1) {\n}");
7131   verifyFormat("++(a->f());");
7132   verifyFormat("--(a->f());");
7133   verifyFormat("(a->f())++;");
7134   verifyFormat("a[42]++;");
7135   verifyFormat("if (!(a->f())) {\n}");
7136   verifyFormat("if (!+i) {\n}");
7137   verifyFormat("~&a;");
7138 
7139   verifyFormat("a-- > b;");
7140   verifyFormat("b ? -a : c;");
7141   verifyFormat("n * sizeof char16;");
7142   verifyFormat("n * alignof char16;", getGoogleStyle());
7143   verifyFormat("sizeof(char);");
7144   verifyFormat("alignof(char);", getGoogleStyle());
7145 
7146   verifyFormat("return -1;");
7147   verifyFormat("throw -1;");
7148   verifyFormat("switch (a) {\n"
7149                "case -1:\n"
7150                "  break;\n"
7151                "}");
7152   verifyFormat("#define X -1");
7153   verifyFormat("#define X -kConstant");
7154 
7155   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
7156   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
7157 
7158   verifyFormat("int a = /* confusing comment */ -1;");
7159   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
7160   verifyFormat("int a = i /* confusing comment */++;");
7161 
7162   verifyFormat("co_yield -1;");
7163   verifyFormat("co_return -1;");
7164 }
7165 
7166 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
7167   verifyFormat("if (!aaaaaaaaaa( // break\n"
7168                "        aaaaa)) {\n"
7169                "}");
7170   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
7171                "    aaaaa));");
7172   verifyFormat("*aaa = aaaaaaa( // break\n"
7173                "    bbbbbb);");
7174 }
7175 
7176 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
7177   verifyFormat("bool operator<();");
7178   verifyFormat("bool operator>();");
7179   verifyFormat("bool operator=();");
7180   verifyFormat("bool operator==();");
7181   verifyFormat("bool operator!=();");
7182   verifyFormat("int operator+();");
7183   verifyFormat("int operator++();");
7184   verifyFormat("int operator++(int) volatile noexcept;");
7185   verifyFormat("bool operator,();");
7186   verifyFormat("bool operator();");
7187   verifyFormat("bool operator()();");
7188   verifyFormat("bool operator[]();");
7189   verifyFormat("operator bool();");
7190   verifyFormat("operator int();");
7191   verifyFormat("operator void *();");
7192   verifyFormat("operator SomeType<int>();");
7193   verifyFormat("operator SomeType<int, int>();");
7194   verifyFormat("operator SomeType<SomeType<int>>();");
7195   verifyFormat("void *operator new(std::size_t size);");
7196   verifyFormat("void *operator new[](std::size_t size);");
7197   verifyFormat("void operator delete(void *ptr);");
7198   verifyFormat("void operator delete[](void *ptr);");
7199   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
7200                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
7201   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
7202                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
7203 
7204   verifyFormat(
7205       "ostream &operator<<(ostream &OutputStream,\n"
7206       "                    SomeReallyLongType WithSomeReallyLongValue);");
7207   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
7208                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
7209                "  return left.group < right.group;\n"
7210                "}");
7211   verifyFormat("SomeType &operator=(const SomeType &S);");
7212   verifyFormat("f.template operator()<int>();");
7213 
7214   verifyGoogleFormat("operator void*();");
7215   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
7216   verifyGoogleFormat("operator ::A();");
7217 
7218   verifyFormat("using A::operator+;");
7219   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
7220                "int i;");
7221 }
7222 
7223 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
7224   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
7225   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
7226   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
7227   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
7228   verifyFormat("Deleted &operator=(const Deleted &) &;");
7229   verifyFormat("Deleted &operator=(const Deleted &) &&;");
7230   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
7231   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
7232   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
7233   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
7234   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
7235   verifyFormat("void Fn(T const &) const &;");
7236   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
7237   verifyFormat("template <typename T>\n"
7238                "void F(T) && = delete;",
7239                getGoogleStyle());
7240 
7241   FormatStyle AlignLeft = getLLVMStyle();
7242   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
7243   verifyFormat("void A::b() && {}", AlignLeft);
7244   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
7245   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
7246                AlignLeft);
7247   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
7248   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
7249   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
7250   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
7251   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
7252   verifyFormat("auto Function(T) & -> void;", AlignLeft);
7253   verifyFormat("void Fn(T const&) const&;", AlignLeft);
7254   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
7255 
7256   FormatStyle Spaces = getLLVMStyle();
7257   Spaces.SpacesInCStyleCastParentheses = true;
7258   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
7259   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
7260   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
7261   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
7262 
7263   Spaces.SpacesInCStyleCastParentheses = false;
7264   Spaces.SpacesInParentheses = true;
7265   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
7266   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
7267                Spaces);
7268   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
7269   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
7270 
7271   FormatStyle BreakTemplate = getLLVMStyle();
7272   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7273 
7274   verifyFormat("struct f {\n"
7275                "  template <class T>\n"
7276                "  int &foo(const std::string &str) &noexcept {}\n"
7277                "};",
7278                BreakTemplate);
7279 
7280   verifyFormat("struct f {\n"
7281                "  template <class T>\n"
7282                "  int &foo(const std::string &str) &&noexcept {}\n"
7283                "};",
7284                BreakTemplate);
7285 
7286   verifyFormat("struct f {\n"
7287                "  template <class T>\n"
7288                "  int &foo(const std::string &str) const &noexcept {}\n"
7289                "};",
7290                BreakTemplate);
7291 
7292   verifyFormat("struct f {\n"
7293                "  template <class T>\n"
7294                "  int &foo(const std::string &str) const &noexcept {}\n"
7295                "};",
7296                BreakTemplate);
7297 
7298   verifyFormat("struct f {\n"
7299                "  template <class T>\n"
7300                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
7301                "};",
7302                BreakTemplate);
7303 
7304   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
7305   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
7306       FormatStyle::BTDS_Yes;
7307   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
7308 
7309   verifyFormat("struct f {\n"
7310                "  template <class T>\n"
7311                "  int& foo(const std::string& str) & noexcept {}\n"
7312                "};",
7313                AlignLeftBreakTemplate);
7314 
7315   verifyFormat("struct f {\n"
7316                "  template <class T>\n"
7317                "  int& foo(const std::string& str) && noexcept {}\n"
7318                "};",
7319                AlignLeftBreakTemplate);
7320 
7321   verifyFormat("struct f {\n"
7322                "  template <class T>\n"
7323                "  int& foo(const std::string& str) const& noexcept {}\n"
7324                "};",
7325                AlignLeftBreakTemplate);
7326 
7327   verifyFormat("struct f {\n"
7328                "  template <class T>\n"
7329                "  int& foo(const std::string& str) const&& noexcept {}\n"
7330                "};",
7331                AlignLeftBreakTemplate);
7332 
7333   verifyFormat("struct f {\n"
7334                "  template <class T>\n"
7335                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
7336                "};",
7337                AlignLeftBreakTemplate);
7338 
7339   // The `&` in `Type&` should not be confused with a trailing `&` of
7340   // DEPRECATED(reason) member function.
7341   verifyFormat("struct f {\n"
7342                "  template <class T>\n"
7343                "  DEPRECATED(reason)\n"
7344                "  Type &foo(arguments) {}\n"
7345                "};",
7346                BreakTemplate);
7347 
7348   verifyFormat("struct f {\n"
7349                "  template <class T>\n"
7350                "  DEPRECATED(reason)\n"
7351                "  Type& foo(arguments) {}\n"
7352                "};",
7353                AlignLeftBreakTemplate);
7354 
7355   verifyFormat("void (*foopt)(int) = &func;");
7356 }
7357 
7358 TEST_F(FormatTest, UnderstandsNewAndDelete) {
7359   verifyFormat("void f() {\n"
7360                "  A *a = new A;\n"
7361                "  A *a = new (placement) A;\n"
7362                "  delete a;\n"
7363                "  delete (A *)a;\n"
7364                "}");
7365   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
7366                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
7367   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7368                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
7369                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
7370   verifyFormat("delete[] h->p;");
7371 }
7372 
7373 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
7374   verifyFormat("int *f(int *a) {}");
7375   verifyFormat("int main(int argc, char **argv) {}");
7376   verifyFormat("Test::Test(int b) : a(b * b) {}");
7377   verifyIndependentOfContext("f(a, *a);");
7378   verifyFormat("void g() { f(*a); }");
7379   verifyIndependentOfContext("int a = b * 10;");
7380   verifyIndependentOfContext("int a = 10 * b;");
7381   verifyIndependentOfContext("int a = b * c;");
7382   verifyIndependentOfContext("int a += b * c;");
7383   verifyIndependentOfContext("int a -= b * c;");
7384   verifyIndependentOfContext("int a *= b * c;");
7385   verifyIndependentOfContext("int a /= b * c;");
7386   verifyIndependentOfContext("int a = *b;");
7387   verifyIndependentOfContext("int a = *b * c;");
7388   verifyIndependentOfContext("int a = b * *c;");
7389   verifyIndependentOfContext("int a = b * (10);");
7390   verifyIndependentOfContext("S << b * (10);");
7391   verifyIndependentOfContext("return 10 * b;");
7392   verifyIndependentOfContext("return *b * *c;");
7393   verifyIndependentOfContext("return a & ~b;");
7394   verifyIndependentOfContext("f(b ? *c : *d);");
7395   verifyIndependentOfContext("int a = b ? *c : *d;");
7396   verifyIndependentOfContext("*b = a;");
7397   verifyIndependentOfContext("a * ~b;");
7398   verifyIndependentOfContext("a * !b;");
7399   verifyIndependentOfContext("a * +b;");
7400   verifyIndependentOfContext("a * -b;");
7401   verifyIndependentOfContext("a * ++b;");
7402   verifyIndependentOfContext("a * --b;");
7403   verifyIndependentOfContext("a[4] * b;");
7404   verifyIndependentOfContext("a[a * a] = 1;");
7405   verifyIndependentOfContext("f() * b;");
7406   verifyIndependentOfContext("a * [self dostuff];");
7407   verifyIndependentOfContext("int x = a * (a + b);");
7408   verifyIndependentOfContext("(a *)(a + b);");
7409   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
7410   verifyIndependentOfContext("int *pa = (int *)&a;");
7411   verifyIndependentOfContext("return sizeof(int **);");
7412   verifyIndependentOfContext("return sizeof(int ******);");
7413   verifyIndependentOfContext("return (int **&)a;");
7414   verifyIndependentOfContext("f((*PointerToArray)[10]);");
7415   verifyFormat("void f(Type (*parameter)[10]) {}");
7416   verifyFormat("void f(Type (&parameter)[10]) {}");
7417   verifyGoogleFormat("return sizeof(int**);");
7418   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
7419   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
7420   verifyFormat("auto a = [](int **&, int ***) {};");
7421   verifyFormat("auto PointerBinding = [](const char *S) {};");
7422   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
7423   verifyFormat("[](const decltype(*a) &value) {}");
7424   verifyFormat("decltype(a * b) F();");
7425   verifyFormat("#define MACRO() [](A *a) { return 1; }");
7426   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
7427   verifyIndependentOfContext("typedef void (*f)(int *a);");
7428   verifyIndependentOfContext("int i{a * b};");
7429   verifyIndependentOfContext("aaa && aaa->f();");
7430   verifyIndependentOfContext("int x = ~*p;");
7431   verifyFormat("Constructor() : a(a), area(width * height) {}");
7432   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
7433   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
7434   verifyFormat("void f() { f(a, c * d); }");
7435   verifyFormat("void f() { f(new a(), c * d); }");
7436   verifyFormat("void f(const MyOverride &override);");
7437   verifyFormat("void f(const MyFinal &final);");
7438   verifyIndependentOfContext("bool a = f() && override.f();");
7439   verifyIndependentOfContext("bool a = f() && final.f();");
7440 
7441   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
7442 
7443   verifyIndependentOfContext("A<int *> a;");
7444   verifyIndependentOfContext("A<int **> a;");
7445   verifyIndependentOfContext("A<int *, int *> a;");
7446   verifyIndependentOfContext("A<int *[]> a;");
7447   verifyIndependentOfContext(
7448       "const char *const p = reinterpret_cast<const char *const>(q);");
7449   verifyIndependentOfContext("A<int **, int **> a;");
7450   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
7451   verifyFormat("for (char **a = b; *a; ++a) {\n}");
7452   verifyFormat("for (; a && b;) {\n}");
7453   verifyFormat("bool foo = true && [] { return false; }();");
7454 
7455   verifyFormat(
7456       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7457       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7458 
7459   verifyGoogleFormat("int const* a = &b;");
7460   verifyGoogleFormat("**outparam = 1;");
7461   verifyGoogleFormat("*outparam = a * b;");
7462   verifyGoogleFormat("int main(int argc, char** argv) {}");
7463   verifyGoogleFormat("A<int*> a;");
7464   verifyGoogleFormat("A<int**> a;");
7465   verifyGoogleFormat("A<int*, int*> a;");
7466   verifyGoogleFormat("A<int**, int**> a;");
7467   verifyGoogleFormat("f(b ? *c : *d);");
7468   verifyGoogleFormat("int a = b ? *c : *d;");
7469   verifyGoogleFormat("Type* t = **x;");
7470   verifyGoogleFormat("Type* t = *++*x;");
7471   verifyGoogleFormat("*++*x;");
7472   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
7473   verifyGoogleFormat("Type* t = x++ * y;");
7474   verifyGoogleFormat(
7475       "const char* const p = reinterpret_cast<const char* const>(q);");
7476   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
7477   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
7478   verifyGoogleFormat("template <typename T>\n"
7479                      "void f(int i = 0, SomeType** temps = NULL);");
7480 
7481   FormatStyle Left = getLLVMStyle();
7482   Left.PointerAlignment = FormatStyle::PAS_Left;
7483   verifyFormat("x = *a(x) = *a(y);", Left);
7484   verifyFormat("for (;; *a = b) {\n}", Left);
7485   verifyFormat("return *this += 1;", Left);
7486   verifyFormat("throw *x;", Left);
7487   verifyFormat("delete *x;", Left);
7488   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
7489   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
7490   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
7491   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
7492   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
7493   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
7494 
7495   verifyIndependentOfContext("a = *(x + y);");
7496   verifyIndependentOfContext("a = &(x + y);");
7497   verifyIndependentOfContext("*(x + y).call();");
7498   verifyIndependentOfContext("&(x + y)->call();");
7499   verifyFormat("void f() { &(*I).first; }");
7500 
7501   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
7502   verifyFormat(
7503       "int *MyValues = {\n"
7504       "    *A, // Operator detection might be confused by the '{'\n"
7505       "    *BB // Operator detection might be confused by previous comment\n"
7506       "};");
7507 
7508   verifyIndependentOfContext("if (int *a = &b)");
7509   verifyIndependentOfContext("if (int &a = *b)");
7510   verifyIndependentOfContext("if (a & b[i])");
7511   verifyIndependentOfContext("if constexpr (a & b[i])");
7512   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
7513   verifyIndependentOfContext("if (a * (b * c))");
7514   verifyIndependentOfContext("if constexpr (a * (b * c))");
7515   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
7516   verifyIndependentOfContext("if (a::b::c::d & b[i])");
7517   verifyIndependentOfContext("if (*b[i])");
7518   verifyIndependentOfContext("if (int *a = (&b))");
7519   verifyIndependentOfContext("while (int *a = &b)");
7520   verifyIndependentOfContext("while (a * (b * c))");
7521   verifyIndependentOfContext("size = sizeof *a;");
7522   verifyIndependentOfContext("if (a && (b = c))");
7523   verifyFormat("void f() {\n"
7524                "  for (const int &v : Values) {\n"
7525                "  }\n"
7526                "}");
7527   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
7528   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
7529   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
7530 
7531   verifyFormat("#define A (!a * b)");
7532   verifyFormat("#define MACRO     \\\n"
7533                "  int *i = a * b; \\\n"
7534                "  void f(a *b);",
7535                getLLVMStyleWithColumns(19));
7536 
7537   verifyIndependentOfContext("A = new SomeType *[Length];");
7538   verifyIndependentOfContext("A = new SomeType *[Length]();");
7539   verifyIndependentOfContext("T **t = new T *;");
7540   verifyIndependentOfContext("T **t = new T *();");
7541   verifyGoogleFormat("A = new SomeType*[Length]();");
7542   verifyGoogleFormat("A = new SomeType*[Length];");
7543   verifyGoogleFormat("T** t = new T*;");
7544   verifyGoogleFormat("T** t = new T*();");
7545 
7546   verifyFormat("STATIC_ASSERT((a & b) == 0);");
7547   verifyFormat("STATIC_ASSERT(0 == (a & b));");
7548   verifyFormat("template <bool a, bool b> "
7549                "typename t::if<x && y>::type f() {}");
7550   verifyFormat("template <int *y> f() {}");
7551   verifyFormat("vector<int *> v;");
7552   verifyFormat("vector<int *const> v;");
7553   verifyFormat("vector<int *const **const *> v;");
7554   verifyFormat("vector<int *volatile> v;");
7555   verifyFormat("vector<a * b> v;");
7556   verifyFormat("foo<b && false>();");
7557   verifyFormat("foo<b & 1>();");
7558   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
7559   verifyFormat(
7560       "template <class T, class = typename std::enable_if<\n"
7561       "                       std::is_integral<T>::value &&\n"
7562       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
7563       "void F();",
7564       getLLVMStyleWithColumns(70));
7565   verifyFormat("template <class T,\n"
7566                "          class = typename std::enable_if<\n"
7567                "              std::is_integral<T>::value &&\n"
7568                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
7569                "          class U>\n"
7570                "void F();",
7571                getLLVMStyleWithColumns(70));
7572   verifyFormat(
7573       "template <class T,\n"
7574       "          class = typename ::std::enable_if<\n"
7575       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
7576       "void F();",
7577       getGoogleStyleWithColumns(68));
7578 
7579   verifyIndependentOfContext("MACRO(int *i);");
7580   verifyIndependentOfContext("MACRO(auto *a);");
7581   verifyIndependentOfContext("MACRO(const A *a);");
7582   verifyIndependentOfContext("MACRO(A *const a);");
7583   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
7584   verifyFormat("void f() { f(float{1}, a * a); }");
7585   // FIXME: Is there a way to make this work?
7586   // verifyIndependentOfContext("MACRO(A *a);");
7587 
7588   verifyFormat("DatumHandle const *operator->() const { return input_; }");
7589   verifyFormat("return options != nullptr && operator==(*options);");
7590 
7591   EXPECT_EQ("#define OP(x)                                    \\\n"
7592             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
7593             "    return s << a.DebugString();                 \\\n"
7594             "  }",
7595             format("#define OP(x) \\\n"
7596                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
7597                    "    return s << a.DebugString(); \\\n"
7598                    "  }",
7599                    getLLVMStyleWithColumns(50)));
7600 
7601   // FIXME: We cannot handle this case yet; we might be able to figure out that
7602   // foo<x> d > v; doesn't make sense.
7603   verifyFormat("foo<a<b && c> d> v;");
7604 
7605   FormatStyle PointerMiddle = getLLVMStyle();
7606   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
7607   verifyFormat("delete *x;", PointerMiddle);
7608   verifyFormat("int * x;", PointerMiddle);
7609   verifyFormat("int *[] x;", PointerMiddle);
7610   verifyFormat("template <int * y> f() {}", PointerMiddle);
7611   verifyFormat("int * f(int * a) {}", PointerMiddle);
7612   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
7613   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
7614   verifyFormat("A<int *> a;", PointerMiddle);
7615   verifyFormat("A<int **> a;", PointerMiddle);
7616   verifyFormat("A<int *, int *> a;", PointerMiddle);
7617   verifyFormat("A<int *[]> a;", PointerMiddle);
7618   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
7619   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
7620   verifyFormat("T ** t = new T *;", PointerMiddle);
7621 
7622   // Member function reference qualifiers aren't binary operators.
7623   verifyFormat("string // break\n"
7624                "operator()() & {}");
7625   verifyFormat("string // break\n"
7626                "operator()() && {}");
7627   verifyGoogleFormat("template <typename T>\n"
7628                      "auto x() & -> int {}");
7629 }
7630 
7631 TEST_F(FormatTest, UnderstandsAttributes) {
7632   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
7633   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
7634                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
7635   FormatStyle AfterType = getLLVMStyle();
7636   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
7637   verifyFormat("__attribute__((nodebug)) void\n"
7638                "foo() {}\n",
7639                AfterType);
7640 }
7641 
7642 TEST_F(FormatTest, UnderstandsSquareAttributes) {
7643   verifyFormat("SomeType s [[unused]] (InitValue);");
7644   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
7645   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
7646   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
7647   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
7648   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7649                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
7650   verifyFormat("[[nodiscard]] bool f() { return false; }");
7651   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
7652   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
7653   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
7654 
7655   // Make sure we do not mistake attributes for array subscripts.
7656   verifyFormat("int a() {}\n"
7657                "[[unused]] int b() {}\n");
7658   verifyFormat("NSArray *arr;\n"
7659                "arr[[Foo() bar]];");
7660 
7661   // On the other hand, we still need to correctly find array subscripts.
7662   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
7663 
7664   // Make sure that we do not mistake Objective-C method inside array literals
7665   // as attributes, even if those method names are also keywords.
7666   verifyFormat("@[ [foo bar] ];");
7667   verifyFormat("@[ [NSArray class] ];");
7668   verifyFormat("@[ [foo enum] ];");
7669 
7670   // Make sure we do not parse attributes as lambda introducers.
7671   FormatStyle MultiLineFunctions = getLLVMStyle();
7672   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
7673   verifyFormat("[[unused]] int b() {\n"
7674                "  return 42;\n"
7675                "}\n",
7676                MultiLineFunctions);
7677 }
7678 
7679 TEST_F(FormatTest, AttributePenaltyBreaking) {
7680   FormatStyle Style = getLLVMStyle();
7681   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
7682                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
7683                Style);
7684   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
7685                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
7686                Style);
7687   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
7688                "shared_ptr<ALongTypeName> &C d) {\n}",
7689                Style);
7690 }
7691 
7692 TEST_F(FormatTest, UnderstandsEllipsis) {
7693   verifyFormat("int printf(const char *fmt, ...);");
7694   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
7695   verifyFormat("template <class... Ts> void Foo(Ts *... ts) {}");
7696 
7697   FormatStyle PointersLeft = getLLVMStyle();
7698   PointersLeft.PointerAlignment = FormatStyle::PAS_Left;
7699   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", PointersLeft);
7700 }
7701 
7702 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
7703   EXPECT_EQ("int *a;\n"
7704             "int *a;\n"
7705             "int *a;",
7706             format("int *a;\n"
7707                    "int* a;\n"
7708                    "int *a;",
7709                    getGoogleStyle()));
7710   EXPECT_EQ("int* a;\n"
7711             "int* a;\n"
7712             "int* a;",
7713             format("int* a;\n"
7714                    "int* a;\n"
7715                    "int *a;",
7716                    getGoogleStyle()));
7717   EXPECT_EQ("int *a;\n"
7718             "int *a;\n"
7719             "int *a;",
7720             format("int *a;\n"
7721                    "int * a;\n"
7722                    "int *  a;",
7723                    getGoogleStyle()));
7724   EXPECT_EQ("auto x = [] {\n"
7725             "  int *a;\n"
7726             "  int *a;\n"
7727             "  int *a;\n"
7728             "};",
7729             format("auto x=[]{int *a;\n"
7730                    "int * a;\n"
7731                    "int *  a;};",
7732                    getGoogleStyle()));
7733 }
7734 
7735 TEST_F(FormatTest, UnderstandsRvalueReferences) {
7736   verifyFormat("int f(int &&a) {}");
7737   verifyFormat("int f(int a, char &&b) {}");
7738   verifyFormat("void f() { int &&a = b; }");
7739   verifyGoogleFormat("int f(int a, char&& b) {}");
7740   verifyGoogleFormat("void f() { int&& a = b; }");
7741 
7742   verifyIndependentOfContext("A<int &&> a;");
7743   verifyIndependentOfContext("A<int &&, int &&> a;");
7744   verifyGoogleFormat("A<int&&> a;");
7745   verifyGoogleFormat("A<int&&, int&&> a;");
7746 
7747   // Not rvalue references:
7748   verifyFormat("template <bool B, bool C> class A {\n"
7749                "  static_assert(B && C, \"Something is wrong\");\n"
7750                "};");
7751   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
7752   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
7753   verifyFormat("#define A(a, b) (a && b)");
7754 }
7755 
7756 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
7757   verifyFormat("void f() {\n"
7758                "  x[aaaaaaaaa -\n"
7759                "    b] = 23;\n"
7760                "}",
7761                getLLVMStyleWithColumns(15));
7762 }
7763 
7764 TEST_F(FormatTest, FormatsCasts) {
7765   verifyFormat("Type *A = static_cast<Type *>(P);");
7766   verifyFormat("Type *A = (Type *)P;");
7767   verifyFormat("Type *A = (vector<Type *, int *>)P;");
7768   verifyFormat("int a = (int)(2.0f);");
7769   verifyFormat("int a = (int)2.0f;");
7770   verifyFormat("x[(int32)y];");
7771   verifyFormat("x = (int32)y;");
7772   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
7773   verifyFormat("int a = (int)*b;");
7774   verifyFormat("int a = (int)2.0f;");
7775   verifyFormat("int a = (int)~0;");
7776   verifyFormat("int a = (int)++a;");
7777   verifyFormat("int a = (int)sizeof(int);");
7778   verifyFormat("int a = (int)+2;");
7779   verifyFormat("my_int a = (my_int)2.0f;");
7780   verifyFormat("my_int a = (my_int)sizeof(int);");
7781   verifyFormat("return (my_int)aaa;");
7782   verifyFormat("#define x ((int)-1)");
7783   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
7784   verifyFormat("#define p(q) ((int *)&q)");
7785   verifyFormat("fn(a)(b) + 1;");
7786 
7787   verifyFormat("void f() { my_int a = (my_int)*b; }");
7788   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
7789   verifyFormat("my_int a = (my_int)~0;");
7790   verifyFormat("my_int a = (my_int)++a;");
7791   verifyFormat("my_int a = (my_int)-2;");
7792   verifyFormat("my_int a = (my_int)1;");
7793   verifyFormat("my_int a = (my_int *)1;");
7794   verifyFormat("my_int a = (const my_int)-1;");
7795   verifyFormat("my_int a = (const my_int *)-1;");
7796   verifyFormat("my_int a = (my_int)(my_int)-1;");
7797   verifyFormat("my_int a = (ns::my_int)-2;");
7798   verifyFormat("case (my_int)ONE:");
7799   verifyFormat("auto x = (X)this;");
7800   // Casts in Obj-C style calls used to not be recognized as such.
7801   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
7802 
7803   // FIXME: single value wrapped with paren will be treated as cast.
7804   verifyFormat("void f(int i = (kValue)*kMask) {}");
7805 
7806   verifyFormat("{ (void)F; }");
7807 
7808   // Don't break after a cast's
7809   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7810                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
7811                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
7812 
7813   // These are not casts.
7814   verifyFormat("void f(int *) {}");
7815   verifyFormat("f(foo)->b;");
7816   verifyFormat("f(foo).b;");
7817   verifyFormat("f(foo)(b);");
7818   verifyFormat("f(foo)[b];");
7819   verifyFormat("[](foo) { return 4; }(bar);");
7820   verifyFormat("(*funptr)(foo)[4];");
7821   verifyFormat("funptrs[4](foo)[4];");
7822   verifyFormat("void f(int *);");
7823   verifyFormat("void f(int *) = 0;");
7824   verifyFormat("void f(SmallVector<int>) {}");
7825   verifyFormat("void f(SmallVector<int>);");
7826   verifyFormat("void f(SmallVector<int>) = 0;");
7827   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
7828   verifyFormat("int a = sizeof(int) * b;");
7829   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
7830   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
7831   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
7832   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
7833 
7834   // These are not casts, but at some point were confused with casts.
7835   verifyFormat("virtual void foo(int *) override;");
7836   verifyFormat("virtual void foo(char &) const;");
7837   verifyFormat("virtual void foo(int *a, char *) const;");
7838   verifyFormat("int a = sizeof(int *) + b;");
7839   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
7840   verifyFormat("bool b = f(g<int>) && c;");
7841   verifyFormat("typedef void (*f)(int i) func;");
7842   verifyFormat("void operator++(int) noexcept;");
7843   verifyFormat("void operator++(int &) noexcept;");
7844   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
7845                "&) noexcept;");
7846   verifyFormat(
7847       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
7848   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
7849   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
7850   verifyFormat("void operator delete(nothrow_t &) noexcept;");
7851   verifyFormat("void operator delete(foo &) noexcept;");
7852   verifyFormat("void operator delete(foo) noexcept;");
7853   verifyFormat("void operator delete(int) noexcept;");
7854   verifyFormat("void operator delete(int &) noexcept;");
7855   verifyFormat("void operator delete(int &) volatile noexcept;");
7856   verifyFormat("void operator delete(int &) const");
7857   verifyFormat("void operator delete(int &) = default");
7858   verifyFormat("void operator delete(int &) = delete");
7859   verifyFormat("void operator delete(int &) [[noreturn]]");
7860   verifyFormat("void operator delete(int &) throw();");
7861   verifyFormat("void operator delete(int &) throw(int);");
7862   verifyFormat("auto operator delete(int &) -> int;");
7863   verifyFormat("auto operator delete(int &) override");
7864   verifyFormat("auto operator delete(int &) final");
7865 
7866   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
7867                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7868   // FIXME: The indentation here is not ideal.
7869   verifyFormat(
7870       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7871       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
7872       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
7873 }
7874 
7875 TEST_F(FormatTest, FormatsFunctionTypes) {
7876   verifyFormat("A<bool()> a;");
7877   verifyFormat("A<SomeType()> a;");
7878   verifyFormat("A<void (*)(int, std::string)> a;");
7879   verifyFormat("A<void *(int)>;");
7880   verifyFormat("void *(*a)(int *, SomeType *);");
7881   verifyFormat("int (*func)(void *);");
7882   verifyFormat("void f() { int (*func)(void *); }");
7883   verifyFormat("template <class CallbackClass>\n"
7884                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
7885 
7886   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
7887   verifyGoogleFormat("void* (*a)(int);");
7888   verifyGoogleFormat(
7889       "template <class CallbackClass>\n"
7890       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
7891 
7892   // Other constructs can look somewhat like function types:
7893   verifyFormat("A<sizeof(*x)> a;");
7894   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
7895   verifyFormat("some_var = function(*some_pointer_var)[0];");
7896   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
7897   verifyFormat("int x = f(&h)();");
7898   verifyFormat("returnsFunction(&param1, &param2)(param);");
7899   verifyFormat("std::function<\n"
7900                "    LooooooooooongTemplatedType<\n"
7901                "        SomeType>*(\n"
7902                "        LooooooooooooooooongType type)>\n"
7903                "    function;",
7904                getGoogleStyleWithColumns(40));
7905 }
7906 
7907 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
7908   verifyFormat("A (*foo_)[6];");
7909   verifyFormat("vector<int> (*foo_)[6];");
7910 }
7911 
7912 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
7913   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
7914                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
7915   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
7916                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
7917   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
7918                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
7919 
7920   // Different ways of ()-initializiation.
7921   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
7922                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
7923   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
7924                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
7925   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
7926                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
7927   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
7928                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
7929 
7930   // Lambdas should not confuse the variable declaration heuristic.
7931   verifyFormat("LooooooooooooooooongType\n"
7932                "    variable(nullptr, [](A *a) {});",
7933                getLLVMStyleWithColumns(40));
7934 }
7935 
7936 TEST_F(FormatTest, BreaksLongDeclarations) {
7937   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
7938                "    AnotherNameForTheLongType;");
7939   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
7940                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7941   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
7942                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
7943   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
7944                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
7945   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
7946                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
7947   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
7948                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
7949   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
7950                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
7951   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
7952                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
7953   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
7954                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
7955   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
7956                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
7957   FormatStyle Indented = getLLVMStyle();
7958   Indented.IndentWrappedFunctionNames = true;
7959   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
7960                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
7961                Indented);
7962   verifyFormat(
7963       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
7964       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
7965       Indented);
7966   verifyFormat(
7967       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
7968       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
7969       Indented);
7970   verifyFormat(
7971       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
7972       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
7973       Indented);
7974 
7975   // FIXME: Without the comment, this breaks after "(".
7976   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
7977                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
7978                getGoogleStyle());
7979 
7980   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
7981                "                  int LoooooooooooooooooooongParam2) {}");
7982   verifyFormat(
7983       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
7984       "                                   SourceLocation L, IdentifierIn *II,\n"
7985       "                                   Type *T) {}");
7986   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
7987                "ReallyReaaallyLongFunctionName(\n"
7988                "    const std::string &SomeParameter,\n"
7989                "    const SomeType<string, SomeOtherTemplateParameter>\n"
7990                "        &ReallyReallyLongParameterName,\n"
7991                "    const SomeType<string, SomeOtherTemplateParameter>\n"
7992                "        &AnotherLongParameterName) {}");
7993   verifyFormat("template <typename A>\n"
7994                "SomeLoooooooooooooooooooooongType<\n"
7995                "    typename some_namespace::SomeOtherType<A>::Type>\n"
7996                "Function() {}");
7997 
7998   verifyGoogleFormat(
7999       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
8000       "    aaaaaaaaaaaaaaaaaaaaaaa;");
8001   verifyGoogleFormat(
8002       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
8003       "                                   SourceLocation L) {}");
8004   verifyGoogleFormat(
8005       "some_namespace::LongReturnType\n"
8006       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
8007       "    int first_long_parameter, int second_parameter) {}");
8008 
8009   verifyGoogleFormat("template <typename T>\n"
8010                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
8011                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
8012   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8013                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
8014 
8015   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
8016                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8017                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8018   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8019                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
8020                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
8021   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8022                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
8023                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
8024                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8025 
8026   verifyFormat("template <typename T> // Templates on own line.\n"
8027                "static int            // Some comment.\n"
8028                "MyFunction(int a);",
8029                getLLVMStyle());
8030 }
8031 
8032 TEST_F(FormatTest, FormatsArrays) {
8033   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
8034                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
8035   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
8036                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
8037   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
8038                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
8039   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8040                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
8041   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8042                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
8043   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8044                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
8045                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
8046   verifyFormat(
8047       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
8048       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
8049       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
8050   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
8051                "    .aaaaaaaaaaaaaaaaaaaaaa();");
8052 
8053   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
8054                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
8055   verifyFormat(
8056       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
8057       "                                  .aaaaaaa[0]\n"
8058       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
8059   verifyFormat("a[::b::c];");
8060 
8061   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
8062 
8063   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
8064   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
8065 }
8066 
8067 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
8068   verifyFormat("(a)->b();");
8069   verifyFormat("--a;");
8070 }
8071 
8072 TEST_F(FormatTest, HandlesIncludeDirectives) {
8073   verifyFormat("#include <string>\n"
8074                "#include <a/b/c.h>\n"
8075                "#include \"a/b/string\"\n"
8076                "#include \"string.h\"\n"
8077                "#include \"string.h\"\n"
8078                "#include <a-a>\n"
8079                "#include < path with space >\n"
8080                "#include_next <test.h>"
8081                "#include \"abc.h\" // this is included for ABC\n"
8082                "#include \"some long include\" // with a comment\n"
8083                "#include \"some very long include path\"\n"
8084                "#include <some/very/long/include/path>\n",
8085                getLLVMStyleWithColumns(35));
8086   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
8087   EXPECT_EQ("#include <a>", format("#include<a>"));
8088 
8089   verifyFormat("#import <string>");
8090   verifyFormat("#import <a/b/c.h>");
8091   verifyFormat("#import \"a/b/string\"");
8092   verifyFormat("#import \"string.h\"");
8093   verifyFormat("#import \"string.h\"");
8094   verifyFormat("#if __has_include(<strstream>)\n"
8095                "#include <strstream>\n"
8096                "#endif");
8097 
8098   verifyFormat("#define MY_IMPORT <a/b>");
8099 
8100   verifyFormat("#if __has_include(<a/b>)");
8101   verifyFormat("#if __has_include_next(<a/b>)");
8102   verifyFormat("#define F __has_include(<a/b>)");
8103   verifyFormat("#define F __has_include_next(<a/b>)");
8104 
8105   // Protocol buffer definition or missing "#".
8106   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
8107                getLLVMStyleWithColumns(30));
8108 
8109   FormatStyle Style = getLLVMStyle();
8110   Style.AlwaysBreakBeforeMultilineStrings = true;
8111   Style.ColumnLimit = 0;
8112   verifyFormat("#import \"abc.h\"", Style);
8113 
8114   // But 'import' might also be a regular C++ namespace.
8115   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8116                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8117 }
8118 
8119 //===----------------------------------------------------------------------===//
8120 // Error recovery tests.
8121 //===----------------------------------------------------------------------===//
8122 
8123 TEST_F(FormatTest, IncompleteParameterLists) {
8124   FormatStyle NoBinPacking = getLLVMStyle();
8125   NoBinPacking.BinPackParameters = false;
8126   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
8127                "                        double *min_x,\n"
8128                "                        double *max_x,\n"
8129                "                        double *min_y,\n"
8130                "                        double *max_y,\n"
8131                "                        double *min_z,\n"
8132                "                        double *max_z, ) {}",
8133                NoBinPacking);
8134 }
8135 
8136 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
8137   verifyFormat("void f() { return; }\n42");
8138   verifyFormat("void f() {\n"
8139                "  if (0)\n"
8140                "    return;\n"
8141                "}\n"
8142                "42");
8143   verifyFormat("void f() { return }\n42");
8144   verifyFormat("void f() {\n"
8145                "  if (0)\n"
8146                "    return\n"
8147                "}\n"
8148                "42");
8149 }
8150 
8151 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
8152   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
8153   EXPECT_EQ("void f() {\n"
8154             "  if (a)\n"
8155             "    return\n"
8156             "}",
8157             format("void  f  (  )  {  if  ( a )  return  }"));
8158   EXPECT_EQ("namespace N {\n"
8159             "void f()\n"
8160             "}",
8161             format("namespace  N  {  void f()  }"));
8162   EXPECT_EQ("namespace N {\n"
8163             "void f() {}\n"
8164             "void g()\n"
8165             "} // namespace N",
8166             format("namespace N  { void f( ) { } void g( ) }"));
8167 }
8168 
8169 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
8170   verifyFormat("int aaaaaaaa =\n"
8171                "    // Overlylongcomment\n"
8172                "    b;",
8173                getLLVMStyleWithColumns(20));
8174   verifyFormat("function(\n"
8175                "    ShortArgument,\n"
8176                "    LoooooooooooongArgument);\n",
8177                getLLVMStyleWithColumns(20));
8178 }
8179 
8180 TEST_F(FormatTest, IncorrectAccessSpecifier) {
8181   verifyFormat("public:");
8182   verifyFormat("class A {\n"
8183                "public\n"
8184                "  void f() {}\n"
8185                "};");
8186   verifyFormat("public\n"
8187                "int qwerty;");
8188   verifyFormat("public\n"
8189                "B {}");
8190   verifyFormat("public\n"
8191                "{}");
8192   verifyFormat("public\n"
8193                "B { int x; }");
8194 }
8195 
8196 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
8197   verifyFormat("{");
8198   verifyFormat("#})");
8199   verifyNoCrash("(/**/[:!] ?[).");
8200 }
8201 
8202 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
8203   // Found by oss-fuzz:
8204   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
8205   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
8206   Style.ColumnLimit = 60;
8207   verifyNoCrash(
8208       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
8209       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
8210       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
8211       Style);
8212 }
8213 
8214 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
8215   verifyFormat("do {\n}");
8216   verifyFormat("do {\n}\n"
8217                "f();");
8218   verifyFormat("do {\n}\n"
8219                "wheeee(fun);");
8220   verifyFormat("do {\n"
8221                "  f();\n"
8222                "}");
8223 }
8224 
8225 TEST_F(FormatTest, IncorrectCodeMissingParens) {
8226   verifyFormat("if {\n  foo;\n  foo();\n}");
8227   verifyFormat("switch {\n  foo;\n  foo();\n}");
8228   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
8229   verifyFormat("while {\n  foo;\n  foo();\n}");
8230   verifyFormat("do {\n  foo;\n  foo();\n} while;");
8231 }
8232 
8233 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
8234   verifyIncompleteFormat("namespace {\n"
8235                          "class Foo { Foo (\n"
8236                          "};\n"
8237                          "} // namespace");
8238 }
8239 
8240 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
8241   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
8242   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
8243   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
8244   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
8245 
8246   EXPECT_EQ("{\n"
8247             "  {\n"
8248             "    breakme(\n"
8249             "        qwe);\n"
8250             "  }\n",
8251             format("{\n"
8252                    "    {\n"
8253                    " breakme(qwe);\n"
8254                    "}\n",
8255                    getLLVMStyleWithColumns(10)));
8256 }
8257 
8258 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
8259   verifyFormat("int x = {\n"
8260                "    avariable,\n"
8261                "    b(alongervariable)};",
8262                getLLVMStyleWithColumns(25));
8263 }
8264 
8265 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
8266   verifyFormat("return (a)(b){1, 2, 3};");
8267 }
8268 
8269 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
8270   verifyFormat("vector<int> x{1, 2, 3, 4};");
8271   verifyFormat("vector<int> x{\n"
8272                "    1,\n"
8273                "    2,\n"
8274                "    3,\n"
8275                "    4,\n"
8276                "};");
8277   verifyFormat("vector<T> x{{}, {}, {}, {}};");
8278   verifyFormat("f({1, 2});");
8279   verifyFormat("auto v = Foo{-1};");
8280   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
8281   verifyFormat("Class::Class : member{1, 2, 3} {}");
8282   verifyFormat("new vector<int>{1, 2, 3};");
8283   verifyFormat("new int[3]{1, 2, 3};");
8284   verifyFormat("new int{1};");
8285   verifyFormat("return {arg1, arg2};");
8286   verifyFormat("return {arg1, SomeType{parameter}};");
8287   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
8288   verifyFormat("new T{arg1, arg2};");
8289   verifyFormat("f(MyMap[{composite, key}]);");
8290   verifyFormat("class Class {\n"
8291                "  T member = {arg1, arg2};\n"
8292                "};");
8293   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
8294   verifyFormat("const struct A a = {.a = 1, .b = 2};");
8295   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
8296   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
8297   verifyFormat("int a = std::is_integral<int>{} + 0;");
8298 
8299   verifyFormat("int foo(int i) { return fo1{}(i); }");
8300   verifyFormat("int foo(int i) { return fo1{}(i); }");
8301   verifyFormat("auto i = decltype(x){};");
8302   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
8303   verifyFormat("Node n{1, Node{1000}, //\n"
8304                "       2};");
8305   verifyFormat("Aaaa aaaaaaa{\n"
8306                "    {\n"
8307                "        aaaa,\n"
8308                "    },\n"
8309                "};");
8310   verifyFormat("class C : public D {\n"
8311                "  SomeClass SC{2};\n"
8312                "};");
8313   verifyFormat("class C : public A {\n"
8314                "  class D : public B {\n"
8315                "    void f() { int i{2}; }\n"
8316                "  };\n"
8317                "};");
8318   verifyFormat("#define A {a, a},");
8319 
8320   // Avoid breaking between equal sign and opening brace
8321   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
8322   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
8323   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
8324                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
8325                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
8326                "     {\"ccccccccccccccccccccc\", 2}};",
8327                AvoidBreakingFirstArgument);
8328 
8329   // Binpacking only if there is no trailing comma
8330   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
8331                "                      cccccccccc, dddddddddd};",
8332                getLLVMStyleWithColumns(50));
8333   verifyFormat("const Aaaaaa aaaaa = {\n"
8334                "    aaaaaaaaaaa,\n"
8335                "    bbbbbbbbbbb,\n"
8336                "    ccccccccccc,\n"
8337                "    ddddddddddd,\n"
8338                "};",
8339                getLLVMStyleWithColumns(50));
8340 
8341   // Cases where distinguising braced lists and blocks is hard.
8342   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
8343   verifyFormat("void f() {\n"
8344                "  return; // comment\n"
8345                "}\n"
8346                "SomeType t;");
8347   verifyFormat("void f() {\n"
8348                "  if (a) {\n"
8349                "    f();\n"
8350                "  }\n"
8351                "}\n"
8352                "SomeType t;");
8353 
8354   // In combination with BinPackArguments = false.
8355   FormatStyle NoBinPacking = getLLVMStyle();
8356   NoBinPacking.BinPackArguments = false;
8357   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
8358                "                      bbbbb,\n"
8359                "                      ccccc,\n"
8360                "                      ddddd,\n"
8361                "                      eeeee,\n"
8362                "                      ffffff,\n"
8363                "                      ggggg,\n"
8364                "                      hhhhhh,\n"
8365                "                      iiiiii,\n"
8366                "                      jjjjjj,\n"
8367                "                      kkkkkk};",
8368                NoBinPacking);
8369   verifyFormat("const Aaaaaa aaaaa = {\n"
8370                "    aaaaa,\n"
8371                "    bbbbb,\n"
8372                "    ccccc,\n"
8373                "    ddddd,\n"
8374                "    eeeee,\n"
8375                "    ffffff,\n"
8376                "    ggggg,\n"
8377                "    hhhhhh,\n"
8378                "    iiiiii,\n"
8379                "    jjjjjj,\n"
8380                "    kkkkkk,\n"
8381                "};",
8382                NoBinPacking);
8383   verifyFormat(
8384       "const Aaaaaa aaaaa = {\n"
8385       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
8386       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
8387       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
8388       "};",
8389       NoBinPacking);
8390 
8391   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
8392   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
8393             "    CDDDP83848_BMCR_REGISTER,\n"
8394             "    CDDDP83848_BMSR_REGISTER,\n"
8395             "    CDDDP83848_RBR_REGISTER};",
8396             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
8397                    "                                CDDDP83848_BMSR_REGISTER,\n"
8398                    "                                CDDDP83848_RBR_REGISTER};",
8399                    NoBinPacking));
8400 
8401   // FIXME: The alignment of these trailing comments might be bad. Then again,
8402   // this might be utterly useless in real code.
8403   verifyFormat("Constructor::Constructor()\n"
8404                "    : some_value{         //\n"
8405                "                 aaaaaaa, //\n"
8406                "                 bbbbbbb} {}");
8407 
8408   // In braced lists, the first comment is always assumed to belong to the
8409   // first element. Thus, it can be moved to the next or previous line as
8410   // appropriate.
8411   EXPECT_EQ("function({// First element:\n"
8412             "          1,\n"
8413             "          // Second element:\n"
8414             "          2});",
8415             format("function({\n"
8416                    "    // First element:\n"
8417                    "    1,\n"
8418                    "    // Second element:\n"
8419                    "    2});"));
8420   EXPECT_EQ("std::vector<int> MyNumbers{\n"
8421             "    // First element:\n"
8422             "    1,\n"
8423             "    // Second element:\n"
8424             "    2};",
8425             format("std::vector<int> MyNumbers{// First element:\n"
8426                    "                           1,\n"
8427                    "                           // Second element:\n"
8428                    "                           2};",
8429                    getLLVMStyleWithColumns(30)));
8430   // A trailing comma should still lead to an enforced line break and no
8431   // binpacking.
8432   EXPECT_EQ("vector<int> SomeVector = {\n"
8433             "    // aaa\n"
8434             "    1,\n"
8435             "    2,\n"
8436             "};",
8437             format("vector<int> SomeVector = { // aaa\n"
8438                    "    1, 2, };"));
8439 
8440   // C++11 brace initializer list l-braces should not be treated any differently
8441   // when breaking before lambda bodies is enabled
8442   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
8443   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
8444   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
8445   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
8446   verifyFormat(
8447       "std::runtime_error{\n"
8448       "    \"Long string which will force a break onto the next line...\"};",
8449       BreakBeforeLambdaBody);
8450 
8451   FormatStyle ExtraSpaces = getLLVMStyle();
8452   ExtraSpaces.Cpp11BracedListStyle = false;
8453   ExtraSpaces.ColumnLimit = 75;
8454   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
8455   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
8456   verifyFormat("f({ 1, 2 });", ExtraSpaces);
8457   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
8458   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
8459   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
8460   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
8461   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
8462   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
8463   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
8464   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
8465   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
8466   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
8467   verifyFormat("class Class {\n"
8468                "  T member = { arg1, arg2 };\n"
8469                "};",
8470                ExtraSpaces);
8471   verifyFormat(
8472       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8473       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
8474       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
8475       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
8476       ExtraSpaces);
8477   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
8478   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
8479                ExtraSpaces);
8480   verifyFormat(
8481       "someFunction(OtherParam,\n"
8482       "             BracedList{ // comment 1 (Forcing interesting break)\n"
8483       "                         param1, param2,\n"
8484       "                         // comment 2\n"
8485       "                         param3, param4 });",
8486       ExtraSpaces);
8487   verifyFormat(
8488       "std::this_thread::sleep_for(\n"
8489       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
8490       ExtraSpaces);
8491   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
8492                "    aaaaaaa,\n"
8493                "    aaaaaaaaaa,\n"
8494                "    aaaaa,\n"
8495                "    aaaaaaaaaaaaaaa,\n"
8496                "    aaa,\n"
8497                "    aaaaaaaaaa,\n"
8498                "    a,\n"
8499                "    aaaaaaaaaaaaaaaaaaaaa,\n"
8500                "    aaaaaaaaaaaa,\n"
8501                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
8502                "    aaaaaaa,\n"
8503                "    a};");
8504   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
8505   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
8506   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
8507 
8508   // Avoid breaking between initializer/equal sign and opening brace
8509   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
8510   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
8511                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
8512                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
8513                "  { \"ccccccccccccccccccccc\", 2 }\n"
8514                "};",
8515                ExtraSpaces);
8516   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
8517                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
8518                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
8519                "  { \"ccccccccccccccccccccc\", 2 }\n"
8520                "};",
8521                ExtraSpaces);
8522 
8523   FormatStyle SpaceBeforeBrace = getLLVMStyle();
8524   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
8525   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
8526   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
8527 
8528   FormatStyle SpaceBetweenBraces = getLLVMStyle();
8529   SpaceBetweenBraces.SpacesInAngles = true;
8530   SpaceBetweenBraces.SpacesInParentheses = true;
8531   SpaceBetweenBraces.SpacesInSquareBrackets = true;
8532   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
8533   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
8534   verifyFormat("vector< int > x{ // comment 1\n"
8535                "                 1, 2, 3, 4 };",
8536                SpaceBetweenBraces);
8537   SpaceBetweenBraces.ColumnLimit = 20;
8538   EXPECT_EQ("vector< int > x{\n"
8539             "    1, 2, 3, 4 };",
8540             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
8541   SpaceBetweenBraces.ColumnLimit = 24;
8542   EXPECT_EQ("vector< int > x{ 1, 2,\n"
8543             "                 3, 4 };",
8544             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
8545   EXPECT_EQ("vector< int > x{\n"
8546             "    1,\n"
8547             "    2,\n"
8548             "    3,\n"
8549             "    4,\n"
8550             "};",
8551             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
8552   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
8553   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
8554   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
8555 }
8556 
8557 TEST_F(FormatTest, FormatSpacesInAngles) {
8558   FormatStyle SpaceInAngles = getLLVMStyle();
8559   SpaceInAngles.SpacesInAngles = true;
8560   verifyFormat("vector< ::std::string > x1;", SpaceInAngles);
8561   verifyFormat("Foo< int, Bar > x2;", SpaceInAngles);
8562   verifyFormat("Foo< ::int, ::Bar > x3;", SpaceInAngles);
8563 
8564   SpaceInAngles.SpacesInAngles = false;
8565   verifyFormat("vector<::std::string> x4;", SpaceInAngles);
8566   verifyFormat("vector<int> x5;", SpaceInAngles);
8567   verifyFormat("Foo<int, Bar> x6;", SpaceInAngles);
8568   verifyFormat("Foo<::int, ::Bar> x7;", SpaceInAngles);
8569 }
8570 
8571 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
8572   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8573                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8574                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8575                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8576                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8577                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
8578   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
8579                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8580                "                 1, 22, 333, 4444, 55555, //\n"
8581                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8582                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
8583   verifyFormat(
8584       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
8585       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
8586       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
8587       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
8588       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
8589       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
8590       "                 7777777};");
8591   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
8592                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
8593                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
8594   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
8595                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
8596                "    // Separating comment.\n"
8597                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
8598   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
8599                "    // Leading comment\n"
8600                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
8601                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
8602   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
8603                "                 1, 1, 1, 1};",
8604                getLLVMStyleWithColumns(39));
8605   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
8606                "                 1, 1, 1, 1};",
8607                getLLVMStyleWithColumns(38));
8608   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
8609                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
8610                getLLVMStyleWithColumns(43));
8611   verifyFormat(
8612       "static unsigned SomeValues[10][3] = {\n"
8613       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
8614       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
8615   verifyFormat("static auto fields = new vector<string>{\n"
8616                "    \"aaaaaaaaaaaaa\",\n"
8617                "    \"aaaaaaaaaaaaa\",\n"
8618                "    \"aaaaaaaaaaaa\",\n"
8619                "    \"aaaaaaaaaaaaaa\",\n"
8620                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
8621                "    \"aaaaaaaaaaaa\",\n"
8622                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
8623                "};");
8624   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
8625   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
8626                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
8627                "                 3, cccccccccccccccccccccc};",
8628                getLLVMStyleWithColumns(60));
8629 
8630   // Trailing commas.
8631   verifyFormat("vector<int> x = {\n"
8632                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
8633                "};",
8634                getLLVMStyleWithColumns(39));
8635   verifyFormat("vector<int> x = {\n"
8636                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
8637                "};",
8638                getLLVMStyleWithColumns(39));
8639   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
8640                "                 1, 1, 1, 1,\n"
8641                "                 /**/ /**/};",
8642                getLLVMStyleWithColumns(39));
8643 
8644   // Trailing comment in the first line.
8645   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
8646                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
8647                "    111111111,  222222222,  3333333333,  444444444,  //\n"
8648                "    11111111,   22222222,   333333333,   44444444};");
8649   // Trailing comment in the last line.
8650   verifyFormat("int aaaaa[] = {\n"
8651                "    1, 2, 3, // comment\n"
8652                "    4, 5, 6  // comment\n"
8653                "};");
8654 
8655   // With nested lists, we should either format one item per line or all nested
8656   // lists one on line.
8657   // FIXME: For some nested lists, we can do better.
8658   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
8659                "        {aaaaaaaaaaaaaaaaaaa},\n"
8660                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
8661                "        {aaaaaaaaaaaaaaaaa}};",
8662                getLLVMStyleWithColumns(60));
8663   verifyFormat(
8664       "SomeStruct my_struct_array = {\n"
8665       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
8666       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
8667       "    {aaa, aaa},\n"
8668       "    {aaa, aaa},\n"
8669       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
8670       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
8671       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
8672 
8673   // No column layout should be used here.
8674   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
8675                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
8676 
8677   verifyNoCrash("a<,");
8678 
8679   // No braced initializer here.
8680   verifyFormat("void f() {\n"
8681                "  struct Dummy {};\n"
8682                "  f(v);\n"
8683                "}");
8684 
8685   // Long lists should be formatted in columns even if they are nested.
8686   verifyFormat(
8687       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8688       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8689       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8690       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8691       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
8692       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
8693 
8694   // Allow "single-column" layout even if that violates the column limit. There
8695   // isn't going to be a better way.
8696   verifyFormat("std::vector<int> a = {\n"
8697                "    aaaaaaaa,\n"
8698                "    aaaaaaaa,\n"
8699                "    aaaaaaaa,\n"
8700                "    aaaaaaaa,\n"
8701                "    aaaaaaaaaa,\n"
8702                "    aaaaaaaa,\n"
8703                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
8704                getLLVMStyleWithColumns(30));
8705   verifyFormat("vector<int> aaaa = {\n"
8706                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8707                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8708                "    aaaaaa.aaaaaaa,\n"
8709                "    aaaaaa.aaaaaaa,\n"
8710                "    aaaaaa.aaaaaaa,\n"
8711                "    aaaaaa.aaaaaaa,\n"
8712                "};");
8713 
8714   // Don't create hanging lists.
8715   verifyFormat("someFunction(Param, {List1, List2,\n"
8716                "                     List3});",
8717                getLLVMStyleWithColumns(35));
8718   verifyFormat("someFunction(Param, Param,\n"
8719                "             {List1, List2,\n"
8720                "              List3});",
8721                getLLVMStyleWithColumns(35));
8722   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
8723                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
8724 }
8725 
8726 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
8727   FormatStyle DoNotMerge = getLLVMStyle();
8728   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8729 
8730   verifyFormat("void f() { return 42; }");
8731   verifyFormat("void f() {\n"
8732                "  return 42;\n"
8733                "}",
8734                DoNotMerge);
8735   verifyFormat("void f() {\n"
8736                "  // Comment\n"
8737                "}");
8738   verifyFormat("{\n"
8739                "#error {\n"
8740                "  int a;\n"
8741                "}");
8742   verifyFormat("{\n"
8743                "  int a;\n"
8744                "#error {\n"
8745                "}");
8746   verifyFormat("void f() {} // comment");
8747   verifyFormat("void f() { int a; } // comment");
8748   verifyFormat("void f() {\n"
8749                "} // comment",
8750                DoNotMerge);
8751   verifyFormat("void f() {\n"
8752                "  int a;\n"
8753                "} // comment",
8754                DoNotMerge);
8755   verifyFormat("void f() {\n"
8756                "} // comment",
8757                getLLVMStyleWithColumns(15));
8758 
8759   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
8760   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
8761 
8762   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
8763   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
8764   verifyFormat("class C {\n"
8765                "  C()\n"
8766                "      : iiiiiiii(nullptr),\n"
8767                "        kkkkkkk(nullptr),\n"
8768                "        mmmmmmm(nullptr),\n"
8769                "        nnnnnnn(nullptr) {}\n"
8770                "};",
8771                getGoogleStyle());
8772 
8773   FormatStyle NoColumnLimit = getLLVMStyle();
8774   NoColumnLimit.ColumnLimit = 0;
8775   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
8776   EXPECT_EQ("class C {\n"
8777             "  A() : b(0) {}\n"
8778             "};",
8779             format("class C{A():b(0){}};", NoColumnLimit));
8780   EXPECT_EQ("A()\n"
8781             "    : b(0) {\n"
8782             "}",
8783             format("A()\n:b(0)\n{\n}", NoColumnLimit));
8784 
8785   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
8786   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
8787       FormatStyle::SFS_None;
8788   EXPECT_EQ("A()\n"
8789             "    : b(0) {\n"
8790             "}",
8791             format("A():b(0){}", DoNotMergeNoColumnLimit));
8792   EXPECT_EQ("A()\n"
8793             "    : b(0) {\n"
8794             "}",
8795             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
8796 
8797   verifyFormat("#define A          \\\n"
8798                "  void f() {       \\\n"
8799                "    int i;         \\\n"
8800                "  }",
8801                getLLVMStyleWithColumns(20));
8802   verifyFormat("#define A           \\\n"
8803                "  void f() { int i; }",
8804                getLLVMStyleWithColumns(21));
8805   verifyFormat("#define A            \\\n"
8806                "  void f() {         \\\n"
8807                "    int i;           \\\n"
8808                "  }                  \\\n"
8809                "  int j;",
8810                getLLVMStyleWithColumns(22));
8811   verifyFormat("#define A             \\\n"
8812                "  void f() { int i; } \\\n"
8813                "  int j;",
8814                getLLVMStyleWithColumns(23));
8815 }
8816 
8817 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
8818   FormatStyle MergeEmptyOnly = getLLVMStyle();
8819   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
8820   verifyFormat("class C {\n"
8821                "  int f() {}\n"
8822                "};",
8823                MergeEmptyOnly);
8824   verifyFormat("class C {\n"
8825                "  int f() {\n"
8826                "    return 42;\n"
8827                "  }\n"
8828                "};",
8829                MergeEmptyOnly);
8830   verifyFormat("int f() {}", MergeEmptyOnly);
8831   verifyFormat("int f() {\n"
8832                "  return 42;\n"
8833                "}",
8834                MergeEmptyOnly);
8835 
8836   // Also verify behavior when BraceWrapping.AfterFunction = true
8837   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
8838   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
8839   verifyFormat("int f() {}", MergeEmptyOnly);
8840   verifyFormat("class C {\n"
8841                "  int f() {}\n"
8842                "};",
8843                MergeEmptyOnly);
8844 }
8845 
8846 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
8847   FormatStyle MergeInlineOnly = getLLVMStyle();
8848   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
8849   verifyFormat("class C {\n"
8850                "  int f() { return 42; }\n"
8851                "};",
8852                MergeInlineOnly);
8853   verifyFormat("int f() {\n"
8854                "  return 42;\n"
8855                "}",
8856                MergeInlineOnly);
8857 
8858   // SFS_Inline implies SFS_Empty
8859   verifyFormat("class C {\n"
8860                "  int f() {}\n"
8861                "};",
8862                MergeInlineOnly);
8863   verifyFormat("int f() {}", MergeInlineOnly);
8864 
8865   // Also verify behavior when BraceWrapping.AfterFunction = true
8866   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
8867   MergeInlineOnly.BraceWrapping.AfterFunction = true;
8868   verifyFormat("class C {\n"
8869                "  int f() { return 42; }\n"
8870                "};",
8871                MergeInlineOnly);
8872   verifyFormat("int f()\n"
8873                "{\n"
8874                "  return 42;\n"
8875                "}",
8876                MergeInlineOnly);
8877 
8878   // SFS_Inline implies SFS_Empty
8879   verifyFormat("int f() {}", MergeInlineOnly);
8880   verifyFormat("class C {\n"
8881                "  int f() {}\n"
8882                "};",
8883                MergeInlineOnly);
8884 }
8885 
8886 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
8887   FormatStyle MergeInlineOnly = getLLVMStyle();
8888   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
8889       FormatStyle::SFS_InlineOnly;
8890   verifyFormat("class C {\n"
8891                "  int f() { return 42; }\n"
8892                "};",
8893                MergeInlineOnly);
8894   verifyFormat("int f() {\n"
8895                "  return 42;\n"
8896                "}",
8897                MergeInlineOnly);
8898 
8899   // SFS_InlineOnly does not imply SFS_Empty
8900   verifyFormat("class C {\n"
8901                "  int f() {}\n"
8902                "};",
8903                MergeInlineOnly);
8904   verifyFormat("int f() {\n"
8905                "}",
8906                MergeInlineOnly);
8907 
8908   // Also verify behavior when BraceWrapping.AfterFunction = true
8909   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
8910   MergeInlineOnly.BraceWrapping.AfterFunction = true;
8911   verifyFormat("class C {\n"
8912                "  int f() { return 42; }\n"
8913                "};",
8914                MergeInlineOnly);
8915   verifyFormat("int f()\n"
8916                "{\n"
8917                "  return 42;\n"
8918                "}",
8919                MergeInlineOnly);
8920 
8921   // SFS_InlineOnly does not imply SFS_Empty
8922   verifyFormat("int f()\n"
8923                "{\n"
8924                "}",
8925                MergeInlineOnly);
8926   verifyFormat("class C {\n"
8927                "  int f() {}\n"
8928                "};",
8929                MergeInlineOnly);
8930 }
8931 
8932 TEST_F(FormatTest, SplitEmptyFunction) {
8933   FormatStyle Style = getLLVMStyle();
8934   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8935   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
8936   Style.BraceWrapping.AfterFunction = true;
8937   Style.BraceWrapping.SplitEmptyFunction = false;
8938   Style.ColumnLimit = 40;
8939 
8940   verifyFormat("int f()\n"
8941                "{}",
8942                Style);
8943   verifyFormat("int f()\n"
8944                "{\n"
8945                "  return 42;\n"
8946                "}",
8947                Style);
8948   verifyFormat("int f()\n"
8949                "{\n"
8950                "  // some comment\n"
8951                "}",
8952                Style);
8953 
8954   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
8955   verifyFormat("int f() {}", Style);
8956   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
8957                "{}",
8958                Style);
8959   verifyFormat("int f()\n"
8960                "{\n"
8961                "  return 0;\n"
8962                "}",
8963                Style);
8964 
8965   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
8966   verifyFormat("class Foo {\n"
8967                "  int f() {}\n"
8968                "};\n",
8969                Style);
8970   verifyFormat("class Foo {\n"
8971                "  int f() { return 0; }\n"
8972                "};\n",
8973                Style);
8974   verifyFormat("class Foo {\n"
8975                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
8976                "  {}\n"
8977                "};\n",
8978                Style);
8979   verifyFormat("class Foo {\n"
8980                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
8981                "  {\n"
8982                "    return 0;\n"
8983                "  }\n"
8984                "};\n",
8985                Style);
8986 
8987   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
8988   verifyFormat("int f() {}", Style);
8989   verifyFormat("int f() { return 0; }", Style);
8990   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
8991                "{}",
8992                Style);
8993   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
8994                "{\n"
8995                "  return 0;\n"
8996                "}",
8997                Style);
8998 }
8999 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
9000   FormatStyle Style = getLLVMStyle();
9001   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
9002   verifyFormat("#ifdef A\n"
9003                "int f() {}\n"
9004                "#else\n"
9005                "int g() {}\n"
9006                "#endif",
9007                Style);
9008 }
9009 
9010 TEST_F(FormatTest, SplitEmptyClass) {
9011   FormatStyle Style = getLLVMStyle();
9012   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9013   Style.BraceWrapping.AfterClass = true;
9014   Style.BraceWrapping.SplitEmptyRecord = false;
9015 
9016   verifyFormat("class Foo\n"
9017                "{};",
9018                Style);
9019   verifyFormat("/* something */ class Foo\n"
9020                "{};",
9021                Style);
9022   verifyFormat("template <typename X> class Foo\n"
9023                "{};",
9024                Style);
9025   verifyFormat("class Foo\n"
9026                "{\n"
9027                "  Foo();\n"
9028                "};",
9029                Style);
9030   verifyFormat("typedef class Foo\n"
9031                "{\n"
9032                "} Foo_t;",
9033                Style);
9034 }
9035 
9036 TEST_F(FormatTest, SplitEmptyStruct) {
9037   FormatStyle Style = getLLVMStyle();
9038   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9039   Style.BraceWrapping.AfterStruct = true;
9040   Style.BraceWrapping.SplitEmptyRecord = false;
9041 
9042   verifyFormat("struct Foo\n"
9043                "{};",
9044                Style);
9045   verifyFormat("/* something */ struct Foo\n"
9046                "{};",
9047                Style);
9048   verifyFormat("template <typename X> struct Foo\n"
9049                "{};",
9050                Style);
9051   verifyFormat("struct Foo\n"
9052                "{\n"
9053                "  Foo();\n"
9054                "};",
9055                Style);
9056   verifyFormat("typedef struct Foo\n"
9057                "{\n"
9058                "} Foo_t;",
9059                Style);
9060   // typedef struct Bar {} Bar_t;
9061 }
9062 
9063 TEST_F(FormatTest, SplitEmptyUnion) {
9064   FormatStyle Style = getLLVMStyle();
9065   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9066   Style.BraceWrapping.AfterUnion = true;
9067   Style.BraceWrapping.SplitEmptyRecord = false;
9068 
9069   verifyFormat("union Foo\n"
9070                "{};",
9071                Style);
9072   verifyFormat("/* something */ union Foo\n"
9073                "{};",
9074                Style);
9075   verifyFormat("union Foo\n"
9076                "{\n"
9077                "  A,\n"
9078                "};",
9079                Style);
9080   verifyFormat("typedef union Foo\n"
9081                "{\n"
9082                "} Foo_t;",
9083                Style);
9084 }
9085 
9086 TEST_F(FormatTest, SplitEmptyNamespace) {
9087   FormatStyle Style = getLLVMStyle();
9088   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9089   Style.BraceWrapping.AfterNamespace = true;
9090   Style.BraceWrapping.SplitEmptyNamespace = false;
9091 
9092   verifyFormat("namespace Foo\n"
9093                "{};",
9094                Style);
9095   verifyFormat("/* something */ namespace Foo\n"
9096                "{};",
9097                Style);
9098   verifyFormat("inline namespace Foo\n"
9099                "{};",
9100                Style);
9101   verifyFormat("/* something */ inline namespace Foo\n"
9102                "{};",
9103                Style);
9104   verifyFormat("export namespace Foo\n"
9105                "{};",
9106                Style);
9107   verifyFormat("namespace Foo\n"
9108                "{\n"
9109                "void Bar();\n"
9110                "};",
9111                Style);
9112 }
9113 
9114 TEST_F(FormatTest, NeverMergeShortRecords) {
9115   FormatStyle Style = getLLVMStyle();
9116 
9117   verifyFormat("class Foo {\n"
9118                "  Foo();\n"
9119                "};",
9120                Style);
9121   verifyFormat("typedef class Foo {\n"
9122                "  Foo();\n"
9123                "} Foo_t;",
9124                Style);
9125   verifyFormat("struct Foo {\n"
9126                "  Foo();\n"
9127                "};",
9128                Style);
9129   verifyFormat("typedef struct Foo {\n"
9130                "  Foo();\n"
9131                "} Foo_t;",
9132                Style);
9133   verifyFormat("union Foo {\n"
9134                "  A,\n"
9135                "};",
9136                Style);
9137   verifyFormat("typedef union Foo {\n"
9138                "  A,\n"
9139                "} Foo_t;",
9140                Style);
9141   verifyFormat("namespace Foo {\n"
9142                "void Bar();\n"
9143                "};",
9144                Style);
9145 
9146   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
9147   Style.BraceWrapping.AfterClass = true;
9148   Style.BraceWrapping.AfterStruct = true;
9149   Style.BraceWrapping.AfterUnion = true;
9150   Style.BraceWrapping.AfterNamespace = true;
9151   verifyFormat("class Foo\n"
9152                "{\n"
9153                "  Foo();\n"
9154                "};",
9155                Style);
9156   verifyFormat("typedef class Foo\n"
9157                "{\n"
9158                "  Foo();\n"
9159                "} Foo_t;",
9160                Style);
9161   verifyFormat("struct Foo\n"
9162                "{\n"
9163                "  Foo();\n"
9164                "};",
9165                Style);
9166   verifyFormat("typedef struct Foo\n"
9167                "{\n"
9168                "  Foo();\n"
9169                "} Foo_t;",
9170                Style);
9171   verifyFormat("union Foo\n"
9172                "{\n"
9173                "  A,\n"
9174                "};",
9175                Style);
9176   verifyFormat("typedef union Foo\n"
9177                "{\n"
9178                "  A,\n"
9179                "} Foo_t;",
9180                Style);
9181   verifyFormat("namespace Foo\n"
9182                "{\n"
9183                "void Bar();\n"
9184                "};",
9185                Style);
9186 }
9187 
9188 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
9189   // Elaborate type variable declarations.
9190   verifyFormat("struct foo a = {bar};\nint n;");
9191   verifyFormat("class foo a = {bar};\nint n;");
9192   verifyFormat("union foo a = {bar};\nint n;");
9193 
9194   // Elaborate types inside function definitions.
9195   verifyFormat("struct foo f() {}\nint n;");
9196   verifyFormat("class foo f() {}\nint n;");
9197   verifyFormat("union foo f() {}\nint n;");
9198 
9199   // Templates.
9200   verifyFormat("template <class X> void f() {}\nint n;");
9201   verifyFormat("template <struct X> void f() {}\nint n;");
9202   verifyFormat("template <union X> void f() {}\nint n;");
9203 
9204   // Actual definitions...
9205   verifyFormat("struct {\n} n;");
9206   verifyFormat(
9207       "template <template <class T, class Y>, class Z> class X {\n} n;");
9208   verifyFormat("union Z {\n  int n;\n} x;");
9209   verifyFormat("class MACRO Z {\n} n;");
9210   verifyFormat("class MACRO(X) Z {\n} n;");
9211   verifyFormat("class __attribute__(X) Z {\n} n;");
9212   verifyFormat("class __declspec(X) Z {\n} n;");
9213   verifyFormat("class A##B##C {\n} n;");
9214   verifyFormat("class alignas(16) Z {\n} n;");
9215   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
9216   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
9217 
9218   // Redefinition from nested context:
9219   verifyFormat("class A::B::C {\n} n;");
9220 
9221   // Template definitions.
9222   verifyFormat(
9223       "template <typename F>\n"
9224       "Matcher(const Matcher<F> &Other,\n"
9225       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
9226       "                             !is_same<F, T>::value>::type * = 0)\n"
9227       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
9228 
9229   // FIXME: This is still incorrectly handled at the formatter side.
9230   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
9231   verifyFormat("int i = SomeFunction(a<b, a> b);");
9232 
9233   // FIXME:
9234   // This now gets parsed incorrectly as class definition.
9235   // verifyFormat("class A<int> f() {\n}\nint n;");
9236 
9237   // Elaborate types where incorrectly parsing the structural element would
9238   // break the indent.
9239   verifyFormat("if (true)\n"
9240                "  class X x;\n"
9241                "else\n"
9242                "  f();\n");
9243 
9244   // This is simply incomplete. Formatting is not important, but must not crash.
9245   verifyFormat("class A:");
9246 }
9247 
9248 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
9249   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
9250             format("#error Leave     all         white!!!!! space* alone!\n"));
9251   EXPECT_EQ(
9252       "#warning Leave     all         white!!!!! space* alone!\n",
9253       format("#warning Leave     all         white!!!!! space* alone!\n"));
9254   EXPECT_EQ("#error 1", format("  #  error   1"));
9255   EXPECT_EQ("#warning 1", format("  #  warning 1"));
9256 }
9257 
9258 TEST_F(FormatTest, FormatHashIfExpressions) {
9259   verifyFormat("#if AAAA && BBBB");
9260   verifyFormat("#if (AAAA && BBBB)");
9261   verifyFormat("#elif (AAAA && BBBB)");
9262   // FIXME: Come up with a better indentation for #elif.
9263   verifyFormat(
9264       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
9265       "    defined(BBBBBBBB)\n"
9266       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
9267       "    defined(BBBBBBBB)\n"
9268       "#endif",
9269       getLLVMStyleWithColumns(65));
9270 }
9271 
9272 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
9273   FormatStyle AllowsMergedIf = getGoogleStyle();
9274   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
9275       FormatStyle::SIS_WithoutElse;
9276   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
9277   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
9278   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
9279   EXPECT_EQ("if (true) return 42;",
9280             format("if (true)\nreturn 42;", AllowsMergedIf));
9281   FormatStyle ShortMergedIf = AllowsMergedIf;
9282   ShortMergedIf.ColumnLimit = 25;
9283   verifyFormat("#define A \\\n"
9284                "  if (true) return 42;",
9285                ShortMergedIf);
9286   verifyFormat("#define A \\\n"
9287                "  f();    \\\n"
9288                "  if (true)\n"
9289                "#define B",
9290                ShortMergedIf);
9291   verifyFormat("#define A \\\n"
9292                "  f();    \\\n"
9293                "  if (true)\n"
9294                "g();",
9295                ShortMergedIf);
9296   verifyFormat("{\n"
9297                "#ifdef A\n"
9298                "  // Comment\n"
9299                "  if (true) continue;\n"
9300                "#endif\n"
9301                "  // Comment\n"
9302                "  if (true) continue;\n"
9303                "}",
9304                ShortMergedIf);
9305   ShortMergedIf.ColumnLimit = 33;
9306   verifyFormat("#define A \\\n"
9307                "  if constexpr (true) return 42;",
9308                ShortMergedIf);
9309   verifyFormat("#define A \\\n"
9310                "  if CONSTEXPR (true) return 42;",
9311                ShortMergedIf);
9312   ShortMergedIf.ColumnLimit = 29;
9313   verifyFormat("#define A                   \\\n"
9314                "  if (aaaaaaaaaa) return 1; \\\n"
9315                "  return 2;",
9316                ShortMergedIf);
9317   ShortMergedIf.ColumnLimit = 28;
9318   verifyFormat("#define A         \\\n"
9319                "  if (aaaaaaaaaa) \\\n"
9320                "    return 1;     \\\n"
9321                "  return 2;",
9322                ShortMergedIf);
9323   verifyFormat("#define A                \\\n"
9324                "  if constexpr (aaaaaaa) \\\n"
9325                "    return 1;            \\\n"
9326                "  return 2;",
9327                ShortMergedIf);
9328   verifyFormat("#define A                \\\n"
9329                "  if CONSTEXPR (aaaaaaa) \\\n"
9330                "    return 1;            \\\n"
9331                "  return 2;",
9332                ShortMergedIf);
9333 }
9334 
9335 TEST_F(FormatTest, FormatStarDependingOnContext) {
9336   verifyFormat("void f(int *a);");
9337   verifyFormat("void f() { f(fint * b); }");
9338   verifyFormat("class A {\n  void f(int *a);\n};");
9339   verifyFormat("class A {\n  int *a;\n};");
9340   verifyFormat("namespace a {\n"
9341                "namespace b {\n"
9342                "class A {\n"
9343                "  void f() {}\n"
9344                "  int *a;\n"
9345                "};\n"
9346                "} // namespace b\n"
9347                "} // namespace a");
9348 }
9349 
9350 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
9351   verifyFormat("while");
9352   verifyFormat("operator");
9353 }
9354 
9355 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
9356   // This code would be painfully slow to format if we didn't skip it.
9357   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
9358                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
9359                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
9360                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
9361                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
9362                    "A(1, 1)\n"
9363                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
9364                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9365                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9366                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9367                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9368                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9369                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9370                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9371                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
9372                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
9373   // Deeply nested part is untouched, rest is formatted.
9374   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
9375             format(std::string("int    i;\n") + Code + "int    j;\n",
9376                    getLLVMStyle(), SC_ExpectIncomplete));
9377 }
9378 
9379 //===----------------------------------------------------------------------===//
9380 // Objective-C tests.
9381 //===----------------------------------------------------------------------===//
9382 
9383 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
9384   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
9385   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
9386             format("-(NSUInteger)indexOfObject:(id)anObject;"));
9387   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
9388   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
9389   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
9390             format("-(NSInteger)Method3:(id)anObject;"));
9391   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
9392             format("-(NSInteger)Method4:(id)anObject;"));
9393   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
9394             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
9395   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
9396             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
9397   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
9398             "forAllCells:(BOOL)flag;",
9399             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
9400                    "forAllCells:(BOOL)flag;"));
9401 
9402   // Very long objectiveC method declaration.
9403   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
9404                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
9405   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
9406                "                    inRange:(NSRange)range\n"
9407                "                   outRange:(NSRange)out_range\n"
9408                "                  outRange1:(NSRange)out_range1\n"
9409                "                  outRange2:(NSRange)out_range2\n"
9410                "                  outRange3:(NSRange)out_range3\n"
9411                "                  outRange4:(NSRange)out_range4\n"
9412                "                  outRange5:(NSRange)out_range5\n"
9413                "                  outRange6:(NSRange)out_range6\n"
9414                "                  outRange7:(NSRange)out_range7\n"
9415                "                  outRange8:(NSRange)out_range8\n"
9416                "                  outRange9:(NSRange)out_range9;");
9417 
9418   // When the function name has to be wrapped.
9419   FormatStyle Style = getLLVMStyle();
9420   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
9421   // and always indents instead.
9422   Style.IndentWrappedFunctionNames = false;
9423   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
9424                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
9425                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
9426                "}",
9427                Style);
9428   Style.IndentWrappedFunctionNames = true;
9429   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
9430                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
9431                "               anotherName:(NSString)dddddddddddddd {\n"
9432                "}",
9433                Style);
9434 
9435   verifyFormat("- (int)sum:(vector<int>)numbers;");
9436   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
9437   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
9438   // protocol lists (but not for template classes):
9439   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
9440 
9441   verifyFormat("- (int (*)())foo:(int (*)())f;");
9442   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
9443 
9444   // If there's no return type (very rare in practice!), LLVM and Google style
9445   // agree.
9446   verifyFormat("- foo;");
9447   verifyFormat("- foo:(int)f;");
9448   verifyGoogleFormat("- foo:(int)foo;");
9449 }
9450 
9451 TEST_F(FormatTest, BreaksStringLiterals) {
9452   EXPECT_EQ("\"some text \"\n"
9453             "\"other\";",
9454             format("\"some text other\";", getLLVMStyleWithColumns(12)));
9455   EXPECT_EQ("\"some text \"\n"
9456             "\"other\";",
9457             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
9458   EXPECT_EQ(
9459       "#define A  \\\n"
9460       "  \"some \"  \\\n"
9461       "  \"text \"  \\\n"
9462       "  \"other\";",
9463       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
9464   EXPECT_EQ(
9465       "#define A  \\\n"
9466       "  \"so \"    \\\n"
9467       "  \"text \"  \\\n"
9468       "  \"other\";",
9469       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
9470 
9471   EXPECT_EQ("\"some text\"",
9472             format("\"some text\"", getLLVMStyleWithColumns(1)));
9473   EXPECT_EQ("\"some text\"",
9474             format("\"some text\"", getLLVMStyleWithColumns(11)));
9475   EXPECT_EQ("\"some \"\n"
9476             "\"text\"",
9477             format("\"some text\"", getLLVMStyleWithColumns(10)));
9478   EXPECT_EQ("\"some \"\n"
9479             "\"text\"",
9480             format("\"some text\"", getLLVMStyleWithColumns(7)));
9481   EXPECT_EQ("\"some\"\n"
9482             "\" tex\"\n"
9483             "\"t\"",
9484             format("\"some text\"", getLLVMStyleWithColumns(6)));
9485   EXPECT_EQ("\"some\"\n"
9486             "\" tex\"\n"
9487             "\" and\"",
9488             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
9489   EXPECT_EQ("\"some\"\n"
9490             "\"/tex\"\n"
9491             "\"/and\"",
9492             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
9493 
9494   EXPECT_EQ("variable =\n"
9495             "    \"long string \"\n"
9496             "    \"literal\";",
9497             format("variable = \"long string literal\";",
9498                    getLLVMStyleWithColumns(20)));
9499 
9500   EXPECT_EQ("variable = f(\n"
9501             "    \"long string \"\n"
9502             "    \"literal\",\n"
9503             "    short,\n"
9504             "    loooooooooooooooooooong);",
9505             format("variable = f(\"long string literal\", short, "
9506                    "loooooooooooooooooooong);",
9507                    getLLVMStyleWithColumns(20)));
9508 
9509   EXPECT_EQ(
9510       "f(g(\"long string \"\n"
9511       "    \"literal\"),\n"
9512       "  b);",
9513       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
9514   EXPECT_EQ("f(g(\"long string \"\n"
9515             "    \"literal\",\n"
9516             "    a),\n"
9517             "  b);",
9518             format("f(g(\"long string literal\", a), b);",
9519                    getLLVMStyleWithColumns(20)));
9520   EXPECT_EQ(
9521       "f(\"one two\".split(\n"
9522       "    variable));",
9523       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
9524   EXPECT_EQ("f(\"one two three four five six \"\n"
9525             "  \"seven\".split(\n"
9526             "      really_looooong_variable));",
9527             format("f(\"one two three four five six seven\"."
9528                    "split(really_looooong_variable));",
9529                    getLLVMStyleWithColumns(33)));
9530 
9531   EXPECT_EQ("f(\"some \"\n"
9532             "  \"text\",\n"
9533             "  other);",
9534             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
9535 
9536   // Only break as a last resort.
9537   verifyFormat(
9538       "aaaaaaaaaaaaaaaaaaaa(\n"
9539       "    aaaaaaaaaaaaaaaaaaaa,\n"
9540       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
9541 
9542   EXPECT_EQ("\"splitmea\"\n"
9543             "\"trandomp\"\n"
9544             "\"oint\"",
9545             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
9546 
9547   EXPECT_EQ("\"split/\"\n"
9548             "\"pathat/\"\n"
9549             "\"slashes\"",
9550             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
9551 
9552   EXPECT_EQ("\"split/\"\n"
9553             "\"pathat/\"\n"
9554             "\"slashes\"",
9555             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
9556   EXPECT_EQ("\"split at \"\n"
9557             "\"spaces/at/\"\n"
9558             "\"slashes.at.any$\"\n"
9559             "\"non-alphanumeric%\"\n"
9560             "\"1111111111characte\"\n"
9561             "\"rs\"",
9562             format("\"split at "
9563                    "spaces/at/"
9564                    "slashes.at."
9565                    "any$non-"
9566                    "alphanumeric%"
9567                    "1111111111characte"
9568                    "rs\"",
9569                    getLLVMStyleWithColumns(20)));
9570 
9571   // Verify that splitting the strings understands
9572   // Style::AlwaysBreakBeforeMultilineStrings.
9573   EXPECT_EQ("aaaaaaaaaaaa(\n"
9574             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
9575             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
9576             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
9577                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
9578                    "aaaaaaaaaaaaaaaaaaaaaa\");",
9579                    getGoogleStyle()));
9580   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
9581             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
9582             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
9583                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
9584                    "aaaaaaaaaaaaaaaaaaaaaa\";",
9585                    getGoogleStyle()));
9586   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
9587             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
9588             format("llvm::outs() << "
9589                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
9590                    "aaaaaaaaaaaaaaaaaaa\";"));
9591   EXPECT_EQ("ffff(\n"
9592             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
9593             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
9594             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
9595                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
9596                    getGoogleStyle()));
9597 
9598   FormatStyle Style = getLLVMStyleWithColumns(12);
9599   Style.BreakStringLiterals = false;
9600   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
9601 
9602   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
9603   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
9604   EXPECT_EQ("#define A \\\n"
9605             "  \"some \" \\\n"
9606             "  \"text \" \\\n"
9607             "  \"other\";",
9608             format("#define A \"some text other\";", AlignLeft));
9609 }
9610 
9611 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
9612   EXPECT_EQ("C a = \"some more \"\n"
9613             "      \"text\";",
9614             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
9615 }
9616 
9617 TEST_F(FormatTest, FullyRemoveEmptyLines) {
9618   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
9619   NoEmptyLines.MaxEmptyLinesToKeep = 0;
9620   EXPECT_EQ("int i = a(b());",
9621             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
9622 }
9623 
9624 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
9625   EXPECT_EQ(
9626       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
9627       "(\n"
9628       "    \"x\t\");",
9629       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
9630              "aaaaaaa("
9631              "\"x\t\");"));
9632 }
9633 
9634 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
9635   EXPECT_EQ(
9636       "u8\"utf8 string \"\n"
9637       "u8\"literal\";",
9638       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
9639   EXPECT_EQ(
9640       "u\"utf16 string \"\n"
9641       "u\"literal\";",
9642       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
9643   EXPECT_EQ(
9644       "U\"utf32 string \"\n"
9645       "U\"literal\";",
9646       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
9647   EXPECT_EQ("L\"wide string \"\n"
9648             "L\"literal\";",
9649             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
9650   EXPECT_EQ("@\"NSString \"\n"
9651             "@\"literal\";",
9652             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
9653   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
9654 
9655   // This input makes clang-format try to split the incomplete unicode escape
9656   // sequence, which used to lead to a crasher.
9657   verifyNoCrash(
9658       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
9659       getLLVMStyleWithColumns(60));
9660 }
9661 
9662 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
9663   FormatStyle Style = getGoogleStyleWithColumns(15);
9664   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
9665   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
9666   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
9667   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
9668   EXPECT_EQ("u8R\"x(raw literal)x\";",
9669             format("u8R\"x(raw literal)x\";", Style));
9670 }
9671 
9672 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
9673   FormatStyle Style = getLLVMStyleWithColumns(20);
9674   EXPECT_EQ(
9675       "_T(\"aaaaaaaaaaaaaa\")\n"
9676       "_T(\"aaaaaaaaaaaaaa\")\n"
9677       "_T(\"aaaaaaaaaaaa\")",
9678       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
9679   EXPECT_EQ("f(x,\n"
9680             "  _T(\"aaaaaaaaaaaa\")\n"
9681             "  _T(\"aaa\"),\n"
9682             "  z);",
9683             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
9684 
9685   // FIXME: Handle embedded spaces in one iteration.
9686   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
9687   //            "_T(\"aaaaaaaaaaaaa\")\n"
9688   //            "_T(\"aaaaaaaaaaaaa\")\n"
9689   //            "_T(\"a\")",
9690   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
9691   //                   getLLVMStyleWithColumns(20)));
9692   EXPECT_EQ(
9693       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
9694       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
9695   EXPECT_EQ("f(\n"
9696             "#if !TEST\n"
9697             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
9698             "#endif\n"
9699             ");",
9700             format("f(\n"
9701                    "#if !TEST\n"
9702                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
9703                    "#endif\n"
9704                    ");"));
9705   EXPECT_EQ("f(\n"
9706             "\n"
9707             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
9708             format("f(\n"
9709                    "\n"
9710                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
9711 }
9712 
9713 TEST_F(FormatTest, BreaksStringLiteralOperands) {
9714   // In a function call with two operands, the second can be broken with no line
9715   // break before it.
9716   EXPECT_EQ(
9717       "func(a, \"long long \"\n"
9718       "        \"long long\");",
9719       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
9720   // In a function call with three operands, the second must be broken with a
9721   // line break before it.
9722   EXPECT_EQ("func(a,\n"
9723             "     \"long long long \"\n"
9724             "     \"long\",\n"
9725             "     c);",
9726             format("func(a, \"long long long long\", c);",
9727                    getLLVMStyleWithColumns(24)));
9728   // In a function call with three operands, the third must be broken with a
9729   // line break before it.
9730   EXPECT_EQ("func(a, b,\n"
9731             "     \"long long long \"\n"
9732             "     \"long\");",
9733             format("func(a, b, \"long long long long\");",
9734                    getLLVMStyleWithColumns(24)));
9735   // In a function call with three operands, both the second and the third must
9736   // be broken with a line break before them.
9737   EXPECT_EQ("func(a,\n"
9738             "     \"long long long \"\n"
9739             "     \"long\",\n"
9740             "     \"long long long \"\n"
9741             "     \"long\");",
9742             format("func(a, \"long long long long\", \"long long long long\");",
9743                    getLLVMStyleWithColumns(24)));
9744   // In a chain of << with two operands, the second can be broken with no line
9745   // break before it.
9746   EXPECT_EQ("a << \"line line \"\n"
9747             "     \"line\";",
9748             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
9749   // In a chain of << with three operands, the second can be broken with no line
9750   // break before it.
9751   EXPECT_EQ(
9752       "abcde << \"line \"\n"
9753       "         \"line line\"\n"
9754       "      << c;",
9755       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
9756   // In a chain of << with three operands, the third must be broken with a line
9757   // break before it.
9758   EXPECT_EQ(
9759       "a << b\n"
9760       "  << \"line line \"\n"
9761       "     \"line\";",
9762       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
9763   // In a chain of << with three operands, the second can be broken with no line
9764   // break before it and the third must be broken with a line break before it.
9765   EXPECT_EQ("abcd << \"line line \"\n"
9766             "        \"line\"\n"
9767             "     << \"line line \"\n"
9768             "        \"line\";",
9769             format("abcd << \"line line line\" << \"line line line\";",
9770                    getLLVMStyleWithColumns(20)));
9771   // In a chain of binary operators with two operands, the second can be broken
9772   // with no line break before it.
9773   EXPECT_EQ(
9774       "abcd + \"line line \"\n"
9775       "       \"line line\";",
9776       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
9777   // In a chain of binary operators with three operands, the second must be
9778   // broken with a line break before it.
9779   EXPECT_EQ("abcd +\n"
9780             "    \"line line \"\n"
9781             "    \"line line\" +\n"
9782             "    e;",
9783             format("abcd + \"line line line line\" + e;",
9784                    getLLVMStyleWithColumns(20)));
9785   // In a function call with two operands, with AlignAfterOpenBracket enabled,
9786   // the first must be broken with a line break before it.
9787   FormatStyle Style = getLLVMStyleWithColumns(25);
9788   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
9789   EXPECT_EQ("someFunction(\n"
9790             "    \"long long long \"\n"
9791             "    \"long\",\n"
9792             "    a);",
9793             format("someFunction(\"long long long long\", a);", Style));
9794 }
9795 
9796 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
9797   EXPECT_EQ(
9798       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
9799       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
9800       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
9801       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
9802              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
9803              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
9804 }
9805 
9806 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
9807   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
9808             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
9809   EXPECT_EQ("fffffffffff(g(R\"x(\n"
9810             "multiline raw string literal xxxxxxxxxxxxxx\n"
9811             ")x\",\n"
9812             "              a),\n"
9813             "            b);",
9814             format("fffffffffff(g(R\"x(\n"
9815                    "multiline raw string literal xxxxxxxxxxxxxx\n"
9816                    ")x\", a), b);",
9817                    getGoogleStyleWithColumns(20)));
9818   EXPECT_EQ("fffffffffff(\n"
9819             "    g(R\"x(qqq\n"
9820             "multiline raw string literal xxxxxxxxxxxxxx\n"
9821             ")x\",\n"
9822             "      a),\n"
9823             "    b);",
9824             format("fffffffffff(g(R\"x(qqq\n"
9825                    "multiline raw string literal xxxxxxxxxxxxxx\n"
9826                    ")x\", a), b);",
9827                    getGoogleStyleWithColumns(20)));
9828 
9829   EXPECT_EQ("fffffffffff(R\"x(\n"
9830             "multiline raw string literal xxxxxxxxxxxxxx\n"
9831             ")x\");",
9832             format("fffffffffff(R\"x(\n"
9833                    "multiline raw string literal xxxxxxxxxxxxxx\n"
9834                    ")x\");",
9835                    getGoogleStyleWithColumns(20)));
9836   EXPECT_EQ("fffffffffff(R\"x(\n"
9837             "multiline raw string literal xxxxxxxxxxxxxx\n"
9838             ")x\" + bbbbbb);",
9839             format("fffffffffff(R\"x(\n"
9840                    "multiline raw string literal xxxxxxxxxxxxxx\n"
9841                    ")x\" +   bbbbbb);",
9842                    getGoogleStyleWithColumns(20)));
9843   EXPECT_EQ("fffffffffff(\n"
9844             "    R\"x(\n"
9845             "multiline raw string literal xxxxxxxxxxxxxx\n"
9846             ")x\" +\n"
9847             "    bbbbbb);",
9848             format("fffffffffff(\n"
9849                    " R\"x(\n"
9850                    "multiline raw string literal xxxxxxxxxxxxxx\n"
9851                    ")x\" + bbbbbb);",
9852                    getGoogleStyleWithColumns(20)));
9853   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
9854             format("fffffffffff(\n"
9855                    " R\"(single line raw string)\" + bbbbbb);"));
9856 }
9857 
9858 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
9859   verifyFormat("string a = \"unterminated;");
9860   EXPECT_EQ("function(\"unterminated,\n"
9861             "         OtherParameter);",
9862             format("function(  \"unterminated,\n"
9863                    "    OtherParameter);"));
9864 }
9865 
9866 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
9867   FormatStyle Style = getLLVMStyle();
9868   Style.Standard = FormatStyle::LS_Cpp03;
9869   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
9870             format("#define x(_a) printf(\"foo\"_a);", Style));
9871 }
9872 
9873 TEST_F(FormatTest, CppLexVersion) {
9874   FormatStyle Style = getLLVMStyle();
9875   // Formatting of x * y differs if x is a type.
9876   verifyFormat("void foo() { MACRO(a * b); }", Style);
9877   verifyFormat("void foo() { MACRO(int *b); }", Style);
9878 
9879   // LLVM style uses latest lexer.
9880   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
9881   Style.Standard = FormatStyle::LS_Cpp17;
9882   // But in c++17, char8_t isn't a keyword.
9883   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
9884 }
9885 
9886 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
9887 
9888 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
9889   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
9890             "             \"ddeeefff\");",
9891             format("someFunction(\"aaabbbcccdddeeefff\");",
9892                    getLLVMStyleWithColumns(25)));
9893   EXPECT_EQ("someFunction1234567890(\n"
9894             "    \"aaabbbcccdddeeefff\");",
9895             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
9896                    getLLVMStyleWithColumns(26)));
9897   EXPECT_EQ("someFunction1234567890(\n"
9898             "    \"aaabbbcccdddeeeff\"\n"
9899             "    \"f\");",
9900             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
9901                    getLLVMStyleWithColumns(25)));
9902   EXPECT_EQ("someFunction1234567890(\n"
9903             "    \"aaabbbcccdddeeeff\"\n"
9904             "    \"f\");",
9905             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
9906                    getLLVMStyleWithColumns(24)));
9907   EXPECT_EQ("someFunction(\n"
9908             "    \"aaabbbcc ddde \"\n"
9909             "    \"efff\");",
9910             format("someFunction(\"aaabbbcc ddde efff\");",
9911                    getLLVMStyleWithColumns(25)));
9912   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
9913             "             \"ddeeefff\");",
9914             format("someFunction(\"aaabbbccc ddeeefff\");",
9915                    getLLVMStyleWithColumns(25)));
9916   EXPECT_EQ("someFunction1234567890(\n"
9917             "    \"aaabb \"\n"
9918             "    \"cccdddeeefff\");",
9919             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
9920                    getLLVMStyleWithColumns(25)));
9921   EXPECT_EQ("#define A          \\\n"
9922             "  string s =       \\\n"
9923             "      \"123456789\"  \\\n"
9924             "      \"0\";         \\\n"
9925             "  int i;",
9926             format("#define A string s = \"1234567890\"; int i;",
9927                    getLLVMStyleWithColumns(20)));
9928   EXPECT_EQ("someFunction(\n"
9929             "    \"aaabbbcc \"\n"
9930             "    \"dddeeefff\");",
9931             format("someFunction(\"aaabbbcc dddeeefff\");",
9932                    getLLVMStyleWithColumns(25)));
9933 }
9934 
9935 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
9936   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
9937   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
9938   EXPECT_EQ("\"test\"\n"
9939             "\"\\n\"",
9940             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
9941   EXPECT_EQ("\"tes\\\\\"\n"
9942             "\"n\"",
9943             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
9944   EXPECT_EQ("\"\\\\\\\\\"\n"
9945             "\"\\n\"",
9946             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
9947   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
9948   EXPECT_EQ("\"\\uff01\"\n"
9949             "\"test\"",
9950             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
9951   EXPECT_EQ("\"\\Uff01ff02\"",
9952             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
9953   EXPECT_EQ("\"\\x000000000001\"\n"
9954             "\"next\"",
9955             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
9956   EXPECT_EQ("\"\\x000000000001next\"",
9957             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
9958   EXPECT_EQ("\"\\x000000000001\"",
9959             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
9960   EXPECT_EQ("\"test\"\n"
9961             "\"\\000000\"\n"
9962             "\"000001\"",
9963             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
9964   EXPECT_EQ("\"test\\000\"\n"
9965             "\"00000000\"\n"
9966             "\"1\"",
9967             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
9968 }
9969 
9970 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
9971   verifyFormat("void f() {\n"
9972                "  return g() {}\n"
9973                "  void h() {}");
9974   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
9975                "g();\n"
9976                "}");
9977 }
9978 
9979 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
9980   verifyFormat(
9981       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
9982 }
9983 
9984 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
9985   verifyFormat("class X {\n"
9986                "  void f() {\n"
9987                "  }\n"
9988                "};",
9989                getLLVMStyleWithColumns(12));
9990 }
9991 
9992 TEST_F(FormatTest, ConfigurableIndentWidth) {
9993   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
9994   EightIndent.IndentWidth = 8;
9995   EightIndent.ContinuationIndentWidth = 8;
9996   verifyFormat("void f() {\n"
9997                "        someFunction();\n"
9998                "        if (true) {\n"
9999                "                f();\n"
10000                "        }\n"
10001                "}",
10002                EightIndent);
10003   verifyFormat("class X {\n"
10004                "        void f() {\n"
10005                "        }\n"
10006                "};",
10007                EightIndent);
10008   verifyFormat("int x[] = {\n"
10009                "        call(),\n"
10010                "        call()};",
10011                EightIndent);
10012 }
10013 
10014 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
10015   verifyFormat("double\n"
10016                "f();",
10017                getLLVMStyleWithColumns(8));
10018 }
10019 
10020 TEST_F(FormatTest, ConfigurableUseOfTab) {
10021   FormatStyle Tab = getLLVMStyleWithColumns(42);
10022   Tab.IndentWidth = 8;
10023   Tab.UseTab = FormatStyle::UT_Always;
10024   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
10025 
10026   EXPECT_EQ("if (aaaaaaaa && // q\n"
10027             "    bb)\t\t// w\n"
10028             "\t;",
10029             format("if (aaaaaaaa &&// q\n"
10030                    "bb)// w\n"
10031                    ";",
10032                    Tab));
10033   EXPECT_EQ("if (aaa && bbb) // w\n"
10034             "\t;",
10035             format("if(aaa&&bbb)// w\n"
10036                    ";",
10037                    Tab));
10038 
10039   verifyFormat("class X {\n"
10040                "\tvoid f() {\n"
10041                "\t\tsomeFunction(parameter1,\n"
10042                "\t\t\t     parameter2);\n"
10043                "\t}\n"
10044                "};",
10045                Tab);
10046   verifyFormat("#define A                        \\\n"
10047                "\tvoid f() {               \\\n"
10048                "\t\tsomeFunction(    \\\n"
10049                "\t\t    parameter1,  \\\n"
10050                "\t\t    parameter2); \\\n"
10051                "\t}",
10052                Tab);
10053   verifyFormat("int a;\t      // x\n"
10054                "int bbbbbbbb; // x\n",
10055                Tab);
10056 
10057   Tab.TabWidth = 4;
10058   Tab.IndentWidth = 8;
10059   verifyFormat("class TabWidth4Indent8 {\n"
10060                "\t\tvoid f() {\n"
10061                "\t\t\t\tsomeFunction(parameter1,\n"
10062                "\t\t\t\t\t\t\t parameter2);\n"
10063                "\t\t}\n"
10064                "};",
10065                Tab);
10066 
10067   Tab.TabWidth = 4;
10068   Tab.IndentWidth = 4;
10069   verifyFormat("class TabWidth4Indent4 {\n"
10070                "\tvoid f() {\n"
10071                "\t\tsomeFunction(parameter1,\n"
10072                "\t\t\t\t\t parameter2);\n"
10073                "\t}\n"
10074                "};",
10075                Tab);
10076 
10077   Tab.TabWidth = 8;
10078   Tab.IndentWidth = 4;
10079   verifyFormat("class TabWidth8Indent4 {\n"
10080                "    void f() {\n"
10081                "\tsomeFunction(parameter1,\n"
10082                "\t\t     parameter2);\n"
10083                "    }\n"
10084                "};",
10085                Tab);
10086 
10087   Tab.TabWidth = 8;
10088   Tab.IndentWidth = 8;
10089   EXPECT_EQ("/*\n"
10090             "\t      a\t\tcomment\n"
10091             "\t      in multiple lines\n"
10092             "       */",
10093             format("   /*\t \t \n"
10094                    " \t \t a\t\tcomment\t \t\n"
10095                    " \t \t in multiple lines\t\n"
10096                    " \t  */",
10097                    Tab));
10098 
10099   Tab.UseTab = FormatStyle::UT_ForIndentation;
10100   verifyFormat("{\n"
10101                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10102                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10103                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10104                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10105                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10106                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10107                "};",
10108                Tab);
10109   verifyFormat("enum AA {\n"
10110                "\ta1, // Force multiple lines\n"
10111                "\ta2,\n"
10112                "\ta3\n"
10113                "};",
10114                Tab);
10115   EXPECT_EQ("if (aaaaaaaa && // q\n"
10116             "    bb)         // w\n"
10117             "\t;",
10118             format("if (aaaaaaaa &&// q\n"
10119                    "bb)// w\n"
10120                    ";",
10121                    Tab));
10122   verifyFormat("class X {\n"
10123                "\tvoid f() {\n"
10124                "\t\tsomeFunction(parameter1,\n"
10125                "\t\t             parameter2);\n"
10126                "\t}\n"
10127                "};",
10128                Tab);
10129   verifyFormat("{\n"
10130                "\tQ(\n"
10131                "\t    {\n"
10132                "\t\t    int a;\n"
10133                "\t\t    someFunction(aaaaaaaa,\n"
10134                "\t\t                 bbbbbbb);\n"
10135                "\t    },\n"
10136                "\t    p);\n"
10137                "}",
10138                Tab);
10139   EXPECT_EQ("{\n"
10140             "\t/* aaaa\n"
10141             "\t   bbbb */\n"
10142             "}",
10143             format("{\n"
10144                    "/* aaaa\n"
10145                    "   bbbb */\n"
10146                    "}",
10147                    Tab));
10148   EXPECT_EQ("{\n"
10149             "\t/*\n"
10150             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10151             "\t  bbbbbbbbbbbbb\n"
10152             "\t*/\n"
10153             "}",
10154             format("{\n"
10155                    "/*\n"
10156                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10157                    "*/\n"
10158                    "}",
10159                    Tab));
10160   EXPECT_EQ("{\n"
10161             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10162             "\t// bbbbbbbbbbbbb\n"
10163             "}",
10164             format("{\n"
10165                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10166                    "}",
10167                    Tab));
10168   EXPECT_EQ("{\n"
10169             "\t/*\n"
10170             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10171             "\t  bbbbbbbbbbbbb\n"
10172             "\t*/\n"
10173             "}",
10174             format("{\n"
10175                    "\t/*\n"
10176                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10177                    "\t*/\n"
10178                    "}",
10179                    Tab));
10180   EXPECT_EQ("{\n"
10181             "\t/*\n"
10182             "\n"
10183             "\t*/\n"
10184             "}",
10185             format("{\n"
10186                    "\t/*\n"
10187                    "\n"
10188                    "\t*/\n"
10189                    "}",
10190                    Tab));
10191   EXPECT_EQ("{\n"
10192             "\t/*\n"
10193             " asdf\n"
10194             "\t*/\n"
10195             "}",
10196             format("{\n"
10197                    "\t/*\n"
10198                    " asdf\n"
10199                    "\t*/\n"
10200                    "}",
10201                    Tab));
10202 
10203   Tab.UseTab = FormatStyle::UT_Never;
10204   EXPECT_EQ("/*\n"
10205             "              a\t\tcomment\n"
10206             "              in multiple lines\n"
10207             "       */",
10208             format("   /*\t \t \n"
10209                    " \t \t a\t\tcomment\t \t\n"
10210                    " \t \t in multiple lines\t\n"
10211                    " \t  */",
10212                    Tab));
10213   EXPECT_EQ("/* some\n"
10214             "   comment */",
10215             format(" \t \t /* some\n"
10216                    " \t \t    comment */",
10217                    Tab));
10218   EXPECT_EQ("int a; /* some\n"
10219             "   comment */",
10220             format(" \t \t int a; /* some\n"
10221                    " \t \t    comment */",
10222                    Tab));
10223 
10224   EXPECT_EQ("int a; /* some\n"
10225             "comment */",
10226             format(" \t \t int\ta; /* some\n"
10227                    " \t \t    comment */",
10228                    Tab));
10229   EXPECT_EQ("f(\"\t\t\"); /* some\n"
10230             "    comment */",
10231             format(" \t \t f(\"\t\t\"); /* some\n"
10232                    " \t \t    comment */",
10233                    Tab));
10234   EXPECT_EQ("{\n"
10235             "        /*\n"
10236             "         * Comment\n"
10237             "         */\n"
10238             "        int i;\n"
10239             "}",
10240             format("{\n"
10241                    "\t/*\n"
10242                    "\t * Comment\n"
10243                    "\t */\n"
10244                    "\t int i;\n"
10245                    "}",
10246                    Tab));
10247 
10248   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
10249   Tab.TabWidth = 8;
10250   Tab.IndentWidth = 8;
10251   EXPECT_EQ("if (aaaaaaaa && // q\n"
10252             "    bb)         // w\n"
10253             "\t;",
10254             format("if (aaaaaaaa &&// q\n"
10255                    "bb)// w\n"
10256                    ";",
10257                    Tab));
10258   EXPECT_EQ("if (aaa && bbb) // w\n"
10259             "\t;",
10260             format("if(aaa&&bbb)// w\n"
10261                    ";",
10262                    Tab));
10263   verifyFormat("class X {\n"
10264                "\tvoid f() {\n"
10265                "\t\tsomeFunction(parameter1,\n"
10266                "\t\t\t     parameter2);\n"
10267                "\t}\n"
10268                "};",
10269                Tab);
10270   verifyFormat("#define A                        \\\n"
10271                "\tvoid f() {               \\\n"
10272                "\t\tsomeFunction(    \\\n"
10273                "\t\t    parameter1,  \\\n"
10274                "\t\t    parameter2); \\\n"
10275                "\t}",
10276                Tab);
10277   Tab.TabWidth = 4;
10278   Tab.IndentWidth = 8;
10279   verifyFormat("class TabWidth4Indent8 {\n"
10280                "\t\tvoid f() {\n"
10281                "\t\t\t\tsomeFunction(parameter1,\n"
10282                "\t\t\t\t\t\t\t parameter2);\n"
10283                "\t\t}\n"
10284                "};",
10285                Tab);
10286   Tab.TabWidth = 4;
10287   Tab.IndentWidth = 4;
10288   verifyFormat("class TabWidth4Indent4 {\n"
10289                "\tvoid f() {\n"
10290                "\t\tsomeFunction(parameter1,\n"
10291                "\t\t\t\t\t parameter2);\n"
10292                "\t}\n"
10293                "};",
10294                Tab);
10295   Tab.TabWidth = 8;
10296   Tab.IndentWidth = 4;
10297   verifyFormat("class TabWidth8Indent4 {\n"
10298                "    void f() {\n"
10299                "\tsomeFunction(parameter1,\n"
10300                "\t\t     parameter2);\n"
10301                "    }\n"
10302                "};",
10303                Tab);
10304   Tab.TabWidth = 8;
10305   Tab.IndentWidth = 8;
10306   EXPECT_EQ("/*\n"
10307             "\t      a\t\tcomment\n"
10308             "\t      in multiple lines\n"
10309             "       */",
10310             format("   /*\t \t \n"
10311                    " \t \t a\t\tcomment\t \t\n"
10312                    " \t \t in multiple lines\t\n"
10313                    " \t  */",
10314                    Tab));
10315   verifyFormat("{\n"
10316                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10317                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10318                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10319                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10320                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10321                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10322                "};",
10323                Tab);
10324   verifyFormat("enum AA {\n"
10325                "\ta1, // Force multiple lines\n"
10326                "\ta2,\n"
10327                "\ta3\n"
10328                "};",
10329                Tab);
10330   EXPECT_EQ("if (aaaaaaaa && // q\n"
10331             "    bb)         // w\n"
10332             "\t;",
10333             format("if (aaaaaaaa &&// q\n"
10334                    "bb)// w\n"
10335                    ";",
10336                    Tab));
10337   verifyFormat("class X {\n"
10338                "\tvoid f() {\n"
10339                "\t\tsomeFunction(parameter1,\n"
10340                "\t\t\t     parameter2);\n"
10341                "\t}\n"
10342                "};",
10343                Tab);
10344   verifyFormat("{\n"
10345                "\tQ(\n"
10346                "\t    {\n"
10347                "\t\t    int a;\n"
10348                "\t\t    someFunction(aaaaaaaa,\n"
10349                "\t\t\t\t bbbbbbb);\n"
10350                "\t    },\n"
10351                "\t    p);\n"
10352                "}",
10353                Tab);
10354   EXPECT_EQ("{\n"
10355             "\t/* aaaa\n"
10356             "\t   bbbb */\n"
10357             "}",
10358             format("{\n"
10359                    "/* aaaa\n"
10360                    "   bbbb */\n"
10361                    "}",
10362                    Tab));
10363   EXPECT_EQ("{\n"
10364             "\t/*\n"
10365             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10366             "\t  bbbbbbbbbbbbb\n"
10367             "\t*/\n"
10368             "}",
10369             format("{\n"
10370                    "/*\n"
10371                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10372                    "*/\n"
10373                    "}",
10374                    Tab));
10375   EXPECT_EQ("{\n"
10376             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10377             "\t// bbbbbbbbbbbbb\n"
10378             "}",
10379             format("{\n"
10380                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10381                    "}",
10382                    Tab));
10383   EXPECT_EQ("{\n"
10384             "\t/*\n"
10385             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10386             "\t  bbbbbbbbbbbbb\n"
10387             "\t*/\n"
10388             "}",
10389             format("{\n"
10390                    "\t/*\n"
10391                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10392                    "\t*/\n"
10393                    "}",
10394                    Tab));
10395   EXPECT_EQ("{\n"
10396             "\t/*\n"
10397             "\n"
10398             "\t*/\n"
10399             "}",
10400             format("{\n"
10401                    "\t/*\n"
10402                    "\n"
10403                    "\t*/\n"
10404                    "}",
10405                    Tab));
10406   EXPECT_EQ("{\n"
10407             "\t/*\n"
10408             " asdf\n"
10409             "\t*/\n"
10410             "}",
10411             format("{\n"
10412                    "\t/*\n"
10413                    " asdf\n"
10414                    "\t*/\n"
10415                    "}",
10416                    Tab));
10417   EXPECT_EQ("/* some\n"
10418             "   comment */",
10419             format(" \t \t /* some\n"
10420                    " \t \t    comment */",
10421                    Tab));
10422   EXPECT_EQ("int a; /* some\n"
10423             "   comment */",
10424             format(" \t \t int a; /* some\n"
10425                    " \t \t    comment */",
10426                    Tab));
10427   EXPECT_EQ("int a; /* some\n"
10428             "comment */",
10429             format(" \t \t int\ta; /* some\n"
10430                    " \t \t    comment */",
10431                    Tab));
10432   EXPECT_EQ("f(\"\t\t\"); /* some\n"
10433             "    comment */",
10434             format(" \t \t f(\"\t\t\"); /* some\n"
10435                    " \t \t    comment */",
10436                    Tab));
10437   EXPECT_EQ("{\n"
10438             "\t/*\n"
10439             "\t * Comment\n"
10440             "\t */\n"
10441             "\tint i;\n"
10442             "}",
10443             format("{\n"
10444                    "\t/*\n"
10445                    "\t * Comment\n"
10446                    "\t */\n"
10447                    "\t int i;\n"
10448                    "}",
10449                    Tab));
10450   Tab.TabWidth = 2;
10451   Tab.IndentWidth = 2;
10452   EXPECT_EQ("{\n"
10453             "\t/* aaaa\n"
10454             "\t\t bbbb */\n"
10455             "}",
10456             format("{\n"
10457                    "/* aaaa\n"
10458                    "\t bbbb */\n"
10459                    "}",
10460                    Tab));
10461   EXPECT_EQ("{\n"
10462             "\t/*\n"
10463             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10464             "\t\tbbbbbbbbbbbbb\n"
10465             "\t*/\n"
10466             "}",
10467             format("{\n"
10468                    "/*\n"
10469                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10470                    "*/\n"
10471                    "}",
10472                    Tab));
10473   Tab.AlignConsecutiveAssignments = true;
10474   Tab.AlignConsecutiveDeclarations = true;
10475   Tab.TabWidth = 4;
10476   Tab.IndentWidth = 4;
10477   verifyFormat("class Assign {\n"
10478                "\tvoid f() {\n"
10479                "\t\tint         x      = 123;\n"
10480                "\t\tint         random = 4;\n"
10481                "\t\tstd::string alphabet =\n"
10482                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
10483                "\t}\n"
10484                "};",
10485                Tab);
10486 
10487   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
10488   Tab.TabWidth = 8;
10489   Tab.IndentWidth = 8;
10490   EXPECT_EQ("if (aaaaaaaa && // q\n"
10491             "    bb)         // w\n"
10492             "\t;",
10493             format("if (aaaaaaaa &&// q\n"
10494                    "bb)// w\n"
10495                    ";",
10496                    Tab));
10497   EXPECT_EQ("if (aaa && bbb) // w\n"
10498             "\t;",
10499             format("if(aaa&&bbb)// w\n"
10500                    ";",
10501                    Tab));
10502   verifyFormat("class X {\n"
10503                "\tvoid f() {\n"
10504                "\t\tsomeFunction(parameter1,\n"
10505                "\t\t             parameter2);\n"
10506                "\t}\n"
10507                "};",
10508                Tab);
10509   verifyFormat("#define A                        \\\n"
10510                "\tvoid f() {               \\\n"
10511                "\t\tsomeFunction(    \\\n"
10512                "\t\t    parameter1,  \\\n"
10513                "\t\t    parameter2); \\\n"
10514                "\t}",
10515                Tab);
10516   Tab.TabWidth = 4;
10517   Tab.IndentWidth = 8;
10518   verifyFormat("class TabWidth4Indent8 {\n"
10519                "\t\tvoid f() {\n"
10520                "\t\t\t\tsomeFunction(parameter1,\n"
10521                "\t\t\t\t             parameter2);\n"
10522                "\t\t}\n"
10523                "};",
10524                Tab);
10525   Tab.TabWidth = 4;
10526   Tab.IndentWidth = 4;
10527   verifyFormat("class TabWidth4Indent4 {\n"
10528                "\tvoid f() {\n"
10529                "\t\tsomeFunction(parameter1,\n"
10530                "\t\t             parameter2);\n"
10531                "\t}\n"
10532                "};",
10533                Tab);
10534   Tab.TabWidth = 8;
10535   Tab.IndentWidth = 4;
10536   verifyFormat("class TabWidth8Indent4 {\n"
10537                "    void f() {\n"
10538                "\tsomeFunction(parameter1,\n"
10539                "\t             parameter2);\n"
10540                "    }\n"
10541                "};",
10542                Tab);
10543   Tab.TabWidth = 8;
10544   Tab.IndentWidth = 8;
10545   EXPECT_EQ("/*\n"
10546             "              a\t\tcomment\n"
10547             "              in multiple lines\n"
10548             "       */",
10549             format("   /*\t \t \n"
10550                    " \t \t a\t\tcomment\t \t\n"
10551                    " \t \t in multiple lines\t\n"
10552                    " \t  */",
10553                    Tab));
10554   verifyFormat("{\n"
10555                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10556                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10557                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10558                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10559                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10560                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
10561                "};",
10562                Tab);
10563   verifyFormat("enum AA {\n"
10564                "\ta1, // Force multiple lines\n"
10565                "\ta2,\n"
10566                "\ta3\n"
10567                "};",
10568                Tab);
10569   EXPECT_EQ("if (aaaaaaaa && // q\n"
10570             "    bb)         // w\n"
10571             "\t;",
10572             format("if (aaaaaaaa &&// q\n"
10573                    "bb)// w\n"
10574                    ";",
10575                    Tab));
10576   verifyFormat("class X {\n"
10577                "\tvoid f() {\n"
10578                "\t\tsomeFunction(parameter1,\n"
10579                "\t\t             parameter2);\n"
10580                "\t}\n"
10581                "};",
10582                Tab);
10583   verifyFormat("{\n"
10584                "\tQ(\n"
10585                "\t    {\n"
10586                "\t\t    int a;\n"
10587                "\t\t    someFunction(aaaaaaaa,\n"
10588                "\t\t                 bbbbbbb);\n"
10589                "\t    },\n"
10590                "\t    p);\n"
10591                "}",
10592                Tab);
10593   EXPECT_EQ("{\n"
10594             "\t/* aaaa\n"
10595             "\t   bbbb */\n"
10596             "}",
10597             format("{\n"
10598                    "/* aaaa\n"
10599                    "   bbbb */\n"
10600                    "}",
10601                    Tab));
10602   EXPECT_EQ("{\n"
10603             "\t/*\n"
10604             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10605             "\t  bbbbbbbbbbbbb\n"
10606             "\t*/\n"
10607             "}",
10608             format("{\n"
10609                    "/*\n"
10610                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10611                    "*/\n"
10612                    "}",
10613                    Tab));
10614   EXPECT_EQ("{\n"
10615             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10616             "\t// bbbbbbbbbbbbb\n"
10617             "}",
10618             format("{\n"
10619                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10620                    "}",
10621                    Tab));
10622   EXPECT_EQ("{\n"
10623             "\t/*\n"
10624             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10625             "\t  bbbbbbbbbbbbb\n"
10626             "\t*/\n"
10627             "}",
10628             format("{\n"
10629                    "\t/*\n"
10630                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10631                    "\t*/\n"
10632                    "}",
10633                    Tab));
10634   EXPECT_EQ("{\n"
10635             "\t/*\n"
10636             "\n"
10637             "\t*/\n"
10638             "}",
10639             format("{\n"
10640                    "\t/*\n"
10641                    "\n"
10642                    "\t*/\n"
10643                    "}",
10644                    Tab));
10645   EXPECT_EQ("{\n"
10646             "\t/*\n"
10647             " asdf\n"
10648             "\t*/\n"
10649             "}",
10650             format("{\n"
10651                    "\t/*\n"
10652                    " asdf\n"
10653                    "\t*/\n"
10654                    "}",
10655                    Tab));
10656   EXPECT_EQ("/* some\n"
10657             "   comment */",
10658             format(" \t \t /* some\n"
10659                    " \t \t    comment */",
10660                    Tab));
10661   EXPECT_EQ("int a; /* some\n"
10662             "   comment */",
10663             format(" \t \t int a; /* some\n"
10664                    " \t \t    comment */",
10665                    Tab));
10666   EXPECT_EQ("int a; /* some\n"
10667             "comment */",
10668             format(" \t \t int\ta; /* some\n"
10669                    " \t \t    comment */",
10670                    Tab));
10671   EXPECT_EQ("f(\"\t\t\"); /* some\n"
10672             "    comment */",
10673             format(" \t \t f(\"\t\t\"); /* some\n"
10674                    " \t \t    comment */",
10675                    Tab));
10676   EXPECT_EQ("{\n"
10677             "\t/*\n"
10678             "\t * Comment\n"
10679             "\t */\n"
10680             "\tint i;\n"
10681             "}",
10682             format("{\n"
10683                    "\t/*\n"
10684                    "\t * Comment\n"
10685                    "\t */\n"
10686                    "\t int i;\n"
10687                    "}",
10688                    Tab));
10689   Tab.TabWidth = 2;
10690   Tab.IndentWidth = 2;
10691   EXPECT_EQ("{\n"
10692             "\t/* aaaa\n"
10693             "\t   bbbb */\n"
10694             "}",
10695             format("{\n"
10696                    "/* aaaa\n"
10697                    "   bbbb */\n"
10698                    "}",
10699                    Tab));
10700   EXPECT_EQ("{\n"
10701             "\t/*\n"
10702             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
10703             "\t  bbbbbbbbbbbbb\n"
10704             "\t*/\n"
10705             "}",
10706             format("{\n"
10707                    "/*\n"
10708                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
10709                    "*/\n"
10710                    "}",
10711                    Tab));
10712   Tab.AlignConsecutiveAssignments = true;
10713   Tab.AlignConsecutiveDeclarations = true;
10714   Tab.TabWidth = 4;
10715   Tab.IndentWidth = 4;
10716   verifyFormat("class Assign {\n"
10717                "\tvoid f() {\n"
10718                "\t\tint         x      = 123;\n"
10719                "\t\tint         random = 4;\n"
10720                "\t\tstd::string alphabet =\n"
10721                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
10722                "\t}\n"
10723                "};",
10724                Tab);
10725 }
10726 
10727 TEST_F(FormatTest, ZeroTabWidth) {
10728   FormatStyle Tab = getLLVMStyleWithColumns(42);
10729   Tab.IndentWidth = 8;
10730   Tab.UseTab = FormatStyle::UT_Never;
10731   Tab.TabWidth = 0;
10732   EXPECT_EQ("void a(){\n"
10733             "    // line starts with '\t'\n"
10734             "};",
10735             format("void a(){\n"
10736                    "\t// line starts with '\t'\n"
10737                    "};",
10738                    Tab));
10739 
10740   EXPECT_EQ("void a(){\n"
10741             "    // line starts with '\t'\n"
10742             "};",
10743             format("void a(){\n"
10744                    "\t\t// line starts with '\t'\n"
10745                    "};",
10746                    Tab));
10747 
10748   Tab.UseTab = FormatStyle::UT_ForIndentation;
10749   EXPECT_EQ("void a(){\n"
10750             "    // line starts with '\t'\n"
10751             "};",
10752             format("void a(){\n"
10753                    "\t// line starts with '\t'\n"
10754                    "};",
10755                    Tab));
10756 
10757   EXPECT_EQ("void a(){\n"
10758             "    // line starts with '\t'\n"
10759             "};",
10760             format("void a(){\n"
10761                    "\t\t// line starts with '\t'\n"
10762                    "};",
10763                    Tab));
10764 
10765   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
10766   EXPECT_EQ("void a(){\n"
10767             "    // line starts with '\t'\n"
10768             "};",
10769             format("void a(){\n"
10770                    "\t// line starts with '\t'\n"
10771                    "};",
10772                    Tab));
10773 
10774   EXPECT_EQ("void a(){\n"
10775             "    // line starts with '\t'\n"
10776             "};",
10777             format("void a(){\n"
10778                    "\t\t// line starts with '\t'\n"
10779                    "};",
10780                    Tab));
10781 
10782   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
10783   EXPECT_EQ("void a(){\n"
10784             "    // line starts with '\t'\n"
10785             "};",
10786             format("void a(){\n"
10787                    "\t// line starts with '\t'\n"
10788                    "};",
10789                    Tab));
10790 
10791   EXPECT_EQ("void a(){\n"
10792             "    // line starts with '\t'\n"
10793             "};",
10794             format("void a(){\n"
10795                    "\t\t// line starts with '\t'\n"
10796                    "};",
10797                    Tab));
10798 
10799   Tab.UseTab = FormatStyle::UT_Always;
10800   EXPECT_EQ("void a(){\n"
10801             "// line starts with '\t'\n"
10802             "};",
10803             format("void a(){\n"
10804                    "\t// line starts with '\t'\n"
10805                    "};",
10806                    Tab));
10807 
10808   EXPECT_EQ("void a(){\n"
10809             "// line starts with '\t'\n"
10810             "};",
10811             format("void a(){\n"
10812                    "\t\t// line starts with '\t'\n"
10813                    "};",
10814                    Tab));
10815 }
10816 
10817 TEST_F(FormatTest, CalculatesOriginalColumn) {
10818   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
10819             "q\"; /* some\n"
10820             "       comment */",
10821             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
10822                    "q\"; /* some\n"
10823                    "       comment */",
10824                    getLLVMStyle()));
10825   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
10826             "/* some\n"
10827             "   comment */",
10828             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
10829                    " /* some\n"
10830                    "    comment */",
10831                    getLLVMStyle()));
10832   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
10833             "qqq\n"
10834             "/* some\n"
10835             "   comment */",
10836             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
10837                    "qqq\n"
10838                    " /* some\n"
10839                    "    comment */",
10840                    getLLVMStyle()));
10841   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
10842             "wwww; /* some\n"
10843             "         comment */",
10844             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
10845                    "wwww; /* some\n"
10846                    "         comment */",
10847                    getLLVMStyle()));
10848 }
10849 
10850 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
10851   FormatStyle NoSpace = getLLVMStyle();
10852   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
10853 
10854   verifyFormat("while(true)\n"
10855                "  continue;",
10856                NoSpace);
10857   verifyFormat("for(;;)\n"
10858                "  continue;",
10859                NoSpace);
10860   verifyFormat("if(true)\n"
10861                "  f();\n"
10862                "else if(true)\n"
10863                "  f();",
10864                NoSpace);
10865   verifyFormat("do {\n"
10866                "  do_something();\n"
10867                "} while(something());",
10868                NoSpace);
10869   verifyFormat("switch(x) {\n"
10870                "default:\n"
10871                "  break;\n"
10872                "}",
10873                NoSpace);
10874   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
10875   verifyFormat("size_t x = sizeof(x);", NoSpace);
10876   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
10877   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
10878   verifyFormat("alignas(128) char a[128];", NoSpace);
10879   verifyFormat("size_t x = alignof(MyType);", NoSpace);
10880   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
10881   verifyFormat("int f() throw(Deprecated);", NoSpace);
10882   verifyFormat("typedef void (*cb)(int);", NoSpace);
10883   verifyFormat("T A::operator()();", NoSpace);
10884   verifyFormat("X A::operator++(T);", NoSpace);
10885   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
10886 
10887   FormatStyle Space = getLLVMStyle();
10888   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
10889 
10890   verifyFormat("int f ();", Space);
10891   verifyFormat("void f (int a, T b) {\n"
10892                "  while (true)\n"
10893                "    continue;\n"
10894                "}",
10895                Space);
10896   verifyFormat("if (true)\n"
10897                "  f ();\n"
10898                "else if (true)\n"
10899                "  f ();",
10900                Space);
10901   verifyFormat("do {\n"
10902                "  do_something ();\n"
10903                "} while (something ());",
10904                Space);
10905   verifyFormat("switch (x) {\n"
10906                "default:\n"
10907                "  break;\n"
10908                "}",
10909                Space);
10910   verifyFormat("A::A () : a (1) {}", Space);
10911   verifyFormat("void f () __attribute__ ((asdf));", Space);
10912   verifyFormat("*(&a + 1);\n"
10913                "&((&a)[1]);\n"
10914                "a[(b + c) * d];\n"
10915                "(((a + 1) * 2) + 3) * 4;",
10916                Space);
10917   verifyFormat("#define A(x) x", Space);
10918   verifyFormat("#define A (x) x", Space);
10919   verifyFormat("#if defined(x)\n"
10920                "#endif",
10921                Space);
10922   verifyFormat("auto i = std::make_unique<int> (5);", Space);
10923   verifyFormat("size_t x = sizeof (x);", Space);
10924   verifyFormat("auto f (int x) -> decltype (x);", Space);
10925   verifyFormat("int f (T x) noexcept (x.create ());", Space);
10926   verifyFormat("alignas (128) char a[128];", Space);
10927   verifyFormat("size_t x = alignof (MyType);", Space);
10928   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
10929   verifyFormat("int f () throw (Deprecated);", Space);
10930   verifyFormat("typedef void (*cb) (int);", Space);
10931   verifyFormat("T A::operator() ();", Space);
10932   verifyFormat("X A::operator++ (T);", Space);
10933   verifyFormat("auto lambda = [] () { return 0; };", Space);
10934   verifyFormat("int x = int (y);", Space);
10935 
10936   FormatStyle SomeSpace = getLLVMStyle();
10937   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
10938 
10939   verifyFormat("[]() -> float {}", SomeSpace);
10940   verifyFormat("[] (auto foo) {}", SomeSpace);
10941   verifyFormat("[foo]() -> int {}", SomeSpace);
10942   verifyFormat("int f();", SomeSpace);
10943   verifyFormat("void f (int a, T b) {\n"
10944                "  while (true)\n"
10945                "    continue;\n"
10946                "}",
10947                SomeSpace);
10948   verifyFormat("if (true)\n"
10949                "  f();\n"
10950                "else if (true)\n"
10951                "  f();",
10952                SomeSpace);
10953   verifyFormat("do {\n"
10954                "  do_something();\n"
10955                "} while (something());",
10956                SomeSpace);
10957   verifyFormat("switch (x) {\n"
10958                "default:\n"
10959                "  break;\n"
10960                "}",
10961                SomeSpace);
10962   verifyFormat("A::A() : a (1) {}", SomeSpace);
10963   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
10964   verifyFormat("*(&a + 1);\n"
10965                "&((&a)[1]);\n"
10966                "a[(b + c) * d];\n"
10967                "(((a + 1) * 2) + 3) * 4;",
10968                SomeSpace);
10969   verifyFormat("#define A(x) x", SomeSpace);
10970   verifyFormat("#define A (x) x", SomeSpace);
10971   verifyFormat("#if defined(x)\n"
10972                "#endif",
10973                SomeSpace);
10974   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
10975   verifyFormat("size_t x = sizeof (x);", SomeSpace);
10976   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
10977   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
10978   verifyFormat("alignas (128) char a[128];", SomeSpace);
10979   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
10980   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
10981                SomeSpace);
10982   verifyFormat("int f() throw (Deprecated);", SomeSpace);
10983   verifyFormat("typedef void (*cb) (int);", SomeSpace);
10984   verifyFormat("T A::operator()();", SomeSpace);
10985   verifyFormat("X A::operator++ (T);", SomeSpace);
10986   verifyFormat("int x = int (y);", SomeSpace);
10987   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
10988 }
10989 
10990 TEST_F(FormatTest, SpaceAfterLogicalNot) {
10991   FormatStyle Spaces = getLLVMStyle();
10992   Spaces.SpaceAfterLogicalNot = true;
10993 
10994   verifyFormat("bool x = ! y", Spaces);
10995   verifyFormat("if (! isFailure())", Spaces);
10996   verifyFormat("if (! (a && b))", Spaces);
10997   verifyFormat("\"Error!\"", Spaces);
10998   verifyFormat("! ! x", Spaces);
10999 }
11000 
11001 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
11002   FormatStyle Spaces = getLLVMStyle();
11003 
11004   Spaces.SpacesInParentheses = true;
11005   verifyFormat("do_something( ::globalVar );", Spaces);
11006   verifyFormat("call( x, y, z );", Spaces);
11007   verifyFormat("call();", Spaces);
11008   verifyFormat("std::function<void( int, int )> callback;", Spaces);
11009   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
11010                Spaces);
11011   verifyFormat("while ( (bool)1 )\n"
11012                "  continue;",
11013                Spaces);
11014   verifyFormat("for ( ;; )\n"
11015                "  continue;",
11016                Spaces);
11017   verifyFormat("if ( true )\n"
11018                "  f();\n"
11019                "else if ( true )\n"
11020                "  f();",
11021                Spaces);
11022   verifyFormat("do {\n"
11023                "  do_something( (int)i );\n"
11024                "} while ( something() );",
11025                Spaces);
11026   verifyFormat("switch ( x ) {\n"
11027                "default:\n"
11028                "  break;\n"
11029                "}",
11030                Spaces);
11031 
11032   Spaces.SpacesInParentheses = false;
11033   Spaces.SpacesInCStyleCastParentheses = true;
11034   verifyFormat("Type *A = ( Type * )P;", Spaces);
11035   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
11036   verifyFormat("x = ( int32 )y;", Spaces);
11037   verifyFormat("int a = ( int )(2.0f);", Spaces);
11038   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
11039   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
11040   verifyFormat("#define x (( int )-1)", Spaces);
11041 
11042   // Run the first set of tests again with:
11043   Spaces.SpacesInParentheses = false;
11044   Spaces.SpaceInEmptyParentheses = true;
11045   Spaces.SpacesInCStyleCastParentheses = true;
11046   verifyFormat("call(x, y, z);", Spaces);
11047   verifyFormat("call( );", Spaces);
11048   verifyFormat("std::function<void(int, int)> callback;", Spaces);
11049   verifyFormat("while (( bool )1)\n"
11050                "  continue;",
11051                Spaces);
11052   verifyFormat("for (;;)\n"
11053                "  continue;",
11054                Spaces);
11055   verifyFormat("if (true)\n"
11056                "  f( );\n"
11057                "else if (true)\n"
11058                "  f( );",
11059                Spaces);
11060   verifyFormat("do {\n"
11061                "  do_something(( int )i);\n"
11062                "} while (something( ));",
11063                Spaces);
11064   verifyFormat("switch (x) {\n"
11065                "default:\n"
11066                "  break;\n"
11067                "}",
11068                Spaces);
11069 
11070   // Run the first set of tests again with:
11071   Spaces.SpaceAfterCStyleCast = true;
11072   verifyFormat("call(x, y, z);", Spaces);
11073   verifyFormat("call( );", Spaces);
11074   verifyFormat("std::function<void(int, int)> callback;", Spaces);
11075   verifyFormat("while (( bool ) 1)\n"
11076                "  continue;",
11077                Spaces);
11078   verifyFormat("for (;;)\n"
11079                "  continue;",
11080                Spaces);
11081   verifyFormat("if (true)\n"
11082                "  f( );\n"
11083                "else if (true)\n"
11084                "  f( );",
11085                Spaces);
11086   verifyFormat("do {\n"
11087                "  do_something(( int ) i);\n"
11088                "} while (something( ));",
11089                Spaces);
11090   verifyFormat("switch (x) {\n"
11091                "default:\n"
11092                "  break;\n"
11093                "}",
11094                Spaces);
11095 
11096   // Run subset of tests again with:
11097   Spaces.SpacesInCStyleCastParentheses = false;
11098   Spaces.SpaceAfterCStyleCast = true;
11099   verifyFormat("while ((bool) 1)\n"
11100                "  continue;",
11101                Spaces);
11102   verifyFormat("do {\n"
11103                "  do_something((int) i);\n"
11104                "} while (something( ));",
11105                Spaces);
11106 }
11107 
11108 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
11109   verifyFormat("int a[5];");
11110   verifyFormat("a[3] += 42;");
11111 
11112   FormatStyle Spaces = getLLVMStyle();
11113   Spaces.SpacesInSquareBrackets = true;
11114   // Not lambdas.
11115   verifyFormat("int a[ 5 ];", Spaces);
11116   verifyFormat("a[ 3 ] += 42;", Spaces);
11117   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
11118   verifyFormat("double &operator[](int i) { return 0; }\n"
11119                "int i;",
11120                Spaces);
11121   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
11122   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
11123   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
11124   // Lambdas.
11125   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
11126   verifyFormat("return [ i, args... ] {};", Spaces);
11127   verifyFormat("int foo = [ &bar ]() {};", Spaces);
11128   verifyFormat("int foo = [ = ]() {};", Spaces);
11129   verifyFormat("int foo = [ & ]() {};", Spaces);
11130   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
11131   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
11132 }
11133 
11134 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
11135   FormatStyle NoSpaceStyle = getLLVMStyle();
11136   verifyFormat("int a[5];", NoSpaceStyle);
11137   verifyFormat("a[3] += 42;", NoSpaceStyle);
11138 
11139   verifyFormat("int a[1];", NoSpaceStyle);
11140   verifyFormat("int 1 [a];", NoSpaceStyle);
11141   verifyFormat("int a[1][2];", NoSpaceStyle);
11142   verifyFormat("a[7] = 5;", NoSpaceStyle);
11143   verifyFormat("int a = (f())[23];", NoSpaceStyle);
11144   verifyFormat("f([] {})", NoSpaceStyle);
11145 
11146   FormatStyle Space = getLLVMStyle();
11147   Space.SpaceBeforeSquareBrackets = true;
11148   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
11149   verifyFormat("return [i, args...] {};", Space);
11150 
11151   verifyFormat("int a [5];", Space);
11152   verifyFormat("a [3] += 42;", Space);
11153   verifyFormat("constexpr char hello []{\"hello\"};", Space);
11154   verifyFormat("double &operator[](int i) { return 0; }\n"
11155                "int i;",
11156                Space);
11157   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
11158   verifyFormat("int i = a [a][a]->f();", Space);
11159   verifyFormat("int i = (*b) [a]->f();", Space);
11160 
11161   verifyFormat("int a [1];", Space);
11162   verifyFormat("int 1 [a];", Space);
11163   verifyFormat("int a [1][2];", Space);
11164   verifyFormat("a [7] = 5;", Space);
11165   verifyFormat("int a = (f()) [23];", Space);
11166   verifyFormat("f([] {})", Space);
11167 }
11168 
11169 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
11170   verifyFormat("int a = 5;");
11171   verifyFormat("a += 42;");
11172   verifyFormat("a or_eq 8;");
11173 
11174   FormatStyle Spaces = getLLVMStyle();
11175   Spaces.SpaceBeforeAssignmentOperators = false;
11176   verifyFormat("int a= 5;", Spaces);
11177   verifyFormat("a+= 42;", Spaces);
11178   verifyFormat("a or_eq 8;", Spaces);
11179 }
11180 
11181 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
11182   verifyFormat("class Foo : public Bar {};");
11183   verifyFormat("Foo::Foo() : foo(1) {}");
11184   verifyFormat("for (auto a : b) {\n}");
11185   verifyFormat("int x = a ? b : c;");
11186   verifyFormat("{\n"
11187                "label0:\n"
11188                "  int x = 0;\n"
11189                "}");
11190   verifyFormat("switch (x) {\n"
11191                "case 1:\n"
11192                "default:\n"
11193                "}");
11194 
11195   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
11196   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
11197   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
11198   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
11199   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
11200   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
11201   verifyFormat("{\n"
11202                "label1:\n"
11203                "  int x = 0;\n"
11204                "}",
11205                CtorInitializerStyle);
11206   verifyFormat("switch (x) {\n"
11207                "case 1:\n"
11208                "default:\n"
11209                "}",
11210                CtorInitializerStyle);
11211   CtorInitializerStyle.BreakConstructorInitializers =
11212       FormatStyle::BCIS_AfterColon;
11213   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
11214                "    aaaaaaaaaaaaaaaa(1),\n"
11215                "    bbbbbbbbbbbbbbbb(2) {}",
11216                CtorInitializerStyle);
11217   CtorInitializerStyle.BreakConstructorInitializers =
11218       FormatStyle::BCIS_BeforeComma;
11219   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
11220                "    : aaaaaaaaaaaaaaaa(1)\n"
11221                "    , bbbbbbbbbbbbbbbb(2) {}",
11222                CtorInitializerStyle);
11223   CtorInitializerStyle.BreakConstructorInitializers =
11224       FormatStyle::BCIS_BeforeColon;
11225   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
11226                "    : aaaaaaaaaaaaaaaa(1),\n"
11227                "      bbbbbbbbbbbbbbbb(2) {}",
11228                CtorInitializerStyle);
11229   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
11230   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
11231                ": aaaaaaaaaaaaaaaa(1),\n"
11232                "  bbbbbbbbbbbbbbbb(2) {}",
11233                CtorInitializerStyle);
11234 
11235   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
11236   InheritanceStyle.SpaceBeforeInheritanceColon = false;
11237   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
11238   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
11239   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
11240   verifyFormat("int x = a ? b : c;", InheritanceStyle);
11241   verifyFormat("{\n"
11242                "label2:\n"
11243                "  int x = 0;\n"
11244                "}",
11245                InheritanceStyle);
11246   verifyFormat("switch (x) {\n"
11247                "case 1:\n"
11248                "default:\n"
11249                "}",
11250                InheritanceStyle);
11251   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
11252   verifyFormat("class Foooooooooooooooooooooo:\n"
11253                "    public aaaaaaaaaaaaaaaaaa,\n"
11254                "    public bbbbbbbbbbbbbbbbbb {\n"
11255                "}",
11256                InheritanceStyle);
11257   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
11258   verifyFormat("class Foooooooooooooooooooooo\n"
11259                "    : public aaaaaaaaaaaaaaaaaa\n"
11260                "    , public bbbbbbbbbbbbbbbbbb {\n"
11261                "}",
11262                InheritanceStyle);
11263   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
11264   verifyFormat("class Foooooooooooooooooooooo\n"
11265                "    : public aaaaaaaaaaaaaaaaaa,\n"
11266                "      public bbbbbbbbbbbbbbbbbb {\n"
11267                "}",
11268                InheritanceStyle);
11269   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
11270   verifyFormat("class Foooooooooooooooooooooo\n"
11271                ": public aaaaaaaaaaaaaaaaaa,\n"
11272                "  public bbbbbbbbbbbbbbbbbb {}",
11273                InheritanceStyle);
11274 
11275   FormatStyle ForLoopStyle = getLLVMStyle();
11276   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
11277   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
11278   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
11279   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
11280   verifyFormat("int x = a ? b : c;", ForLoopStyle);
11281   verifyFormat("{\n"
11282                "label2:\n"
11283                "  int x = 0;\n"
11284                "}",
11285                ForLoopStyle);
11286   verifyFormat("switch (x) {\n"
11287                "case 1:\n"
11288                "default:\n"
11289                "}",
11290                ForLoopStyle);
11291 
11292   FormatStyle NoSpaceStyle = getLLVMStyle();
11293   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
11294   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
11295   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
11296   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
11297   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
11298   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
11299   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
11300   verifyFormat("{\n"
11301                "label3:\n"
11302                "  int x = 0;\n"
11303                "}",
11304                NoSpaceStyle);
11305   verifyFormat("switch (x) {\n"
11306                "case 1:\n"
11307                "default:\n"
11308                "}",
11309                NoSpaceStyle);
11310 }
11311 
11312 TEST_F(FormatTest, AlignConsecutiveMacros) {
11313   FormatStyle Style = getLLVMStyle();
11314   Style.AlignConsecutiveAssignments = true;
11315   Style.AlignConsecutiveDeclarations = true;
11316   Style.AlignConsecutiveMacros = false;
11317 
11318   verifyFormat("#define a 3\n"
11319                "#define bbbb 4\n"
11320                "#define ccc (5)",
11321                Style);
11322 
11323   verifyFormat("#define f(x) (x * x)\n"
11324                "#define fff(x, y, z) (x * y + z)\n"
11325                "#define ffff(x, y) (x - y)",
11326                Style);
11327 
11328   verifyFormat("#define foo(x, y) (x + y)\n"
11329                "#define bar (5, 6)(2 + 2)",
11330                Style);
11331 
11332   verifyFormat("#define a 3\n"
11333                "#define bbbb 4\n"
11334                "#define ccc (5)\n"
11335                "#define f(x) (x * x)\n"
11336                "#define fff(x, y, z) (x * y + z)\n"
11337                "#define ffff(x, y) (x - y)",
11338                Style);
11339 
11340   Style.AlignConsecutiveMacros = true;
11341   verifyFormat("#define a    3\n"
11342                "#define bbbb 4\n"
11343                "#define ccc  (5)",
11344                Style);
11345 
11346   verifyFormat("#define f(x)         (x * x)\n"
11347                "#define fff(x, y, z) (x * y + z)\n"
11348                "#define ffff(x, y)   (x - y)",
11349                Style);
11350 
11351   verifyFormat("#define foo(x, y) (x + y)\n"
11352                "#define bar       (5, 6)(2 + 2)",
11353                Style);
11354 
11355   verifyFormat("#define a            3\n"
11356                "#define bbbb         4\n"
11357                "#define ccc          (5)\n"
11358                "#define f(x)         (x * x)\n"
11359                "#define fff(x, y, z) (x * y + z)\n"
11360                "#define ffff(x, y)   (x - y)",
11361                Style);
11362 
11363   verifyFormat("#define a         5\n"
11364                "#define foo(x, y) (x + y)\n"
11365                "#define CCC       (6)\n"
11366                "auto lambda = []() {\n"
11367                "  auto  ii = 0;\n"
11368                "  float j  = 0;\n"
11369                "  return 0;\n"
11370                "};\n"
11371                "int   i  = 0;\n"
11372                "float i2 = 0;\n"
11373                "auto  v  = type{\n"
11374                "    i = 1,   //\n"
11375                "    (i = 2), //\n"
11376                "    i = 3    //\n"
11377                "};",
11378                Style);
11379 
11380   Style.AlignConsecutiveMacros = false;
11381   Style.ColumnLimit = 20;
11382 
11383   verifyFormat("#define a          \\\n"
11384                "  \"aabbbbbbbbbbbb\"\n"
11385                "#define D          \\\n"
11386                "  \"aabbbbbbbbbbbb\" \\\n"
11387                "  \"ccddeeeeeeeee\"\n"
11388                "#define B          \\\n"
11389                "  \"QQQQQQQQQQQQQ\"  \\\n"
11390                "  \"FFFFFFFFFFFFF\"  \\\n"
11391                "  \"LLLLLLLL\"\n",
11392                Style);
11393 
11394   Style.AlignConsecutiveMacros = true;
11395   verifyFormat("#define a          \\\n"
11396                "  \"aabbbbbbbbbbbb\"\n"
11397                "#define D          \\\n"
11398                "  \"aabbbbbbbbbbbb\" \\\n"
11399                "  \"ccddeeeeeeeee\"\n"
11400                "#define B          \\\n"
11401                "  \"QQQQQQQQQQQQQ\"  \\\n"
11402                "  \"FFFFFFFFFFFFF\"  \\\n"
11403                "  \"LLLLLLLL\"\n",
11404                Style);
11405 }
11406 
11407 TEST_F(FormatTest, AlignConsecutiveAssignments) {
11408   FormatStyle Alignment = getLLVMStyle();
11409   Alignment.AlignConsecutiveMacros = true;
11410   Alignment.AlignConsecutiveAssignments = false;
11411   verifyFormat("int a = 5;\n"
11412                "int oneTwoThree = 123;",
11413                Alignment);
11414   verifyFormat("int a = 5;\n"
11415                "int oneTwoThree = 123;",
11416                Alignment);
11417 
11418   Alignment.AlignConsecutiveAssignments = true;
11419   verifyFormat("int a           = 5;\n"
11420                "int oneTwoThree = 123;",
11421                Alignment);
11422   verifyFormat("int a           = method();\n"
11423                "int oneTwoThree = 133;",
11424                Alignment);
11425   verifyFormat("a &= 5;\n"
11426                "bcd *= 5;\n"
11427                "ghtyf += 5;\n"
11428                "dvfvdb -= 5;\n"
11429                "a /= 5;\n"
11430                "vdsvsv %= 5;\n"
11431                "sfdbddfbdfbb ^= 5;\n"
11432                "dvsdsv |= 5;\n"
11433                "int dsvvdvsdvvv = 123;",
11434                Alignment);
11435   verifyFormat("int i = 1, j = 10;\n"
11436                "something = 2000;",
11437                Alignment);
11438   verifyFormat("something = 2000;\n"
11439                "int i = 1, j = 10;\n",
11440                Alignment);
11441   verifyFormat("something = 2000;\n"
11442                "another   = 911;\n"
11443                "int i = 1, j = 10;\n"
11444                "oneMore = 1;\n"
11445                "i       = 2;",
11446                Alignment);
11447   verifyFormat("int a   = 5;\n"
11448                "int one = 1;\n"
11449                "method();\n"
11450                "int oneTwoThree = 123;\n"
11451                "int oneTwo      = 12;",
11452                Alignment);
11453   verifyFormat("int oneTwoThree = 123;\n"
11454                "int oneTwo      = 12;\n"
11455                "method();\n",
11456                Alignment);
11457   verifyFormat("int oneTwoThree = 123; // comment\n"
11458                "int oneTwo      = 12;  // comment",
11459                Alignment);
11460 
11461   // Bug 25167
11462   verifyFormat("#if A\n"
11463                "#else\n"
11464                "int aaaaaaaa = 12;\n"
11465                "#endif\n"
11466                "#if B\n"
11467                "#else\n"
11468                "int a = 12;\n"
11469                "#endif\n",
11470                Alignment);
11471   verifyFormat("enum foo {\n"
11472                "#if A\n"
11473                "#else\n"
11474                "  aaaaaaaa = 12;\n"
11475                "#endif\n"
11476                "#if B\n"
11477                "#else\n"
11478                "  a = 12;\n"
11479                "#endif\n"
11480                "};\n",
11481                Alignment);
11482 
11483   EXPECT_EQ("int a = 5;\n"
11484             "\n"
11485             "int oneTwoThree = 123;",
11486             format("int a       = 5;\n"
11487                    "\n"
11488                    "int oneTwoThree= 123;",
11489                    Alignment));
11490   EXPECT_EQ("int a   = 5;\n"
11491             "int one = 1;\n"
11492             "\n"
11493             "int oneTwoThree = 123;",
11494             format("int a = 5;\n"
11495                    "int one = 1;\n"
11496                    "\n"
11497                    "int oneTwoThree = 123;",
11498                    Alignment));
11499   EXPECT_EQ("int a   = 5;\n"
11500             "int one = 1;\n"
11501             "\n"
11502             "int oneTwoThree = 123;\n"
11503             "int oneTwo      = 12;",
11504             format("int a = 5;\n"
11505                    "int one = 1;\n"
11506                    "\n"
11507                    "int oneTwoThree = 123;\n"
11508                    "int oneTwo = 12;",
11509                    Alignment));
11510   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
11511   verifyFormat("#define A \\\n"
11512                "  int aaaa       = 12; \\\n"
11513                "  int b          = 23; \\\n"
11514                "  int ccc        = 234; \\\n"
11515                "  int dddddddddd = 2345;",
11516                Alignment);
11517   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
11518   verifyFormat("#define A               \\\n"
11519                "  int aaaa       = 12;  \\\n"
11520                "  int b          = 23;  \\\n"
11521                "  int ccc        = 234; \\\n"
11522                "  int dddddddddd = 2345;",
11523                Alignment);
11524   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
11525   verifyFormat("#define A                                                      "
11526                "                \\\n"
11527                "  int aaaa       = 12;                                         "
11528                "                \\\n"
11529                "  int b          = 23;                                         "
11530                "                \\\n"
11531                "  int ccc        = 234;                                        "
11532                "                \\\n"
11533                "  int dddddddddd = 2345;",
11534                Alignment);
11535   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
11536                "k = 4, int l = 5,\n"
11537                "                  int m = 6) {\n"
11538                "  int j      = 10;\n"
11539                "  otherThing = 1;\n"
11540                "}",
11541                Alignment);
11542   verifyFormat("void SomeFunction(int parameter = 0) {\n"
11543                "  int i   = 1;\n"
11544                "  int j   = 2;\n"
11545                "  int big = 10000;\n"
11546                "}",
11547                Alignment);
11548   verifyFormat("class C {\n"
11549                "public:\n"
11550                "  int i            = 1;\n"
11551                "  virtual void f() = 0;\n"
11552                "};",
11553                Alignment);
11554   verifyFormat("int i = 1;\n"
11555                "if (SomeType t = getSomething()) {\n"
11556                "}\n"
11557                "int j   = 2;\n"
11558                "int big = 10000;",
11559                Alignment);
11560   verifyFormat("int j = 7;\n"
11561                "for (int k = 0; k < N; ++k) {\n"
11562                "}\n"
11563                "int j   = 2;\n"
11564                "int big = 10000;\n"
11565                "}",
11566                Alignment);
11567   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
11568   verifyFormat("int i = 1;\n"
11569                "LooooooooooongType loooooooooooooooooooooongVariable\n"
11570                "    = someLooooooooooooooooongFunction();\n"
11571                "int j = 2;",
11572                Alignment);
11573   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
11574   verifyFormat("int i = 1;\n"
11575                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
11576                "    someLooooooooooooooooongFunction();\n"
11577                "int j = 2;",
11578                Alignment);
11579 
11580   verifyFormat("auto lambda = []() {\n"
11581                "  auto i = 0;\n"
11582                "  return 0;\n"
11583                "};\n"
11584                "int i  = 0;\n"
11585                "auto v = type{\n"
11586                "    i = 1,   //\n"
11587                "    (i = 2), //\n"
11588                "    i = 3    //\n"
11589                "};",
11590                Alignment);
11591 
11592   verifyFormat(
11593       "int i      = 1;\n"
11594       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
11595       "                          loooooooooooooooooooooongParameterB);\n"
11596       "int j      = 2;",
11597       Alignment);
11598 
11599   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
11600                "          typename B   = very_long_type_name_1,\n"
11601                "          typename T_2 = very_long_type_name_2>\n"
11602                "auto foo() {}\n",
11603                Alignment);
11604   verifyFormat("int a, b = 1;\n"
11605                "int c  = 2;\n"
11606                "int dd = 3;\n",
11607                Alignment);
11608   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
11609                "float b[1][] = {{3.f}};\n",
11610                Alignment);
11611   verifyFormat("for (int i = 0; i < 1; i++)\n"
11612                "  int x = 1;\n",
11613                Alignment);
11614   verifyFormat("for (i = 0; i < 1; i++)\n"
11615                "  x = 1;\n"
11616                "y = 1;\n",
11617                Alignment);
11618 }
11619 
11620 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
11621   FormatStyle Alignment = getLLVMStyle();
11622   Alignment.AlignConsecutiveMacros = true;
11623   Alignment.AlignConsecutiveDeclarations = false;
11624   verifyFormat("float const a = 5;\n"
11625                "int oneTwoThree = 123;",
11626                Alignment);
11627   verifyFormat("int a = 5;\n"
11628                "float const oneTwoThree = 123;",
11629                Alignment);
11630 
11631   Alignment.AlignConsecutiveDeclarations = true;
11632   verifyFormat("float const a = 5;\n"
11633                "int         oneTwoThree = 123;",
11634                Alignment);
11635   verifyFormat("int         a = method();\n"
11636                "float const oneTwoThree = 133;",
11637                Alignment);
11638   verifyFormat("int i = 1, j = 10;\n"
11639                "something = 2000;",
11640                Alignment);
11641   verifyFormat("something = 2000;\n"
11642                "int i = 1, j = 10;\n",
11643                Alignment);
11644   verifyFormat("float      something = 2000;\n"
11645                "double     another = 911;\n"
11646                "int        i = 1, j = 10;\n"
11647                "const int *oneMore = 1;\n"
11648                "unsigned   i = 2;",
11649                Alignment);
11650   verifyFormat("float a = 5;\n"
11651                "int   one = 1;\n"
11652                "method();\n"
11653                "const double       oneTwoThree = 123;\n"
11654                "const unsigned int oneTwo = 12;",
11655                Alignment);
11656   verifyFormat("int      oneTwoThree{0}; // comment\n"
11657                "unsigned oneTwo;         // comment",
11658                Alignment);
11659   EXPECT_EQ("float const a = 5;\n"
11660             "\n"
11661             "int oneTwoThree = 123;",
11662             format("float const   a = 5;\n"
11663                    "\n"
11664                    "int           oneTwoThree= 123;",
11665                    Alignment));
11666   EXPECT_EQ("float a = 5;\n"
11667             "int   one = 1;\n"
11668             "\n"
11669             "unsigned oneTwoThree = 123;",
11670             format("float    a = 5;\n"
11671                    "int      one = 1;\n"
11672                    "\n"
11673                    "unsigned oneTwoThree = 123;",
11674                    Alignment));
11675   EXPECT_EQ("float a = 5;\n"
11676             "int   one = 1;\n"
11677             "\n"
11678             "unsigned oneTwoThree = 123;\n"
11679             "int      oneTwo = 12;",
11680             format("float    a = 5;\n"
11681                    "int one = 1;\n"
11682                    "\n"
11683                    "unsigned oneTwoThree = 123;\n"
11684                    "int oneTwo = 12;",
11685                    Alignment));
11686   // Function prototype alignment
11687   verifyFormat("int    a();\n"
11688                "double b();",
11689                Alignment);
11690   verifyFormat("int    a(int x);\n"
11691                "double b();",
11692                Alignment);
11693   unsigned OldColumnLimit = Alignment.ColumnLimit;
11694   // We need to set ColumnLimit to zero, in order to stress nested alignments,
11695   // otherwise the function parameters will be re-flowed onto a single line.
11696   Alignment.ColumnLimit = 0;
11697   EXPECT_EQ("int    a(int   x,\n"
11698             "         float y);\n"
11699             "double b(int    x,\n"
11700             "         double y);",
11701             format("int a(int x,\n"
11702                    " float y);\n"
11703                    "double b(int x,\n"
11704                    " double y);",
11705                    Alignment));
11706   // This ensures that function parameters of function declarations are
11707   // correctly indented when their owning functions are indented.
11708   // The failure case here is for 'double y' to not be indented enough.
11709   EXPECT_EQ("double a(int x);\n"
11710             "int    b(int    y,\n"
11711             "         double z);",
11712             format("double a(int x);\n"
11713                    "int b(int y,\n"
11714                    " double z);",
11715                    Alignment));
11716   // Set ColumnLimit low so that we induce wrapping immediately after
11717   // the function name and opening paren.
11718   Alignment.ColumnLimit = 13;
11719   verifyFormat("int function(\n"
11720                "    int  x,\n"
11721                "    bool y);",
11722                Alignment);
11723   Alignment.ColumnLimit = OldColumnLimit;
11724   // Ensure function pointers don't screw up recursive alignment
11725   verifyFormat("int    a(int x, void (*fp)(int y));\n"
11726                "double b();",
11727                Alignment);
11728   Alignment.AlignConsecutiveAssignments = true;
11729   // Ensure recursive alignment is broken by function braces, so that the
11730   // "a = 1" does not align with subsequent assignments inside the function
11731   // body.
11732   verifyFormat("int func(int a = 1) {\n"
11733                "  int b  = 2;\n"
11734                "  int cc = 3;\n"
11735                "}",
11736                Alignment);
11737   verifyFormat("float      something = 2000;\n"
11738                "double     another   = 911;\n"
11739                "int        i = 1, j = 10;\n"
11740                "const int *oneMore = 1;\n"
11741                "unsigned   i       = 2;",
11742                Alignment);
11743   verifyFormat("int      oneTwoThree = {0}; // comment\n"
11744                "unsigned oneTwo      = 0;   // comment",
11745                Alignment);
11746   // Make sure that scope is correctly tracked, in the absence of braces
11747   verifyFormat("for (int i = 0; i < n; i++)\n"
11748                "  j = i;\n"
11749                "double x = 1;\n",
11750                Alignment);
11751   verifyFormat("if (int i = 0)\n"
11752                "  j = i;\n"
11753                "double x = 1;\n",
11754                Alignment);
11755   // Ensure operator[] and operator() are comprehended
11756   verifyFormat("struct test {\n"
11757                "  long long int foo();\n"
11758                "  int           operator[](int a);\n"
11759                "  double        bar();\n"
11760                "};\n",
11761                Alignment);
11762   verifyFormat("struct test {\n"
11763                "  long long int foo();\n"
11764                "  int           operator()(int a);\n"
11765                "  double        bar();\n"
11766                "};\n",
11767                Alignment);
11768   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
11769             "  int const i   = 1;\n"
11770             "  int *     j   = 2;\n"
11771             "  int       big = 10000;\n"
11772             "\n"
11773             "  unsigned oneTwoThree = 123;\n"
11774             "  int      oneTwo      = 12;\n"
11775             "  method();\n"
11776             "  float k  = 2;\n"
11777             "  int   ll = 10000;\n"
11778             "}",
11779             format("void SomeFunction(int parameter= 0) {\n"
11780                    " int const  i= 1;\n"
11781                    "  int *j=2;\n"
11782                    " int big  =  10000;\n"
11783                    "\n"
11784                    "unsigned oneTwoThree  =123;\n"
11785                    "int oneTwo = 12;\n"
11786                    "  method();\n"
11787                    "float k= 2;\n"
11788                    "int ll=10000;\n"
11789                    "}",
11790                    Alignment));
11791   Alignment.AlignConsecutiveAssignments = false;
11792   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
11793   verifyFormat("#define A \\\n"
11794                "  int       aaaa = 12; \\\n"
11795                "  float     b = 23; \\\n"
11796                "  const int ccc = 234; \\\n"
11797                "  unsigned  dddddddddd = 2345;",
11798                Alignment);
11799   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
11800   verifyFormat("#define A              \\\n"
11801                "  int       aaaa = 12; \\\n"
11802                "  float     b = 23;    \\\n"
11803                "  const int ccc = 234; \\\n"
11804                "  unsigned  dddddddddd = 2345;",
11805                Alignment);
11806   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
11807   Alignment.ColumnLimit = 30;
11808   verifyFormat("#define A                    \\\n"
11809                "  int       aaaa = 12;       \\\n"
11810                "  float     b = 23;          \\\n"
11811                "  const int ccc = 234;       \\\n"
11812                "  int       dddddddddd = 2345;",
11813                Alignment);
11814   Alignment.ColumnLimit = 80;
11815   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
11816                "k = 4, int l = 5,\n"
11817                "                  int m = 6) {\n"
11818                "  const int j = 10;\n"
11819                "  otherThing = 1;\n"
11820                "}",
11821                Alignment);
11822   verifyFormat("void SomeFunction(int parameter = 0) {\n"
11823                "  int const i = 1;\n"
11824                "  int *     j = 2;\n"
11825                "  int       big = 10000;\n"
11826                "}",
11827                Alignment);
11828   verifyFormat("class C {\n"
11829                "public:\n"
11830                "  int          i = 1;\n"
11831                "  virtual void f() = 0;\n"
11832                "};",
11833                Alignment);
11834   verifyFormat("float i = 1;\n"
11835                "if (SomeType t = getSomething()) {\n"
11836                "}\n"
11837                "const unsigned j = 2;\n"
11838                "int            big = 10000;",
11839                Alignment);
11840   verifyFormat("float j = 7;\n"
11841                "for (int k = 0; k < N; ++k) {\n"
11842                "}\n"
11843                "unsigned j = 2;\n"
11844                "int      big = 10000;\n"
11845                "}",
11846                Alignment);
11847   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
11848   verifyFormat("float              i = 1;\n"
11849                "LooooooooooongType loooooooooooooooooooooongVariable\n"
11850                "    = someLooooooooooooooooongFunction();\n"
11851                "int j = 2;",
11852                Alignment);
11853   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
11854   verifyFormat("int                i = 1;\n"
11855                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
11856                "    someLooooooooooooooooongFunction();\n"
11857                "int j = 2;",
11858                Alignment);
11859 
11860   Alignment.AlignConsecutiveAssignments = true;
11861   verifyFormat("auto lambda = []() {\n"
11862                "  auto  ii = 0;\n"
11863                "  float j  = 0;\n"
11864                "  return 0;\n"
11865                "};\n"
11866                "int   i  = 0;\n"
11867                "float i2 = 0;\n"
11868                "auto  v  = type{\n"
11869                "    i = 1,   //\n"
11870                "    (i = 2), //\n"
11871                "    i = 3    //\n"
11872                "};",
11873                Alignment);
11874   Alignment.AlignConsecutiveAssignments = false;
11875 
11876   verifyFormat(
11877       "int      i = 1;\n"
11878       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
11879       "                          loooooooooooooooooooooongParameterB);\n"
11880       "int      j = 2;",
11881       Alignment);
11882 
11883   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
11884   // We expect declarations and assignments to align, as long as it doesn't
11885   // exceed the column limit, starting a new alignment sequence whenever it
11886   // happens.
11887   Alignment.AlignConsecutiveAssignments = true;
11888   Alignment.ColumnLimit = 30;
11889   verifyFormat("float    ii              = 1;\n"
11890                "unsigned j               = 2;\n"
11891                "int someVerylongVariable = 1;\n"
11892                "AnotherLongType  ll = 123456;\n"
11893                "VeryVeryLongType k  = 2;\n"
11894                "int              myvar = 1;",
11895                Alignment);
11896   Alignment.ColumnLimit = 80;
11897   Alignment.AlignConsecutiveAssignments = false;
11898 
11899   verifyFormat(
11900       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
11901       "          typename LongType, typename B>\n"
11902       "auto foo() {}\n",
11903       Alignment);
11904   verifyFormat("float a, b = 1;\n"
11905                "int   c = 2;\n"
11906                "int   dd = 3;\n",
11907                Alignment);
11908   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
11909                "float b[1][] = {{3.f}};\n",
11910                Alignment);
11911   Alignment.AlignConsecutiveAssignments = true;
11912   verifyFormat("float a, b = 1;\n"
11913                "int   c  = 2;\n"
11914                "int   dd = 3;\n",
11915                Alignment);
11916   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
11917                "float b[1][] = {{3.f}};\n",
11918                Alignment);
11919   Alignment.AlignConsecutiveAssignments = false;
11920 
11921   Alignment.ColumnLimit = 30;
11922   Alignment.BinPackParameters = false;
11923   verifyFormat("void foo(float     a,\n"
11924                "         float     b,\n"
11925                "         int       c,\n"
11926                "         uint32_t *d) {\n"
11927                "  int *  e = 0;\n"
11928                "  float  f = 0;\n"
11929                "  double g = 0;\n"
11930                "}\n"
11931                "void bar(ino_t     a,\n"
11932                "         int       b,\n"
11933                "         uint32_t *c,\n"
11934                "         bool      d) {}\n",
11935                Alignment);
11936   Alignment.BinPackParameters = true;
11937   Alignment.ColumnLimit = 80;
11938 
11939   // Bug 33507
11940   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
11941   verifyFormat(
11942       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
11943       "  static const Version verVs2017;\n"
11944       "  return true;\n"
11945       "});\n",
11946       Alignment);
11947   Alignment.PointerAlignment = FormatStyle::PAS_Right;
11948 
11949   // See llvm.org/PR35641
11950   Alignment.AlignConsecutiveDeclarations = true;
11951   verifyFormat("int func() { //\n"
11952                "  int      b;\n"
11953                "  unsigned c;\n"
11954                "}",
11955                Alignment);
11956 
11957   // See PR37175
11958   FormatStyle Style = getMozillaStyle();
11959   Style.AlignConsecutiveDeclarations = true;
11960   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
11961             "foo(int a);",
11962             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
11963 }
11964 
11965 TEST_F(FormatTest, LinuxBraceBreaking) {
11966   FormatStyle LinuxBraceStyle = getLLVMStyle();
11967   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
11968   verifyFormat("namespace a\n"
11969                "{\n"
11970                "class A\n"
11971                "{\n"
11972                "  void f()\n"
11973                "  {\n"
11974                "    if (true) {\n"
11975                "      a();\n"
11976                "      b();\n"
11977                "    } else {\n"
11978                "      a();\n"
11979                "    }\n"
11980                "  }\n"
11981                "  void g() { return; }\n"
11982                "};\n"
11983                "struct B {\n"
11984                "  int x;\n"
11985                "};\n"
11986                "} // namespace a\n",
11987                LinuxBraceStyle);
11988   verifyFormat("enum X {\n"
11989                "  Y = 0,\n"
11990                "}\n",
11991                LinuxBraceStyle);
11992   verifyFormat("struct S {\n"
11993                "  int Type;\n"
11994                "  union {\n"
11995                "    int x;\n"
11996                "    double y;\n"
11997                "  } Value;\n"
11998                "  class C\n"
11999                "  {\n"
12000                "    MyFavoriteType Value;\n"
12001                "  } Class;\n"
12002                "}\n",
12003                LinuxBraceStyle);
12004 }
12005 
12006 TEST_F(FormatTest, MozillaBraceBreaking) {
12007   FormatStyle MozillaBraceStyle = getLLVMStyle();
12008   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
12009   MozillaBraceStyle.FixNamespaceComments = false;
12010   verifyFormat("namespace a {\n"
12011                "class A\n"
12012                "{\n"
12013                "  void f()\n"
12014                "  {\n"
12015                "    if (true) {\n"
12016                "      a();\n"
12017                "      b();\n"
12018                "    }\n"
12019                "  }\n"
12020                "  void g() { return; }\n"
12021                "};\n"
12022                "enum E\n"
12023                "{\n"
12024                "  A,\n"
12025                "  // foo\n"
12026                "  B,\n"
12027                "  C\n"
12028                "};\n"
12029                "struct B\n"
12030                "{\n"
12031                "  int x;\n"
12032                "};\n"
12033                "}\n",
12034                MozillaBraceStyle);
12035   verifyFormat("struct S\n"
12036                "{\n"
12037                "  int Type;\n"
12038                "  union\n"
12039                "  {\n"
12040                "    int x;\n"
12041                "    double y;\n"
12042                "  } Value;\n"
12043                "  class C\n"
12044                "  {\n"
12045                "    MyFavoriteType Value;\n"
12046                "  } Class;\n"
12047                "}\n",
12048                MozillaBraceStyle);
12049 }
12050 
12051 TEST_F(FormatTest, StroustrupBraceBreaking) {
12052   FormatStyle StroustrupBraceStyle = getLLVMStyle();
12053   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
12054   verifyFormat("namespace a {\n"
12055                "class A {\n"
12056                "  void f()\n"
12057                "  {\n"
12058                "    if (true) {\n"
12059                "      a();\n"
12060                "      b();\n"
12061                "    }\n"
12062                "  }\n"
12063                "  void g() { return; }\n"
12064                "};\n"
12065                "struct B {\n"
12066                "  int x;\n"
12067                "};\n"
12068                "} // namespace a\n",
12069                StroustrupBraceStyle);
12070 
12071   verifyFormat("void foo()\n"
12072                "{\n"
12073                "  if (a) {\n"
12074                "    a();\n"
12075                "  }\n"
12076                "  else {\n"
12077                "    b();\n"
12078                "  }\n"
12079                "}\n",
12080                StroustrupBraceStyle);
12081 
12082   verifyFormat("#ifdef _DEBUG\n"
12083                "int foo(int i = 0)\n"
12084                "#else\n"
12085                "int foo(int i = 5)\n"
12086                "#endif\n"
12087                "{\n"
12088                "  return i;\n"
12089                "}",
12090                StroustrupBraceStyle);
12091 
12092   verifyFormat("void foo() {}\n"
12093                "void bar()\n"
12094                "#ifdef _DEBUG\n"
12095                "{\n"
12096                "  foo();\n"
12097                "}\n"
12098                "#else\n"
12099                "{\n"
12100                "}\n"
12101                "#endif",
12102                StroustrupBraceStyle);
12103 
12104   verifyFormat("void foobar() { int i = 5; }\n"
12105                "#ifdef _DEBUG\n"
12106                "void bar() {}\n"
12107                "#else\n"
12108                "void bar() { foobar(); }\n"
12109                "#endif",
12110                StroustrupBraceStyle);
12111 }
12112 
12113 TEST_F(FormatTest, AllmanBraceBreaking) {
12114   FormatStyle AllmanBraceStyle = getLLVMStyle();
12115   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
12116 
12117   EXPECT_EQ("namespace a\n"
12118             "{\n"
12119             "void f();\n"
12120             "void g();\n"
12121             "} // namespace a\n",
12122             format("namespace a\n"
12123                    "{\n"
12124                    "void f();\n"
12125                    "void g();\n"
12126                    "}\n",
12127                    AllmanBraceStyle));
12128 
12129   verifyFormat("namespace a\n"
12130                "{\n"
12131                "class A\n"
12132                "{\n"
12133                "  void f()\n"
12134                "  {\n"
12135                "    if (true)\n"
12136                "    {\n"
12137                "      a();\n"
12138                "      b();\n"
12139                "    }\n"
12140                "  }\n"
12141                "  void g() { return; }\n"
12142                "};\n"
12143                "struct B\n"
12144                "{\n"
12145                "  int x;\n"
12146                "};\n"
12147                "union C\n"
12148                "{\n"
12149                "};\n"
12150                "} // namespace a",
12151                AllmanBraceStyle);
12152 
12153   verifyFormat("void f()\n"
12154                "{\n"
12155                "  if (true)\n"
12156                "  {\n"
12157                "    a();\n"
12158                "  }\n"
12159                "  else if (false)\n"
12160                "  {\n"
12161                "    b();\n"
12162                "  }\n"
12163                "  else\n"
12164                "  {\n"
12165                "    c();\n"
12166                "  }\n"
12167                "}\n",
12168                AllmanBraceStyle);
12169 
12170   verifyFormat("void f()\n"
12171                "{\n"
12172                "  for (int i = 0; i < 10; ++i)\n"
12173                "  {\n"
12174                "    a();\n"
12175                "  }\n"
12176                "  while (false)\n"
12177                "  {\n"
12178                "    b();\n"
12179                "  }\n"
12180                "  do\n"
12181                "  {\n"
12182                "    c();\n"
12183                "  } while (false)\n"
12184                "}\n",
12185                AllmanBraceStyle);
12186 
12187   verifyFormat("void f(int a)\n"
12188                "{\n"
12189                "  switch (a)\n"
12190                "  {\n"
12191                "  case 0:\n"
12192                "    break;\n"
12193                "  case 1:\n"
12194                "  {\n"
12195                "    break;\n"
12196                "  }\n"
12197                "  case 2:\n"
12198                "  {\n"
12199                "  }\n"
12200                "  break;\n"
12201                "  default:\n"
12202                "    break;\n"
12203                "  }\n"
12204                "}\n",
12205                AllmanBraceStyle);
12206 
12207   verifyFormat("enum X\n"
12208                "{\n"
12209                "  Y = 0,\n"
12210                "}\n",
12211                AllmanBraceStyle);
12212   verifyFormat("enum X\n"
12213                "{\n"
12214                "  Y = 0\n"
12215                "}\n",
12216                AllmanBraceStyle);
12217 
12218   verifyFormat("@interface BSApplicationController ()\n"
12219                "{\n"
12220                "@private\n"
12221                "  id _extraIvar;\n"
12222                "}\n"
12223                "@end\n",
12224                AllmanBraceStyle);
12225 
12226   verifyFormat("#ifdef _DEBUG\n"
12227                "int foo(int i = 0)\n"
12228                "#else\n"
12229                "int foo(int i = 5)\n"
12230                "#endif\n"
12231                "{\n"
12232                "  return i;\n"
12233                "}",
12234                AllmanBraceStyle);
12235 
12236   verifyFormat("void foo() {}\n"
12237                "void bar()\n"
12238                "#ifdef _DEBUG\n"
12239                "{\n"
12240                "  foo();\n"
12241                "}\n"
12242                "#else\n"
12243                "{\n"
12244                "}\n"
12245                "#endif",
12246                AllmanBraceStyle);
12247 
12248   verifyFormat("void foobar() { int i = 5; }\n"
12249                "#ifdef _DEBUG\n"
12250                "void bar() {}\n"
12251                "#else\n"
12252                "void bar() { foobar(); }\n"
12253                "#endif",
12254                AllmanBraceStyle);
12255 
12256   // This shouldn't affect ObjC blocks..
12257   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
12258                "  // ...\n"
12259                "  int i;\n"
12260                "}];",
12261                AllmanBraceStyle);
12262   verifyFormat("void (^block)(void) = ^{\n"
12263                "  // ...\n"
12264                "  int i;\n"
12265                "};",
12266                AllmanBraceStyle);
12267   // .. or dict literals.
12268   verifyFormat("void f()\n"
12269                "{\n"
12270                "  // ...\n"
12271                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
12272                "}",
12273                AllmanBraceStyle);
12274   verifyFormat("void f()\n"
12275                "{\n"
12276                "  // ...\n"
12277                "  [object someMethod:@{a : @\"b\"}];\n"
12278                "}",
12279                AllmanBraceStyle);
12280   verifyFormat("int f()\n"
12281                "{ // comment\n"
12282                "  return 42;\n"
12283                "}",
12284                AllmanBraceStyle);
12285 
12286   AllmanBraceStyle.ColumnLimit = 19;
12287   verifyFormat("void f() { int i; }", AllmanBraceStyle);
12288   AllmanBraceStyle.ColumnLimit = 18;
12289   verifyFormat("void f()\n"
12290                "{\n"
12291                "  int i;\n"
12292                "}",
12293                AllmanBraceStyle);
12294   AllmanBraceStyle.ColumnLimit = 80;
12295 
12296   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
12297   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
12298       FormatStyle::SIS_WithoutElse;
12299   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
12300   verifyFormat("void f(bool b)\n"
12301                "{\n"
12302                "  if (b)\n"
12303                "  {\n"
12304                "    return;\n"
12305                "  }\n"
12306                "}\n",
12307                BreakBeforeBraceShortIfs);
12308   verifyFormat("void f(bool b)\n"
12309                "{\n"
12310                "  if constexpr (b)\n"
12311                "  {\n"
12312                "    return;\n"
12313                "  }\n"
12314                "}\n",
12315                BreakBeforeBraceShortIfs);
12316   verifyFormat("void f(bool b)\n"
12317                "{\n"
12318                "  if CONSTEXPR (b)\n"
12319                "  {\n"
12320                "    return;\n"
12321                "  }\n"
12322                "}\n",
12323                BreakBeforeBraceShortIfs);
12324   verifyFormat("void f(bool b)\n"
12325                "{\n"
12326                "  if (b) return;\n"
12327                "}\n",
12328                BreakBeforeBraceShortIfs);
12329   verifyFormat("void f(bool b)\n"
12330                "{\n"
12331                "  if constexpr (b) return;\n"
12332                "}\n",
12333                BreakBeforeBraceShortIfs);
12334   verifyFormat("void f(bool b)\n"
12335                "{\n"
12336                "  if CONSTEXPR (b) return;\n"
12337                "}\n",
12338                BreakBeforeBraceShortIfs);
12339   verifyFormat("void f(bool b)\n"
12340                "{\n"
12341                "  while (b)\n"
12342                "  {\n"
12343                "    return;\n"
12344                "  }\n"
12345                "}\n",
12346                BreakBeforeBraceShortIfs);
12347 }
12348 
12349 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
12350   FormatStyle WhitesmithsBraceStyle = getLLVMStyle();
12351   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
12352 
12353   // Make a few changes to the style for testing purposes
12354   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
12355       FormatStyle::SFS_Empty;
12356   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
12357   WhitesmithsBraceStyle.ColumnLimit = 0;
12358 
12359   // FIXME: this test case can't decide whether there should be a blank line
12360   // after the ~D() line or not. It adds one if one doesn't exist in the test
12361   // and it removes the line if one exists.
12362   /*
12363   verifyFormat("class A;\n"
12364                "namespace B\n"
12365                "  {\n"
12366                "class C;\n"
12367                "// Comment\n"
12368                "class D\n"
12369                "  {\n"
12370                "public:\n"
12371                "  D();\n"
12372                "  ~D() {}\n"
12373                "private:\n"
12374                "  enum E\n"
12375                "    {\n"
12376                "    F\n"
12377                "    }\n"
12378                "  };\n"
12379                "  } // namespace B\n",
12380                WhitesmithsBraceStyle);
12381   */
12382 
12383   verifyFormat("namespace a\n"
12384                "  {\n"
12385                "class A\n"
12386                "  {\n"
12387                "  void f()\n"
12388                "    {\n"
12389                "    if (true)\n"
12390                "      {\n"
12391                "      a();\n"
12392                "      b();\n"
12393                "      }\n"
12394                "    }\n"
12395                "  void g()\n"
12396                "    {\n"
12397                "    return;\n"
12398                "    }\n"
12399                "  };\n"
12400                "struct B\n"
12401                "  {\n"
12402                "  int x;\n"
12403                "  };\n"
12404                "  } // namespace a",
12405                WhitesmithsBraceStyle);
12406 
12407   verifyFormat("void f()\n"
12408                "  {\n"
12409                "  if (true)\n"
12410                "    {\n"
12411                "    a();\n"
12412                "    }\n"
12413                "  else if (false)\n"
12414                "    {\n"
12415                "    b();\n"
12416                "    }\n"
12417                "  else\n"
12418                "    {\n"
12419                "    c();\n"
12420                "    }\n"
12421                "  }\n",
12422                WhitesmithsBraceStyle);
12423 
12424   verifyFormat("void f()\n"
12425                "  {\n"
12426                "  for (int i = 0; i < 10; ++i)\n"
12427                "    {\n"
12428                "    a();\n"
12429                "    }\n"
12430                "  while (false)\n"
12431                "    {\n"
12432                "    b();\n"
12433                "    }\n"
12434                "  do\n"
12435                "    {\n"
12436                "    c();\n"
12437                "    } while (false)\n"
12438                "  }\n",
12439                WhitesmithsBraceStyle);
12440 
12441   // FIXME: the block and the break under case 2 in this test don't get indented
12442   // correctly
12443   /*
12444   verifyFormat("void switchTest1(int a)\n"
12445                "  {\n"
12446                "  switch (a)\n"
12447                "    {\n"
12448                "    case 2:\n"
12449                "      {\n"
12450                "      }\n"
12451                "      break;\n"
12452                "    }\n"
12453                "  }\n",
12454                WhitesmithsBraceStyle);
12455   */
12456 
12457   // FIXME: the block and the break under case 2 in this test don't get indented
12458   // correctly
12459   /*
12460   verifyFormat("void switchTest2(int a)\n"
12461                "  {\n"
12462                "  switch (a)\n"
12463                "    {\n"
12464                "  case 0:\n"
12465                "    break;\n"
12466                "  case 1:\n"
12467                "    {\n"
12468                "    break;\n"
12469                "    }\n"
12470                "  case 2:\n"
12471                "    {\n"
12472                "    }\n"
12473                "    break;\n"
12474                "  default:\n"
12475                "    break;\n"
12476                "    }\n"
12477                "  }\n",
12478                WhitesmithsBraceStyle);
12479   */
12480 
12481   verifyFormat("enum X\n"
12482                "  {\n"
12483                "  Y = 0, // testing\n"
12484                "  }\n",
12485                WhitesmithsBraceStyle);
12486 
12487   verifyFormat("enum X\n"
12488                "  {\n"
12489                "  Y = 0\n"
12490                "  }\n",
12491                WhitesmithsBraceStyle);
12492   verifyFormat("enum X\n"
12493                "  {\n"
12494                "  Y = 0,\n"
12495                "  Z = 1\n"
12496                "  };\n",
12497                WhitesmithsBraceStyle);
12498 
12499   verifyFormat("@interface BSApplicationController ()\n"
12500                "  {\n"
12501                "@private\n"
12502                "  id _extraIvar;\n"
12503                "  }\n"
12504                "@end\n",
12505                WhitesmithsBraceStyle);
12506 
12507   verifyFormat("#ifdef _DEBUG\n"
12508                "int foo(int i = 0)\n"
12509                "#else\n"
12510                "int foo(int i = 5)\n"
12511                "#endif\n"
12512                "  {\n"
12513                "  return i;\n"
12514                "  }",
12515                WhitesmithsBraceStyle);
12516 
12517   verifyFormat("void foo() {}\n"
12518                "void bar()\n"
12519                "#ifdef _DEBUG\n"
12520                "  {\n"
12521                "  foo();\n"
12522                "  }\n"
12523                "#else\n"
12524                "  {\n"
12525                "  }\n"
12526                "#endif",
12527                WhitesmithsBraceStyle);
12528 
12529   verifyFormat("void foobar()\n"
12530                "  {\n"
12531                "  int i = 5;\n"
12532                "  }\n"
12533                "#ifdef _DEBUG\n"
12534                "void bar()\n"
12535                "  {\n"
12536                "  }\n"
12537                "#else\n"
12538                "void bar()\n"
12539                "  {\n"
12540                "  foobar();\n"
12541                "  }\n"
12542                "#endif",
12543                WhitesmithsBraceStyle);
12544 
12545   // This shouldn't affect ObjC blocks..
12546   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
12547                "  // ...\n"
12548                "  int i;\n"
12549                "}];",
12550                WhitesmithsBraceStyle);
12551   verifyFormat("void (^block)(void) = ^{\n"
12552                "  // ...\n"
12553                "  int i;\n"
12554                "};",
12555                WhitesmithsBraceStyle);
12556   // .. or dict literals.
12557   verifyFormat("void f()\n"
12558                "  {\n"
12559                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
12560                "  }",
12561                WhitesmithsBraceStyle);
12562 
12563   verifyFormat("int f()\n"
12564                "  { // comment\n"
12565                "  return 42;\n"
12566                "  }",
12567                WhitesmithsBraceStyle);
12568 
12569   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
12570   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
12571       FormatStyle::SIS_Always;
12572   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
12573   verifyFormat("void f(bool b)\n"
12574                "  {\n"
12575                "  if (b)\n"
12576                "    {\n"
12577                "    return;\n"
12578                "    }\n"
12579                "  }\n",
12580                BreakBeforeBraceShortIfs);
12581   verifyFormat("void f(bool b)\n"
12582                "  {\n"
12583                "  if (b) return;\n"
12584                "  }\n",
12585                BreakBeforeBraceShortIfs);
12586   verifyFormat("void f(bool b)\n"
12587                "  {\n"
12588                "  while (b)\n"
12589                "    {\n"
12590                "    return;\n"
12591                "    }\n"
12592                "  }\n",
12593                BreakBeforeBraceShortIfs);
12594 }
12595 
12596 TEST_F(FormatTest, GNUBraceBreaking) {
12597   FormatStyle GNUBraceStyle = getLLVMStyle();
12598   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
12599   verifyFormat("namespace a\n"
12600                "{\n"
12601                "class A\n"
12602                "{\n"
12603                "  void f()\n"
12604                "  {\n"
12605                "    int a;\n"
12606                "    {\n"
12607                "      int b;\n"
12608                "    }\n"
12609                "    if (true)\n"
12610                "      {\n"
12611                "        a();\n"
12612                "        b();\n"
12613                "      }\n"
12614                "  }\n"
12615                "  void g() { return; }\n"
12616                "}\n"
12617                "} // namespace a",
12618                GNUBraceStyle);
12619 
12620   verifyFormat("void f()\n"
12621                "{\n"
12622                "  if (true)\n"
12623                "    {\n"
12624                "      a();\n"
12625                "    }\n"
12626                "  else if (false)\n"
12627                "    {\n"
12628                "      b();\n"
12629                "    }\n"
12630                "  else\n"
12631                "    {\n"
12632                "      c();\n"
12633                "    }\n"
12634                "}\n",
12635                GNUBraceStyle);
12636 
12637   verifyFormat("void f()\n"
12638                "{\n"
12639                "  for (int i = 0; i < 10; ++i)\n"
12640                "    {\n"
12641                "      a();\n"
12642                "    }\n"
12643                "  while (false)\n"
12644                "    {\n"
12645                "      b();\n"
12646                "    }\n"
12647                "  do\n"
12648                "    {\n"
12649                "      c();\n"
12650                "    }\n"
12651                "  while (false);\n"
12652                "}\n",
12653                GNUBraceStyle);
12654 
12655   verifyFormat("void f(int a)\n"
12656                "{\n"
12657                "  switch (a)\n"
12658                "    {\n"
12659                "    case 0:\n"
12660                "      break;\n"
12661                "    case 1:\n"
12662                "      {\n"
12663                "        break;\n"
12664                "      }\n"
12665                "    case 2:\n"
12666                "      {\n"
12667                "      }\n"
12668                "      break;\n"
12669                "    default:\n"
12670                "      break;\n"
12671                "    }\n"
12672                "}\n",
12673                GNUBraceStyle);
12674 
12675   verifyFormat("enum X\n"
12676                "{\n"
12677                "  Y = 0,\n"
12678                "}\n",
12679                GNUBraceStyle);
12680 
12681   verifyFormat("@interface BSApplicationController ()\n"
12682                "{\n"
12683                "@private\n"
12684                "  id _extraIvar;\n"
12685                "}\n"
12686                "@end\n",
12687                GNUBraceStyle);
12688 
12689   verifyFormat("#ifdef _DEBUG\n"
12690                "int foo(int i = 0)\n"
12691                "#else\n"
12692                "int foo(int i = 5)\n"
12693                "#endif\n"
12694                "{\n"
12695                "  return i;\n"
12696                "}",
12697                GNUBraceStyle);
12698 
12699   verifyFormat("void foo() {}\n"
12700                "void bar()\n"
12701                "#ifdef _DEBUG\n"
12702                "{\n"
12703                "  foo();\n"
12704                "}\n"
12705                "#else\n"
12706                "{\n"
12707                "}\n"
12708                "#endif",
12709                GNUBraceStyle);
12710 
12711   verifyFormat("void foobar() { int i = 5; }\n"
12712                "#ifdef _DEBUG\n"
12713                "void bar() {}\n"
12714                "#else\n"
12715                "void bar() { foobar(); }\n"
12716                "#endif",
12717                GNUBraceStyle);
12718 }
12719 
12720 TEST_F(FormatTest, WebKitBraceBreaking) {
12721   FormatStyle WebKitBraceStyle = getLLVMStyle();
12722   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
12723   WebKitBraceStyle.FixNamespaceComments = false;
12724   verifyFormat("namespace a {\n"
12725                "class A {\n"
12726                "  void f()\n"
12727                "  {\n"
12728                "    if (true) {\n"
12729                "      a();\n"
12730                "      b();\n"
12731                "    }\n"
12732                "  }\n"
12733                "  void g() { return; }\n"
12734                "};\n"
12735                "enum E {\n"
12736                "  A,\n"
12737                "  // foo\n"
12738                "  B,\n"
12739                "  C\n"
12740                "};\n"
12741                "struct B {\n"
12742                "  int x;\n"
12743                "};\n"
12744                "}\n",
12745                WebKitBraceStyle);
12746   verifyFormat("struct S {\n"
12747                "  int Type;\n"
12748                "  union {\n"
12749                "    int x;\n"
12750                "    double y;\n"
12751                "  } Value;\n"
12752                "  class C {\n"
12753                "    MyFavoriteType Value;\n"
12754                "  } Class;\n"
12755                "};\n",
12756                WebKitBraceStyle);
12757 }
12758 
12759 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
12760   verifyFormat("void f() {\n"
12761                "  try {\n"
12762                "  } catch (const Exception &e) {\n"
12763                "  }\n"
12764                "}\n",
12765                getLLVMStyle());
12766 }
12767 
12768 TEST_F(FormatTest, UnderstandsPragmas) {
12769   verifyFormat("#pragma omp reduction(| : var)");
12770   verifyFormat("#pragma omp reduction(+ : var)");
12771 
12772   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
12773             "(including parentheses).",
12774             format("#pragma    mark   Any non-hyphenated or hyphenated string "
12775                    "(including parentheses)."));
12776 }
12777 
12778 TEST_F(FormatTest, UnderstandPragmaOption) {
12779   verifyFormat("#pragma option -C -A");
12780 
12781   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
12782 }
12783 
12784 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
12785   FormatStyle Style = getLLVMStyle();
12786   Style.ColumnLimit = 20;
12787 
12788   // See PR41213
12789   EXPECT_EQ("/*\n"
12790             " *\t9012345\n"
12791             " * /8901\n"
12792             " */",
12793             format("/*\n"
12794                    " *\t9012345 /8901\n"
12795                    " */",
12796                    Style));
12797   EXPECT_EQ("/*\n"
12798             " *345678\n"
12799             " *\t/8901\n"
12800             " */",
12801             format("/*\n"
12802                    " *345678\t/8901\n"
12803                    " */",
12804                    Style));
12805 
12806   verifyFormat("int a; // the\n"
12807                "       // comment",
12808                Style);
12809   EXPECT_EQ("int a; /* first line\n"
12810             "        * second\n"
12811             "        * line third\n"
12812             "        * line\n"
12813             "        */",
12814             format("int a; /* first line\n"
12815                    "        * second\n"
12816                    "        * line third\n"
12817                    "        * line\n"
12818                    "        */",
12819                    Style));
12820   EXPECT_EQ("int a; // first line\n"
12821             "       // second\n"
12822             "       // line third\n"
12823             "       // line",
12824             format("int a; // first line\n"
12825                    "       // second line\n"
12826                    "       // third line",
12827                    Style));
12828 
12829   Style.PenaltyExcessCharacter = 90;
12830   verifyFormat("int a; // the comment", Style);
12831   EXPECT_EQ("int a; // the comment\n"
12832             "       // aaa",
12833             format("int a; // the comment aaa", Style));
12834   EXPECT_EQ("int a; /* first line\n"
12835             "        * second line\n"
12836             "        * third line\n"
12837             "        */",
12838             format("int a; /* first line\n"
12839                    "        * second line\n"
12840                    "        * third line\n"
12841                    "        */",
12842                    Style));
12843   EXPECT_EQ("int a; // first line\n"
12844             "       // second line\n"
12845             "       // third line",
12846             format("int a; // first line\n"
12847                    "       // second line\n"
12848                    "       // third line",
12849                    Style));
12850   // FIXME: Investigate why this is not getting the same layout as the test
12851   // above.
12852   EXPECT_EQ("int a; /* first line\n"
12853             "        * second line\n"
12854             "        * third line\n"
12855             "        */",
12856             format("int a; /* first line second line third line"
12857                    "\n*/",
12858                    Style));
12859 
12860   EXPECT_EQ("// foo bar baz bazfoo\n"
12861             "// foo bar foo bar\n",
12862             format("// foo bar baz bazfoo\n"
12863                    "// foo bar foo           bar\n",
12864                    Style));
12865   EXPECT_EQ("// foo bar baz bazfoo\n"
12866             "// foo bar foo bar\n",
12867             format("// foo bar baz      bazfoo\n"
12868                    "// foo            bar foo bar\n",
12869                    Style));
12870 
12871   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
12872   // next one.
12873   EXPECT_EQ("// foo bar baz bazfoo\n"
12874             "// bar foo bar\n",
12875             format("// foo bar baz      bazfoo bar\n"
12876                    "// foo            bar\n",
12877                    Style));
12878 
12879   EXPECT_EQ("// foo bar baz bazfoo\n"
12880             "// foo bar baz bazfoo\n"
12881             "// bar foo bar\n",
12882             format("// foo bar baz      bazfoo\n"
12883                    "// foo bar baz      bazfoo bar\n"
12884                    "// foo bar\n",
12885                    Style));
12886 
12887   EXPECT_EQ("// foo bar baz bazfoo\n"
12888             "// foo bar baz bazfoo\n"
12889             "// bar foo bar\n",
12890             format("// foo bar baz      bazfoo\n"
12891                    "// foo bar baz      bazfoo bar\n"
12892                    "// foo           bar\n",
12893                    Style));
12894 
12895   // Make sure we do not keep protruding characters if strict mode reflow is
12896   // cheaper than keeping protruding characters.
12897   Style.ColumnLimit = 21;
12898   EXPECT_EQ(
12899       "// foo foo foo foo\n"
12900       "// foo foo foo foo\n"
12901       "// foo foo foo foo\n",
12902       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
12903 
12904   EXPECT_EQ("int a = /* long block\n"
12905             "           comment */\n"
12906             "    42;",
12907             format("int a = /* long block comment */ 42;", Style));
12908 }
12909 
12910 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
12911   for (size_t i = 1; i < Styles.size(); ++i)                                   \
12912   EXPECT_EQ(Styles[0], Styles[i])                                              \
12913       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
12914 
12915 TEST_F(FormatTest, GetsPredefinedStyleByName) {
12916   SmallVector<FormatStyle, 3> Styles;
12917   Styles.resize(3);
12918 
12919   Styles[0] = getLLVMStyle();
12920   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
12921   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
12922   EXPECT_ALL_STYLES_EQUAL(Styles);
12923 
12924   Styles[0] = getGoogleStyle();
12925   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
12926   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
12927   EXPECT_ALL_STYLES_EQUAL(Styles);
12928 
12929   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
12930   EXPECT_TRUE(
12931       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
12932   EXPECT_TRUE(
12933       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
12934   EXPECT_ALL_STYLES_EQUAL(Styles);
12935 
12936   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
12937   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
12938   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
12939   EXPECT_ALL_STYLES_EQUAL(Styles);
12940 
12941   Styles[0] = getMozillaStyle();
12942   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
12943   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
12944   EXPECT_ALL_STYLES_EQUAL(Styles);
12945 
12946   Styles[0] = getWebKitStyle();
12947   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
12948   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
12949   EXPECT_ALL_STYLES_EQUAL(Styles);
12950 
12951   Styles[0] = getGNUStyle();
12952   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
12953   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
12954   EXPECT_ALL_STYLES_EQUAL(Styles);
12955 
12956   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
12957 }
12958 
12959 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
12960   SmallVector<FormatStyle, 8> Styles;
12961   Styles.resize(2);
12962 
12963   Styles[0] = getGoogleStyle();
12964   Styles[1] = getLLVMStyle();
12965   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
12966   EXPECT_ALL_STYLES_EQUAL(Styles);
12967 
12968   Styles.resize(5);
12969   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
12970   Styles[1] = getLLVMStyle();
12971   Styles[1].Language = FormatStyle::LK_JavaScript;
12972   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
12973 
12974   Styles[2] = getLLVMStyle();
12975   Styles[2].Language = FormatStyle::LK_JavaScript;
12976   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
12977                                   "BasedOnStyle: Google",
12978                                   &Styles[2])
12979                    .value());
12980 
12981   Styles[3] = getLLVMStyle();
12982   Styles[3].Language = FormatStyle::LK_JavaScript;
12983   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
12984                                   "Language: JavaScript",
12985                                   &Styles[3])
12986                    .value());
12987 
12988   Styles[4] = getLLVMStyle();
12989   Styles[4].Language = FormatStyle::LK_JavaScript;
12990   EXPECT_EQ(0, parseConfiguration("---\n"
12991                                   "BasedOnStyle: LLVM\n"
12992                                   "IndentWidth: 123\n"
12993                                   "---\n"
12994                                   "BasedOnStyle: Google\n"
12995                                   "Language: JavaScript",
12996                                   &Styles[4])
12997                    .value());
12998   EXPECT_ALL_STYLES_EQUAL(Styles);
12999 }
13000 
13001 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
13002   Style.FIELD = false;                                                         \
13003   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
13004   EXPECT_TRUE(Style.FIELD);                                                    \
13005   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
13006   EXPECT_FALSE(Style.FIELD);
13007 
13008 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
13009 
13010 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
13011   Style.STRUCT.FIELD = false;                                                  \
13012   EXPECT_EQ(0,                                                                 \
13013             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
13014                 .value());                                                     \
13015   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
13016   EXPECT_EQ(0,                                                                 \
13017             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
13018                 .value());                                                     \
13019   EXPECT_FALSE(Style.STRUCT.FIELD);
13020 
13021 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
13022   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
13023 
13024 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
13025   EXPECT_NE(VALUE, Style.FIELD);                                               \
13026   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
13027   EXPECT_EQ(VALUE, Style.FIELD)
13028 
13029 TEST_F(FormatTest, ParsesConfigurationBools) {
13030   FormatStyle Style = {};
13031   Style.Language = FormatStyle::LK_Cpp;
13032   CHECK_PARSE_BOOL(AlignOperands);
13033   CHECK_PARSE_BOOL(AlignTrailingComments);
13034   CHECK_PARSE_BOOL(AlignConsecutiveAssignments);
13035   CHECK_PARSE_BOOL(AlignConsecutiveDeclarations);
13036   CHECK_PARSE_BOOL(AlignConsecutiveMacros);
13037   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
13038   CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine);
13039   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
13040   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
13041   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
13042   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
13043   CHECK_PARSE_BOOL(BinPackArguments);
13044   CHECK_PARSE_BOOL(BinPackParameters);
13045   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
13046   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
13047   CHECK_PARSE_BOOL(BreakStringLiterals);
13048   CHECK_PARSE_BOOL(CompactNamespaces);
13049   CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
13050   CHECK_PARSE_BOOL(DeriveLineEnding);
13051   CHECK_PARSE_BOOL(DerivePointerAlignment);
13052   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
13053   CHECK_PARSE_BOOL(DisableFormat);
13054   CHECK_PARSE_BOOL(IndentCaseLabels);
13055   CHECK_PARSE_BOOL(IndentCaseBlocks);
13056   CHECK_PARSE_BOOL(IndentGotoLabels);
13057   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
13058   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
13059   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
13060   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
13061   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
13062   CHECK_PARSE_BOOL(ReflowComments);
13063   CHECK_PARSE_BOOL(SortIncludes);
13064   CHECK_PARSE_BOOL(SortUsingDeclarations);
13065   CHECK_PARSE_BOOL(SpacesInParentheses);
13066   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
13067   CHECK_PARSE_BOOL(SpacesInAngles);
13068   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
13069   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
13070   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
13071   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
13072   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
13073   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
13074   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
13075   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
13076   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
13077   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
13078   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
13079   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
13080   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
13081   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
13082   CHECK_PARSE_BOOL(UseCRLF);
13083 
13084   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
13085   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
13086   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
13087   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
13088   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
13089   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
13090   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
13091   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
13092   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
13093   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
13094   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
13095   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
13096   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
13097   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
13098   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
13099   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
13100 }
13101 
13102 #undef CHECK_PARSE_BOOL
13103 
13104 TEST_F(FormatTest, ParsesConfiguration) {
13105   FormatStyle Style = {};
13106   Style.Language = FormatStyle::LK_Cpp;
13107   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
13108   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
13109               ConstructorInitializerIndentWidth, 1234u);
13110   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
13111   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
13112   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
13113   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
13114   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
13115               PenaltyBreakBeforeFirstCallParameter, 1234u);
13116   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
13117               PenaltyBreakTemplateDeclaration, 1234u);
13118   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
13119   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
13120               PenaltyReturnTypeOnItsOwnLine, 1234u);
13121   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
13122               SpacesBeforeTrailingComments, 1234u);
13123   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
13124   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
13125   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
13126 
13127   Style.PointerAlignment = FormatStyle::PAS_Middle;
13128   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
13129               FormatStyle::PAS_Left);
13130   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
13131               FormatStyle::PAS_Right);
13132   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
13133               FormatStyle::PAS_Middle);
13134   // For backward compatibility:
13135   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
13136               FormatStyle::PAS_Left);
13137   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
13138               FormatStyle::PAS_Right);
13139   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
13140               FormatStyle::PAS_Middle);
13141 
13142   Style.Standard = FormatStyle::LS_Auto;
13143   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
13144   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
13145   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
13146   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
13147   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
13148   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
13149   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
13150   // Legacy aliases:
13151   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
13152   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
13153   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
13154   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
13155 
13156   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
13157   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
13158               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
13159   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
13160               FormatStyle::BOS_None);
13161   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
13162               FormatStyle::BOS_All);
13163   // For backward compatibility:
13164   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
13165               FormatStyle::BOS_None);
13166   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
13167               FormatStyle::BOS_All);
13168 
13169   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
13170   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
13171               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
13172   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
13173               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
13174   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
13175               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
13176   // For backward compatibility:
13177   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
13178               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
13179 
13180   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
13181   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
13182               FormatStyle::BILS_BeforeComma);
13183   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
13184               FormatStyle::BILS_AfterColon);
13185   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
13186               FormatStyle::BILS_BeforeColon);
13187   // For backward compatibility:
13188   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
13189               FormatStyle::BILS_BeforeComma);
13190 
13191   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13192   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
13193               FormatStyle::BAS_Align);
13194   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
13195               FormatStyle::BAS_DontAlign);
13196   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
13197               FormatStyle::BAS_AlwaysBreak);
13198   // For backward compatibility:
13199   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
13200               FormatStyle::BAS_DontAlign);
13201   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
13202               FormatStyle::BAS_Align);
13203 
13204   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
13205   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
13206               FormatStyle::ENAS_DontAlign);
13207   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
13208               FormatStyle::ENAS_Left);
13209   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
13210               FormatStyle::ENAS_Right);
13211   // For backward compatibility:
13212   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
13213               FormatStyle::ENAS_Left);
13214   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
13215               FormatStyle::ENAS_Right);
13216 
13217   Style.UseTab = FormatStyle::UT_ForIndentation;
13218   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
13219   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
13220   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
13221   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
13222               FormatStyle::UT_ForContinuationAndIndentation);
13223   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
13224               FormatStyle::UT_AlignWithSpaces);
13225   // For backward compatibility:
13226   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
13227   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
13228 
13229   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
13230   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
13231               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
13232   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
13233               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
13234   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
13235               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
13236   // For backward compatibility:
13237   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
13238               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
13239   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
13240               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
13241 
13242   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
13243   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
13244               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
13245   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
13246               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
13247   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
13248               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
13249   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
13250               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
13251   // For backward compatibility:
13252   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
13253               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
13254   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
13255               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
13256 
13257   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
13258   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
13259               FormatStyle::SBPO_Never);
13260   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
13261               FormatStyle::SBPO_Always);
13262   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
13263               FormatStyle::SBPO_ControlStatements);
13264   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
13265               FormatStyle::SBPO_NonEmptyParentheses);
13266   // For backward compatibility:
13267   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
13268               FormatStyle::SBPO_Never);
13269   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
13270               FormatStyle::SBPO_ControlStatements);
13271 
13272   Style.ColumnLimit = 123;
13273   FormatStyle BaseStyle = getLLVMStyle();
13274   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
13275   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
13276 
13277   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
13278   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
13279               FormatStyle::BS_Attach);
13280   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
13281               FormatStyle::BS_Linux);
13282   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
13283               FormatStyle::BS_Mozilla);
13284   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
13285               FormatStyle::BS_Stroustrup);
13286   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
13287               FormatStyle::BS_Allman);
13288   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
13289               FormatStyle::BS_Whitesmiths);
13290   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
13291   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
13292               FormatStyle::BS_WebKit);
13293   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
13294               FormatStyle::BS_Custom);
13295 
13296   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
13297   CHECK_PARSE("BraceWrapping:\n"
13298               "  AfterControlStatement: MultiLine",
13299               BraceWrapping.AfterControlStatement,
13300               FormatStyle::BWACS_MultiLine);
13301   CHECK_PARSE("BraceWrapping:\n"
13302               "  AfterControlStatement: Always",
13303               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
13304   CHECK_PARSE("BraceWrapping:\n"
13305               "  AfterControlStatement: Never",
13306               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
13307   // For backward compatibility:
13308   CHECK_PARSE("BraceWrapping:\n"
13309               "  AfterControlStatement: true",
13310               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
13311   CHECK_PARSE("BraceWrapping:\n"
13312               "  AfterControlStatement: false",
13313               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
13314 
13315   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
13316   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
13317               FormatStyle::RTBS_None);
13318   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
13319               FormatStyle::RTBS_All);
13320   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
13321               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
13322   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
13323               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
13324   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
13325               AlwaysBreakAfterReturnType,
13326               FormatStyle::RTBS_TopLevelDefinitions);
13327 
13328   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
13329   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
13330               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
13331   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
13332               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
13333   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
13334               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
13335   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
13336               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
13337   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
13338               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
13339 
13340   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
13341   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
13342               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
13343   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
13344               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
13345   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
13346               AlwaysBreakAfterDefinitionReturnType,
13347               FormatStyle::DRTBS_TopLevel);
13348 
13349   Style.NamespaceIndentation = FormatStyle::NI_All;
13350   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
13351               FormatStyle::NI_None);
13352   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
13353               FormatStyle::NI_Inner);
13354   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
13355               FormatStyle::NI_All);
13356 
13357   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
13358   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
13359               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
13360   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
13361               AllowShortIfStatementsOnASingleLine,
13362               FormatStyle::SIS_WithoutElse);
13363   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
13364               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Always);
13365   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
13366               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
13367   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
13368               AllowShortIfStatementsOnASingleLine,
13369               FormatStyle::SIS_WithoutElse);
13370 
13371   // FIXME: This is required because parsing a configuration simply overwrites
13372   // the first N elements of the list instead of resetting it.
13373   Style.ForEachMacros.clear();
13374   std::vector<std::string> BoostForeach;
13375   BoostForeach.push_back("BOOST_FOREACH");
13376   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
13377   std::vector<std::string> BoostAndQForeach;
13378   BoostAndQForeach.push_back("BOOST_FOREACH");
13379   BoostAndQForeach.push_back("Q_FOREACH");
13380   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
13381               BoostAndQForeach);
13382 
13383   Style.StatementMacros.clear();
13384   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
13385               std::vector<std::string>{"QUNUSED"});
13386   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
13387               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
13388 
13389   Style.NamespaceMacros.clear();
13390   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
13391               std::vector<std::string>{"TESTSUITE"});
13392   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
13393               std::vector<std::string>({"TESTSUITE", "SUITE"}));
13394 
13395   Style.IncludeStyle.IncludeCategories.clear();
13396   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
13397       {"abc/.*", 2, 0}, {".*", 1, 0}};
13398   CHECK_PARSE("IncludeCategories:\n"
13399               "  - Regex: abc/.*\n"
13400               "    Priority: 2\n"
13401               "  - Regex: .*\n"
13402               "    Priority: 1",
13403               IncludeStyle.IncludeCategories, ExpectedCategories);
13404   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
13405               "abc$");
13406   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
13407               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
13408 
13409   Style.RawStringFormats.clear();
13410   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
13411       {
13412           FormatStyle::LK_TextProto,
13413           {"pb", "proto"},
13414           {"PARSE_TEXT_PROTO"},
13415           /*CanonicalDelimiter=*/"",
13416           "llvm",
13417       },
13418       {
13419           FormatStyle::LK_Cpp,
13420           {"cc", "cpp"},
13421           {"C_CODEBLOCK", "CPPEVAL"},
13422           /*CanonicalDelimiter=*/"cc",
13423           /*BasedOnStyle=*/"",
13424       },
13425   };
13426 
13427   CHECK_PARSE("RawStringFormats:\n"
13428               "  - Language: TextProto\n"
13429               "    Delimiters:\n"
13430               "      - 'pb'\n"
13431               "      - 'proto'\n"
13432               "    EnclosingFunctions:\n"
13433               "      - 'PARSE_TEXT_PROTO'\n"
13434               "    BasedOnStyle: llvm\n"
13435               "  - Language: Cpp\n"
13436               "    Delimiters:\n"
13437               "      - 'cc'\n"
13438               "      - 'cpp'\n"
13439               "    EnclosingFunctions:\n"
13440               "      - 'C_CODEBLOCK'\n"
13441               "      - 'CPPEVAL'\n"
13442               "    CanonicalDelimiter: 'cc'",
13443               RawStringFormats, ExpectedRawStringFormats);
13444 }
13445 
13446 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
13447   FormatStyle Style = {};
13448   Style.Language = FormatStyle::LK_Cpp;
13449   CHECK_PARSE("Language: Cpp\n"
13450               "IndentWidth: 12",
13451               IndentWidth, 12u);
13452   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
13453                                "IndentWidth: 34",
13454                                &Style),
13455             ParseError::Unsuitable);
13456   FormatStyle BinPackedTCS = {};
13457   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
13458   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
13459                                "InsertTrailingCommas: Wrapped",
13460                                &BinPackedTCS),
13461             ParseError::BinPackTrailingCommaConflict);
13462   EXPECT_EQ(12u, Style.IndentWidth);
13463   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
13464   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
13465 
13466   Style.Language = FormatStyle::LK_JavaScript;
13467   CHECK_PARSE("Language: JavaScript\n"
13468               "IndentWidth: 12",
13469               IndentWidth, 12u);
13470   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
13471   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
13472                                "IndentWidth: 34",
13473                                &Style),
13474             ParseError::Unsuitable);
13475   EXPECT_EQ(23u, Style.IndentWidth);
13476   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
13477   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
13478 
13479   CHECK_PARSE("BasedOnStyle: LLVM\n"
13480               "IndentWidth: 67",
13481               IndentWidth, 67u);
13482 
13483   CHECK_PARSE("---\n"
13484               "Language: JavaScript\n"
13485               "IndentWidth: 12\n"
13486               "---\n"
13487               "Language: Cpp\n"
13488               "IndentWidth: 34\n"
13489               "...\n",
13490               IndentWidth, 12u);
13491 
13492   Style.Language = FormatStyle::LK_Cpp;
13493   CHECK_PARSE("---\n"
13494               "Language: JavaScript\n"
13495               "IndentWidth: 12\n"
13496               "---\n"
13497               "Language: Cpp\n"
13498               "IndentWidth: 34\n"
13499               "...\n",
13500               IndentWidth, 34u);
13501   CHECK_PARSE("---\n"
13502               "IndentWidth: 78\n"
13503               "---\n"
13504               "Language: JavaScript\n"
13505               "IndentWidth: 56\n"
13506               "...\n",
13507               IndentWidth, 78u);
13508 
13509   Style.ColumnLimit = 123;
13510   Style.IndentWidth = 234;
13511   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
13512   Style.TabWidth = 345;
13513   EXPECT_FALSE(parseConfiguration("---\n"
13514                                   "IndentWidth: 456\n"
13515                                   "BreakBeforeBraces: Allman\n"
13516                                   "---\n"
13517                                   "Language: JavaScript\n"
13518                                   "IndentWidth: 111\n"
13519                                   "TabWidth: 111\n"
13520                                   "---\n"
13521                                   "Language: Cpp\n"
13522                                   "BreakBeforeBraces: Stroustrup\n"
13523                                   "TabWidth: 789\n"
13524                                   "...\n",
13525                                   &Style));
13526   EXPECT_EQ(123u, Style.ColumnLimit);
13527   EXPECT_EQ(456u, Style.IndentWidth);
13528   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
13529   EXPECT_EQ(789u, Style.TabWidth);
13530 
13531   EXPECT_EQ(parseConfiguration("---\n"
13532                                "Language: JavaScript\n"
13533                                "IndentWidth: 56\n"
13534                                "---\n"
13535                                "IndentWidth: 78\n"
13536                                "...\n",
13537                                &Style),
13538             ParseError::Error);
13539   EXPECT_EQ(parseConfiguration("---\n"
13540                                "Language: JavaScript\n"
13541                                "IndentWidth: 56\n"
13542                                "---\n"
13543                                "Language: JavaScript\n"
13544                                "IndentWidth: 78\n"
13545                                "...\n",
13546                                &Style),
13547             ParseError::Error);
13548 
13549   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
13550 }
13551 
13552 #undef CHECK_PARSE
13553 
13554 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
13555   FormatStyle Style = {};
13556   Style.Language = FormatStyle::LK_JavaScript;
13557   Style.BreakBeforeTernaryOperators = true;
13558   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
13559   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
13560 
13561   Style.BreakBeforeTernaryOperators = true;
13562   EXPECT_EQ(0, parseConfiguration("---\n"
13563                                   "BasedOnStyle: Google\n"
13564                                   "---\n"
13565                                   "Language: JavaScript\n"
13566                                   "IndentWidth: 76\n"
13567                                   "...\n",
13568                                   &Style)
13569                    .value());
13570   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
13571   EXPECT_EQ(76u, Style.IndentWidth);
13572   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
13573 }
13574 
13575 TEST_F(FormatTest, ConfigurationRoundTripTest) {
13576   FormatStyle Style = getLLVMStyle();
13577   std::string YAML = configurationAsText(Style);
13578   FormatStyle ParsedStyle = {};
13579   ParsedStyle.Language = FormatStyle::LK_Cpp;
13580   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
13581   EXPECT_EQ(Style, ParsedStyle);
13582 }
13583 
13584 TEST_F(FormatTest, WorksFor8bitEncodings) {
13585   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
13586             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
13587             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
13588             "\"\xef\xee\xf0\xf3...\"",
13589             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
13590                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
13591                    "\xef\xee\xf0\xf3...\"",
13592                    getLLVMStyleWithColumns(12)));
13593 }
13594 
13595 TEST_F(FormatTest, HandlesUTF8BOM) {
13596   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
13597   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
13598             format("\xef\xbb\xbf#include <iostream>"));
13599   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
13600             format("\xef\xbb\xbf\n#include <iostream>"));
13601 }
13602 
13603 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
13604 #if !defined(_MSC_VER)
13605 
13606 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
13607   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
13608                getLLVMStyleWithColumns(35));
13609   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
13610                getLLVMStyleWithColumns(31));
13611   verifyFormat("// Однажды в студёную зимнюю пору...",
13612                getLLVMStyleWithColumns(36));
13613   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
13614   verifyFormat("/* Однажды в студёную зимнюю пору... */",
13615                getLLVMStyleWithColumns(39));
13616   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
13617                getLLVMStyleWithColumns(35));
13618 }
13619 
13620 TEST_F(FormatTest, SplitsUTF8Strings) {
13621   // Non-printable characters' width is currently considered to be the length in
13622   // bytes in UTF8. The characters can be displayed in very different manner
13623   // (zero-width, single width with a substitution glyph, expanded to their code
13624   // (e.g. "<8d>"), so there's no single correct way to handle them.
13625   EXPECT_EQ("\"aaaaÄ\"\n"
13626             "\"\xc2\x8d\";",
13627             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
13628   EXPECT_EQ("\"aaaaaaaÄ\"\n"
13629             "\"\xc2\x8d\";",
13630             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
13631   EXPECT_EQ("\"Однажды, в \"\n"
13632             "\"студёную \"\n"
13633             "\"зимнюю \"\n"
13634             "\"пору,\"",
13635             format("\"Однажды, в студёную зимнюю пору,\"",
13636                    getLLVMStyleWithColumns(13)));
13637   EXPECT_EQ(
13638       "\"一 二 三 \"\n"
13639       "\"四 五六 \"\n"
13640       "\"七 八 九 \"\n"
13641       "\"十\"",
13642       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
13643   EXPECT_EQ("\"一\t\"\n"
13644             "\"二 \t\"\n"
13645             "\"三 四 \"\n"
13646             "\"五\t\"\n"
13647             "\"六 \t\"\n"
13648             "\"七 \"\n"
13649             "\"八九十\tqq\"",
13650             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
13651                    getLLVMStyleWithColumns(11)));
13652 
13653   // UTF8 character in an escape sequence.
13654   EXPECT_EQ("\"aaaaaa\"\n"
13655             "\"\\\xC2\x8D\"",
13656             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
13657 }
13658 
13659 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
13660   EXPECT_EQ("const char *sssss =\n"
13661             "    \"一二三四五六七八\\\n"
13662             " 九 十\";",
13663             format("const char *sssss = \"一二三四五六七八\\\n"
13664                    " 九 十\";",
13665                    getLLVMStyleWithColumns(30)));
13666 }
13667 
13668 TEST_F(FormatTest, SplitsUTF8LineComments) {
13669   EXPECT_EQ("// aaaaÄ\xc2\x8d",
13670             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
13671   EXPECT_EQ("// Я из лесу\n"
13672             "// вышел; был\n"
13673             "// сильный\n"
13674             "// мороз.",
13675             format("// Я из лесу вышел; был сильный мороз.",
13676                    getLLVMStyleWithColumns(13)));
13677   EXPECT_EQ("// 一二三\n"
13678             "// 四五六七\n"
13679             "// 八  九\n"
13680             "// 十",
13681             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
13682 }
13683 
13684 TEST_F(FormatTest, SplitsUTF8BlockComments) {
13685   EXPECT_EQ("/* Гляжу,\n"
13686             " * поднимается\n"
13687             " * медленно в\n"
13688             " * гору\n"
13689             " * Лошадка,\n"
13690             " * везущая\n"
13691             " * хворосту\n"
13692             " * воз. */",
13693             format("/* Гляжу, поднимается медленно в гору\n"
13694                    " * Лошадка, везущая хворосту воз. */",
13695                    getLLVMStyleWithColumns(13)));
13696   EXPECT_EQ(
13697       "/* 一二三\n"
13698       " * 四五六七\n"
13699       " * 八  九\n"
13700       " * 十  */",
13701       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
13702   EXPECT_EQ("/* �������� ��������\n"
13703             " * ��������\n"
13704             " * ������-�� */",
13705             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
13706 }
13707 
13708 #endif // _MSC_VER
13709 
13710 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
13711   FormatStyle Style = getLLVMStyle();
13712 
13713   Style.ConstructorInitializerIndentWidth = 4;
13714   verifyFormat(
13715       "SomeClass::Constructor()\n"
13716       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
13717       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
13718       Style);
13719 
13720   Style.ConstructorInitializerIndentWidth = 2;
13721   verifyFormat(
13722       "SomeClass::Constructor()\n"
13723       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
13724       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
13725       Style);
13726 
13727   Style.ConstructorInitializerIndentWidth = 0;
13728   verifyFormat(
13729       "SomeClass::Constructor()\n"
13730       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
13731       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
13732       Style);
13733   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
13734   verifyFormat(
13735       "SomeLongTemplateVariableName<\n"
13736       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
13737       Style);
13738   verifyFormat("bool smaller = 1 < "
13739                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
13740                "                       "
13741                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
13742                Style);
13743 
13744   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
13745   verifyFormat("SomeClass::Constructor() :\n"
13746                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
13747                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
13748                Style);
13749 }
13750 
13751 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
13752   FormatStyle Style = getLLVMStyle();
13753   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
13754   Style.ConstructorInitializerIndentWidth = 4;
13755   verifyFormat("SomeClass::Constructor()\n"
13756                "    : a(a)\n"
13757                "    , b(b)\n"
13758                "    , c(c) {}",
13759                Style);
13760   verifyFormat("SomeClass::Constructor()\n"
13761                "    : a(a) {}",
13762                Style);
13763 
13764   Style.ColumnLimit = 0;
13765   verifyFormat("SomeClass::Constructor()\n"
13766                "    : a(a) {}",
13767                Style);
13768   verifyFormat("SomeClass::Constructor() noexcept\n"
13769                "    : a(a) {}",
13770                Style);
13771   verifyFormat("SomeClass::Constructor()\n"
13772                "    : a(a)\n"
13773                "    , b(b)\n"
13774                "    , c(c) {}",
13775                Style);
13776   verifyFormat("SomeClass::Constructor()\n"
13777                "    : a(a) {\n"
13778                "  foo();\n"
13779                "  bar();\n"
13780                "}",
13781                Style);
13782 
13783   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
13784   verifyFormat("SomeClass::Constructor()\n"
13785                "    : a(a)\n"
13786                "    , b(b)\n"
13787                "    , c(c) {\n}",
13788                Style);
13789   verifyFormat("SomeClass::Constructor()\n"
13790                "    : a(a) {\n}",
13791                Style);
13792 
13793   Style.ColumnLimit = 80;
13794   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
13795   Style.ConstructorInitializerIndentWidth = 2;
13796   verifyFormat("SomeClass::Constructor()\n"
13797                "  : a(a)\n"
13798                "  , b(b)\n"
13799                "  , c(c) {}",
13800                Style);
13801 
13802   Style.ConstructorInitializerIndentWidth = 0;
13803   verifyFormat("SomeClass::Constructor()\n"
13804                ": a(a)\n"
13805                ", b(b)\n"
13806                ", c(c) {}",
13807                Style);
13808 
13809   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
13810   Style.ConstructorInitializerIndentWidth = 4;
13811   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
13812   verifyFormat(
13813       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
13814       Style);
13815   verifyFormat(
13816       "SomeClass::Constructor()\n"
13817       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
13818       Style);
13819   Style.ConstructorInitializerIndentWidth = 4;
13820   Style.ColumnLimit = 60;
13821   verifyFormat("SomeClass::Constructor()\n"
13822                "    : aaaaaaaa(aaaaaaaa)\n"
13823                "    , aaaaaaaa(aaaaaaaa)\n"
13824                "    , aaaaaaaa(aaaaaaaa) {}",
13825                Style);
13826 }
13827 
13828 TEST_F(FormatTest, Destructors) {
13829   verifyFormat("void F(int &i) { i.~int(); }");
13830   verifyFormat("void F(int &i) { i->~int(); }");
13831 }
13832 
13833 TEST_F(FormatTest, FormatsWithWebKitStyle) {
13834   FormatStyle Style = getWebKitStyle();
13835 
13836   // Don't indent in outer namespaces.
13837   verifyFormat("namespace outer {\n"
13838                "int i;\n"
13839                "namespace inner {\n"
13840                "    int i;\n"
13841                "} // namespace inner\n"
13842                "} // namespace outer\n"
13843                "namespace other_outer {\n"
13844                "int i;\n"
13845                "}",
13846                Style);
13847 
13848   // Don't indent case labels.
13849   verifyFormat("switch (variable) {\n"
13850                "case 1:\n"
13851                "case 2:\n"
13852                "    doSomething();\n"
13853                "    break;\n"
13854                "default:\n"
13855                "    ++variable;\n"
13856                "}",
13857                Style);
13858 
13859   // Wrap before binary operators.
13860   EXPECT_EQ("void f()\n"
13861             "{\n"
13862             "    if (aaaaaaaaaaaaaaaa\n"
13863             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
13864             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
13865             "        return;\n"
13866             "}",
13867             format("void f() {\n"
13868                    "if (aaaaaaaaaaaaaaaa\n"
13869                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
13870                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
13871                    "return;\n"
13872                    "}",
13873                    Style));
13874 
13875   // Allow functions on a single line.
13876   verifyFormat("void f() { return; }", Style);
13877 
13878   // Allow empty blocks on a single line and insert a space in empty blocks.
13879   EXPECT_EQ("void f() { }", format("void f() {}", Style));
13880   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
13881   // However, don't merge non-empty short loops.
13882   EXPECT_EQ("while (true) {\n"
13883             "    continue;\n"
13884             "}",
13885             format("while (true) { continue; }", Style));
13886 
13887   // Constructor initializers are formatted one per line with the "," on the
13888   // new line.
13889   verifyFormat("Constructor()\n"
13890                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
13891                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
13892                "          aaaaaaaaaaaaaa)\n"
13893                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
13894                "{\n"
13895                "}",
13896                Style);
13897   verifyFormat("SomeClass::Constructor()\n"
13898                "    : a(a)\n"
13899                "{\n"
13900                "}",
13901                Style);
13902   EXPECT_EQ("SomeClass::Constructor()\n"
13903             "    : a(a)\n"
13904             "{\n"
13905             "}",
13906             format("SomeClass::Constructor():a(a){}", Style));
13907   verifyFormat("SomeClass::Constructor()\n"
13908                "    : a(a)\n"
13909                "    , b(b)\n"
13910                "    , c(c)\n"
13911                "{\n"
13912                "}",
13913                Style);
13914   verifyFormat("SomeClass::Constructor()\n"
13915                "    : a(a)\n"
13916                "{\n"
13917                "    foo();\n"
13918                "    bar();\n"
13919                "}",
13920                Style);
13921 
13922   // Access specifiers should be aligned left.
13923   verifyFormat("class C {\n"
13924                "public:\n"
13925                "    int i;\n"
13926                "};",
13927                Style);
13928 
13929   // Do not align comments.
13930   verifyFormat("int a; // Do not\n"
13931                "double b; // align comments.",
13932                Style);
13933 
13934   // Do not align operands.
13935   EXPECT_EQ("ASSERT(aaaa\n"
13936             "    || bbbb);",
13937             format("ASSERT ( aaaa\n||bbbb);", Style));
13938 
13939   // Accept input's line breaks.
13940   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
13941             "    || bbbbbbbbbbbbbbb) {\n"
13942             "    i++;\n"
13943             "}",
13944             format("if (aaaaaaaaaaaaaaa\n"
13945                    "|| bbbbbbbbbbbbbbb) { i++; }",
13946                    Style));
13947   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
13948             "    i++;\n"
13949             "}",
13950             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
13951 
13952   // Don't automatically break all macro definitions (llvm.org/PR17842).
13953   verifyFormat("#define aNumber 10", Style);
13954   // However, generally keep the line breaks that the user authored.
13955   EXPECT_EQ("#define aNumber \\\n"
13956             "    10",
13957             format("#define aNumber \\\n"
13958                    " 10",
13959                    Style));
13960 
13961   // Keep empty and one-element array literals on a single line.
13962   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
13963             "                                  copyItems:YES];",
13964             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
13965                    "copyItems:YES];",
13966                    Style));
13967   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
13968             "                                  copyItems:YES];",
13969             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
13970                    "             copyItems:YES];",
13971                    Style));
13972   // FIXME: This does not seem right, there should be more indentation before
13973   // the array literal's entries. Nested blocks have the same problem.
13974   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
13975             "    @\"a\",\n"
13976             "    @\"a\"\n"
13977             "]\n"
13978             "                                  copyItems:YES];",
13979             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
13980                    "     @\"a\",\n"
13981                    "     @\"a\"\n"
13982                    "     ]\n"
13983                    "       copyItems:YES];",
13984                    Style));
13985   EXPECT_EQ(
13986       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
13987       "                                  copyItems:YES];",
13988       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
13989              "   copyItems:YES];",
13990              Style));
13991 
13992   verifyFormat("[self.a b:c c:d];", Style);
13993   EXPECT_EQ("[self.a b:c\n"
13994             "        c:d];",
13995             format("[self.a b:c\n"
13996                    "c:d];",
13997                    Style));
13998 }
13999 
14000 TEST_F(FormatTest, FormatsLambdas) {
14001   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
14002   verifyFormat(
14003       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
14004   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
14005   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
14006   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
14007   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
14008   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
14009   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
14010   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
14011   verifyFormat("int x = f(*+[] {});");
14012   verifyFormat("void f() {\n"
14013                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
14014                "}\n");
14015   verifyFormat("void f() {\n"
14016                "  other(x.begin(), //\n"
14017                "        x.end(),   //\n"
14018                "        [&](int, int) { return 1; });\n"
14019                "}\n");
14020   verifyFormat("void f() {\n"
14021                "  other.other.other.other.other(\n"
14022                "      x.begin(), x.end(),\n"
14023                "      [something, rather](int, int, int, int, int, int, int) { "
14024                "return 1; });\n"
14025                "}\n");
14026   verifyFormat(
14027       "void f() {\n"
14028       "  other.other.other.other.other(\n"
14029       "      x.begin(), x.end(),\n"
14030       "      [something, rather](int, int, int, int, int, int, int) {\n"
14031       "        //\n"
14032       "      });\n"
14033       "}\n");
14034   verifyFormat("SomeFunction([]() { // A cool function...\n"
14035                "  return 43;\n"
14036                "});");
14037   EXPECT_EQ("SomeFunction([]() {\n"
14038             "#define A a\n"
14039             "  return 43;\n"
14040             "});",
14041             format("SomeFunction([](){\n"
14042                    "#define A a\n"
14043                    "return 43;\n"
14044                    "});"));
14045   verifyFormat("void f() {\n"
14046                "  SomeFunction([](decltype(x), A *a) {});\n"
14047                "}");
14048   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
14049                "    [](const aaaaaaaaaa &a) { return a; });");
14050   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
14051                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
14052                "});");
14053   verifyFormat("Constructor()\n"
14054                "    : Field([] { // comment\n"
14055                "        int i;\n"
14056                "      }) {}");
14057   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
14058                "  return some_parameter.size();\n"
14059                "};");
14060   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
14061                "    [](const string &s) { return s; };");
14062   verifyFormat("int i = aaaaaa ? 1 //\n"
14063                "               : [] {\n"
14064                "                   return 2; //\n"
14065                "                 }();");
14066   verifyFormat("llvm::errs() << \"number of twos is \"\n"
14067                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
14068                "                  return x == 2; // force break\n"
14069                "                });");
14070   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
14071                "    [=](int iiiiiiiiiiii) {\n"
14072                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
14073                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
14074                "    });",
14075                getLLVMStyleWithColumns(60));
14076   verifyFormat("SomeFunction({[&] {\n"
14077                "                // comment\n"
14078                "              },\n"
14079                "              [&] {\n"
14080                "                // comment\n"
14081                "              }});");
14082   verifyFormat("SomeFunction({[&] {\n"
14083                "  // comment\n"
14084                "}});");
14085   verifyFormat(
14086       "virtual aaaaaaaaaaaaaaaa(\n"
14087       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
14088       "    aaaaa aaaaaaaaa);");
14089 
14090   // Lambdas with return types.
14091   verifyFormat("int c = []() -> int { return 2; }();\n");
14092   verifyFormat("int c = []() -> int * { return 2; }();\n");
14093   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
14094   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
14095   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
14096   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
14097   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
14098   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
14099   verifyFormat("[a, a]() -> a<1> {};");
14100   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
14101   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
14102   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
14103   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
14104   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
14105   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
14106   verifyFormat("[]() -> foo<!5> { return {}; };");
14107   verifyFormat("[]() -> foo<~5> { return {}; };");
14108   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
14109   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
14110   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
14111   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
14112   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
14113   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
14114   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
14115   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
14116   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
14117   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
14118   verifyFormat("namespace bar {\n"
14119                "// broken:\n"
14120                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
14121                "} // namespace bar");
14122   verifyFormat("namespace bar {\n"
14123                "// broken:\n"
14124                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
14125                "} // namespace bar");
14126   verifyFormat("namespace bar {\n"
14127                "// broken:\n"
14128                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
14129                "} // namespace bar");
14130   verifyFormat("namespace bar {\n"
14131                "// broken:\n"
14132                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
14133                "} // namespace bar");
14134   verifyFormat("namespace bar {\n"
14135                "// broken:\n"
14136                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
14137                "} // namespace bar");
14138   verifyFormat("namespace bar {\n"
14139                "// broken:\n"
14140                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
14141                "} // namespace bar");
14142   verifyFormat("namespace bar {\n"
14143                "// broken:\n"
14144                "auto foo{[]() -> foo<!5> { return {}; }};\n"
14145                "} // namespace bar");
14146   verifyFormat("namespace bar {\n"
14147                "// broken:\n"
14148                "auto foo{[]() -> foo<~5> { return {}; }};\n"
14149                "} // namespace bar");
14150   verifyFormat("namespace bar {\n"
14151                "// broken:\n"
14152                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
14153                "} // namespace bar");
14154   verifyFormat("namespace bar {\n"
14155                "// broken:\n"
14156                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
14157                "} // namespace bar");
14158   verifyFormat("namespace bar {\n"
14159                "// broken:\n"
14160                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
14161                "} // namespace bar");
14162   verifyFormat("namespace bar {\n"
14163                "// broken:\n"
14164                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
14165                "} // namespace bar");
14166   verifyFormat("namespace bar {\n"
14167                "// broken:\n"
14168                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
14169                "} // namespace bar");
14170   verifyFormat("namespace bar {\n"
14171                "// broken:\n"
14172                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
14173                "} // namespace bar");
14174   verifyFormat("namespace bar {\n"
14175                "// broken:\n"
14176                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
14177                "} // namespace bar");
14178   verifyFormat("namespace bar {\n"
14179                "// broken:\n"
14180                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
14181                "} // namespace bar");
14182   verifyFormat("namespace bar {\n"
14183                "// broken:\n"
14184                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
14185                "} // namespace bar");
14186   verifyFormat("namespace bar {\n"
14187                "// broken:\n"
14188                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
14189                "} // namespace bar");
14190   verifyFormat("[]() -> a<1> {};");
14191   verifyFormat("[]() -> a<1> { ; };");
14192   verifyFormat("[]() -> a<1> { ; }();");
14193   verifyFormat("[a, a]() -> a<true> {};");
14194   verifyFormat("[]() -> a<true> {};");
14195   verifyFormat("[]() -> a<true> { ; };");
14196   verifyFormat("[]() -> a<true> { ; }();");
14197   verifyFormat("[a, a]() -> a<false> {};");
14198   verifyFormat("[]() -> a<false> {};");
14199   verifyFormat("[]() -> a<false> { ; };");
14200   verifyFormat("[]() -> a<false> { ; }();");
14201   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
14202   verifyFormat("namespace bar {\n"
14203                "auto foo{[]() -> foo<false> { ; }};\n"
14204                "} // namespace bar");
14205   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
14206                "                   int j) -> int {\n"
14207                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
14208                "};");
14209   verifyFormat(
14210       "aaaaaaaaaaaaaaaaaaaaaa(\n"
14211       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
14212       "      return aaaaaaaaaaaaaaaaa;\n"
14213       "    });",
14214       getLLVMStyleWithColumns(70));
14215   verifyFormat("[]() //\n"
14216                "    -> int {\n"
14217                "  return 1; //\n"
14218                "};");
14219   verifyFormat("[]() -> Void<T...> {};");
14220   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
14221 
14222   // Lambdas with explicit template argument lists.
14223   verifyFormat(
14224       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
14225 
14226   // Multiple lambdas in the same parentheses change indentation rules. These
14227   // lambdas are forced to start on new lines.
14228   verifyFormat("SomeFunction(\n"
14229                "    []() {\n"
14230                "      //\n"
14231                "    },\n"
14232                "    []() {\n"
14233                "      //\n"
14234                "    });");
14235 
14236   // A lambda passed as arg0 is always pushed to the next line.
14237   verifyFormat("SomeFunction(\n"
14238                "    [this] {\n"
14239                "      //\n"
14240                "    },\n"
14241                "    1);\n");
14242 
14243   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
14244   // the arg0 case above.
14245   auto Style = getGoogleStyle();
14246   Style.BinPackArguments = false;
14247   verifyFormat("SomeFunction(\n"
14248                "    a,\n"
14249                "    [this] {\n"
14250                "      //\n"
14251                "    },\n"
14252                "    b);\n",
14253                Style);
14254   verifyFormat("SomeFunction(\n"
14255                "    a,\n"
14256                "    [this] {\n"
14257                "      //\n"
14258                "    },\n"
14259                "    b);\n");
14260 
14261   // A lambda with a very long line forces arg0 to be pushed out irrespective of
14262   // the BinPackArguments value (as long as the code is wide enough).
14263   verifyFormat(
14264       "something->SomeFunction(\n"
14265       "    a,\n"
14266       "    [this] {\n"
14267       "      "
14268       "D0000000000000000000000000000000000000000000000000000000000001();\n"
14269       "    },\n"
14270       "    b);\n");
14271 
14272   // A multi-line lambda is pulled up as long as the introducer fits on the
14273   // previous line and there are no further args.
14274   verifyFormat("function(1, [this, that] {\n"
14275                "  //\n"
14276                "});\n");
14277   verifyFormat("function([this, that] {\n"
14278                "  //\n"
14279                "});\n");
14280   // FIXME: this format is not ideal and we should consider forcing the first
14281   // arg onto its own line.
14282   verifyFormat("function(a, b, c, //\n"
14283                "         d, [this, that] {\n"
14284                "           //\n"
14285                "         });\n");
14286 
14287   // Multiple lambdas are treated correctly even when there is a short arg0.
14288   verifyFormat("SomeFunction(\n"
14289                "    1,\n"
14290                "    [this] {\n"
14291                "      //\n"
14292                "    },\n"
14293                "    [this] {\n"
14294                "      //\n"
14295                "    },\n"
14296                "    1);\n");
14297 
14298   // More complex introducers.
14299   verifyFormat("return [i, args...] {};");
14300 
14301   // Not lambdas.
14302   verifyFormat("constexpr char hello[]{\"hello\"};");
14303   verifyFormat("double &operator[](int i) { return 0; }\n"
14304                "int i;");
14305   verifyFormat("std::unique_ptr<int[]> foo() {}");
14306   verifyFormat("int i = a[a][a]->f();");
14307   verifyFormat("int i = (*b)[a]->f();");
14308 
14309   // Other corner cases.
14310   verifyFormat("void f() {\n"
14311                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
14312                "  );\n"
14313                "}");
14314 
14315   // Lambdas created through weird macros.
14316   verifyFormat("void f() {\n"
14317                "  MACRO((const AA &a) { return 1; });\n"
14318                "  MACRO((AA &a) { return 1; });\n"
14319                "}");
14320 
14321   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
14322                "      doo_dah();\n"
14323                "      doo_dah();\n"
14324                "    })) {\n"
14325                "}");
14326   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
14327                "                doo_dah();\n"
14328                "                doo_dah();\n"
14329                "              })) {\n"
14330                "}");
14331   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
14332                "                doo_dah();\n"
14333                "                doo_dah();\n"
14334                "              })) {\n"
14335                "}");
14336   verifyFormat("auto lambda = []() {\n"
14337                "  int a = 2\n"
14338                "#if A\n"
14339                "          + 2\n"
14340                "#endif\n"
14341                "      ;\n"
14342                "};");
14343 
14344   // Lambdas with complex multiline introducers.
14345   verifyFormat(
14346       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
14347       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
14348       "        -> ::std::unordered_set<\n"
14349       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
14350       "      //\n"
14351       "    });");
14352 
14353   FormatStyle DoNotMerge = getLLVMStyle();
14354   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
14355   verifyFormat("auto c = []() {\n"
14356                "  return b;\n"
14357                "};",
14358                "auto c = []() { return b; };", DoNotMerge);
14359   verifyFormat("auto c = []() {\n"
14360                "};",
14361                " auto c = []() {};", DoNotMerge);
14362 
14363   FormatStyle MergeEmptyOnly = getLLVMStyle();
14364   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
14365   verifyFormat("auto c = []() {\n"
14366                "  return b;\n"
14367                "};",
14368                "auto c = []() {\n"
14369                "  return b;\n"
14370                " };",
14371                MergeEmptyOnly);
14372   verifyFormat("auto c = []() {};",
14373                "auto c = []() {\n"
14374                "};",
14375                MergeEmptyOnly);
14376 
14377   FormatStyle MergeInline = getLLVMStyle();
14378   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
14379   verifyFormat("auto c = []() {\n"
14380                "  return b;\n"
14381                "};",
14382                "auto c = []() { return b; };", MergeInline);
14383   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
14384                MergeInline);
14385   verifyFormat("function([]() { return b; }, a)",
14386                "function([]() { return b; }, a)", MergeInline);
14387   verifyFormat("function(a, []() { return b; })",
14388                "function(a, []() { return b; })", MergeInline);
14389 
14390   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
14391   // AllowShortLambdasOnASingleLine
14392   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
14393   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
14394   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
14395   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
14396       FormatStyle::ShortLambdaStyle::SLS_None;
14397   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
14398                "    []()\n"
14399                "    {\n"
14400                "      return 17;\n"
14401                "    });",
14402                LLVMWithBeforeLambdaBody);
14403   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
14404                "    []()\n"
14405                "    {\n"
14406                "    });",
14407                LLVMWithBeforeLambdaBody);
14408   verifyFormat("auto fct_SLS_None = []()\n"
14409                "{\n"
14410                "  return 17;\n"
14411                "};",
14412                LLVMWithBeforeLambdaBody);
14413   verifyFormat("TwoNestedLambdas_SLS_None(\n"
14414                "    []()\n"
14415                "    {\n"
14416                "      return Call(\n"
14417                "          []()\n"
14418                "          {\n"
14419                "            return 17;\n"
14420                "          });\n"
14421                "    });",
14422                LLVMWithBeforeLambdaBody);
14423   verifyFormat("void Fct()\n"
14424                "{\n"
14425                "  return {[]()\n"
14426                "          {\n"
14427                "            return 17;\n"
14428                "          }};\n"
14429                "}",
14430                LLVMWithBeforeLambdaBody);
14431 
14432   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
14433       FormatStyle::ShortLambdaStyle::SLS_Empty;
14434   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
14435                "    []()\n"
14436                "    {\n"
14437                "      return 17;\n"
14438                "    });",
14439                LLVMWithBeforeLambdaBody);
14440   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
14441                LLVMWithBeforeLambdaBody);
14442   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
14443                "ongFunctionName_SLS_Empty(\n"
14444                "    []() {});",
14445                LLVMWithBeforeLambdaBody);
14446   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
14447                "                                []()\n"
14448                "                                {\n"
14449                "                                  return 17;\n"
14450                "                                });",
14451                LLVMWithBeforeLambdaBody);
14452   verifyFormat("auto fct_SLS_Empty = []()\n"
14453                "{\n"
14454                "  return 17;\n"
14455                "};",
14456                LLVMWithBeforeLambdaBody);
14457   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
14458                "    []()\n"
14459                "    {\n"
14460                "      return Call([]() {});\n"
14461                "    });",
14462                LLVMWithBeforeLambdaBody);
14463   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
14464                "                           []()\n"
14465                "                           {\n"
14466                "                             return Call([]() {});\n"
14467                "                           });",
14468                LLVMWithBeforeLambdaBody);
14469   verifyFormat(
14470       "FctWithLongLineInLambda_SLS_Empty(\n"
14471       "    []()\n"
14472       "    {\n"
14473       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
14474       "                               AndShouldNotBeConsiderAsInline,\n"
14475       "                               LambdaBodyMustBeBreak);\n"
14476       "    });",
14477       LLVMWithBeforeLambdaBody);
14478 
14479   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
14480       FormatStyle::ShortLambdaStyle::SLS_Inline;
14481   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
14482                LLVMWithBeforeLambdaBody);
14483   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
14484                LLVMWithBeforeLambdaBody);
14485   verifyFormat("auto fct_SLS_Inline = []()\n"
14486                "{\n"
14487                "  return 17;\n"
14488                "};",
14489                LLVMWithBeforeLambdaBody);
14490   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
14491                "17; }); });",
14492                LLVMWithBeforeLambdaBody);
14493   verifyFormat(
14494       "FctWithLongLineInLambda_SLS_Inline(\n"
14495       "    []()\n"
14496       "    {\n"
14497       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
14498       "                               AndShouldNotBeConsiderAsInline,\n"
14499       "                               LambdaBodyMustBeBreak);\n"
14500       "    });",
14501       LLVMWithBeforeLambdaBody);
14502   verifyFormat("FctWithMultipleParams_SLS_Inline("
14503                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
14504                "                                 []() { return 17; });",
14505                LLVMWithBeforeLambdaBody);
14506   verifyFormat(
14507       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
14508       LLVMWithBeforeLambdaBody);
14509 
14510   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
14511       FormatStyle::ShortLambdaStyle::SLS_All;
14512   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
14513                LLVMWithBeforeLambdaBody);
14514   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
14515                LLVMWithBeforeLambdaBody);
14516   verifyFormat("auto fct_SLS_All = []() { return 17; };",
14517                LLVMWithBeforeLambdaBody);
14518   verifyFormat("FctWithOneParam_SLS_All(\n"
14519                "    []()\n"
14520                "    {\n"
14521                "      // A cool function...\n"
14522                "      return 43;\n"
14523                "    });",
14524                LLVMWithBeforeLambdaBody);
14525   verifyFormat("FctWithMultipleParams_SLS_All("
14526                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
14527                "                              []() { return 17; });",
14528                LLVMWithBeforeLambdaBody);
14529   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
14530                LLVMWithBeforeLambdaBody);
14531   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
14532                LLVMWithBeforeLambdaBody);
14533   verifyFormat(
14534       "FctWithLongLineInLambda_SLS_All(\n"
14535       "    []()\n"
14536       "    {\n"
14537       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
14538       "                               AndShouldNotBeConsiderAsInline,\n"
14539       "                               LambdaBodyMustBeBreak);\n"
14540       "    });",
14541       LLVMWithBeforeLambdaBody);
14542   verifyFormat(
14543       "auto fct_SLS_All = []()\n"
14544       "{\n"
14545       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
14546       "                           AndShouldNotBeConsiderAsInline,\n"
14547       "                           LambdaBodyMustBeBreak);\n"
14548       "};",
14549       LLVMWithBeforeLambdaBody);
14550   LLVMWithBeforeLambdaBody.BinPackParameters = false;
14551   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
14552                LLVMWithBeforeLambdaBody);
14553   verifyFormat(
14554       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
14555       "                                FirstParam,\n"
14556       "                                SecondParam,\n"
14557       "                                ThirdParam,\n"
14558       "                                FourthParam);",
14559       LLVMWithBeforeLambdaBody);
14560   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
14561                "    []() { return "
14562                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
14563                "    FirstParam,\n"
14564                "    SecondParam,\n"
14565                "    ThirdParam,\n"
14566                "    FourthParam);",
14567                LLVMWithBeforeLambdaBody);
14568   verifyFormat(
14569       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
14570       "                                SecondParam,\n"
14571       "                                ThirdParam,\n"
14572       "                                FourthParam,\n"
14573       "                                []() { return SomeValueNotSoLong; });",
14574       LLVMWithBeforeLambdaBody);
14575   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
14576                "    []()\n"
14577                "    {\n"
14578                "      return "
14579                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
14580                "eConsiderAsInline;\n"
14581                "    });",
14582                LLVMWithBeforeLambdaBody);
14583   verifyFormat(
14584       "FctWithLongLineInLambda_SLS_All(\n"
14585       "    []()\n"
14586       "    {\n"
14587       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
14588       "                               AndShouldNotBeConsiderAsInline,\n"
14589       "                               LambdaBodyMustBeBreak);\n"
14590       "    });",
14591       LLVMWithBeforeLambdaBody);
14592   verifyFormat("FctWithTwoParams_SLS_All(\n"
14593                "    []()\n"
14594                "    {\n"
14595                "      // A cool function...\n"
14596                "      return 43;\n"
14597                "    },\n"
14598                "    87);",
14599                LLVMWithBeforeLambdaBody);
14600   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
14601                LLVMWithBeforeLambdaBody);
14602   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
14603                LLVMWithBeforeLambdaBody);
14604   verifyFormat(
14605       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
14606       LLVMWithBeforeLambdaBody);
14607   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
14608                "}); }, x);",
14609                LLVMWithBeforeLambdaBody);
14610   verifyFormat("TwoNestedLambdas_SLS_All(\n"
14611                "    []()\n"
14612                "    {\n"
14613                "      // A cool function...\n"
14614                "      return Call([]() { return 17; });\n"
14615                "    });",
14616                LLVMWithBeforeLambdaBody);
14617   verifyFormat("TwoNestedLambdas_SLS_All(\n"
14618                "    []()\n"
14619                "    {\n"
14620                "      return Call(\n"
14621                "          []()\n"
14622                "          {\n"
14623                "            // A cool function...\n"
14624                "            return 17;\n"
14625                "          });\n"
14626                "    });",
14627                LLVMWithBeforeLambdaBody);
14628 }
14629 
14630 TEST_F(FormatTest, LambdaWithLineComments) {
14631   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
14632   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
14633   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
14634   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
14635       FormatStyle::ShortLambdaStyle::SLS_All;
14636 
14637   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
14638   verifyFormat("auto k = []() // comment\n"
14639                "{ return; }",
14640                LLVMWithBeforeLambdaBody);
14641   verifyFormat("auto k = []() /* comment */ { return; }",
14642                LLVMWithBeforeLambdaBody);
14643   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
14644                LLVMWithBeforeLambdaBody);
14645   verifyFormat("auto k = []() // X\n"
14646                "{ return; }",
14647                LLVMWithBeforeLambdaBody);
14648   verifyFormat(
14649       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
14650       "{ return; }",
14651       LLVMWithBeforeLambdaBody);
14652 }
14653 
14654 TEST_F(FormatTest, EmptyLinesInLambdas) {
14655   verifyFormat("auto lambda = []() {\n"
14656                "  x(); //\n"
14657                "};",
14658                "auto lambda = []() {\n"
14659                "\n"
14660                "  x(); //\n"
14661                "\n"
14662                "};");
14663 }
14664 
14665 TEST_F(FormatTest, FormatsBlocks) {
14666   FormatStyle ShortBlocks = getLLVMStyle();
14667   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
14668   verifyFormat("int (^Block)(int, int);", ShortBlocks);
14669   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
14670   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
14671   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
14672   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
14673   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
14674 
14675   verifyFormat("foo(^{ bar(); });", ShortBlocks);
14676   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
14677   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
14678 
14679   verifyFormat("[operation setCompletionBlock:^{\n"
14680                "  [self onOperationDone];\n"
14681                "}];");
14682   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
14683                "  [self onOperationDone];\n"
14684                "}]};");
14685   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
14686                "  f();\n"
14687                "}];");
14688   verifyFormat("int a = [operation block:^int(int *i) {\n"
14689                "  return 1;\n"
14690                "}];");
14691   verifyFormat("[myObject doSomethingWith:arg1\n"
14692                "                      aaa:^int(int *a) {\n"
14693                "                        return 1;\n"
14694                "                      }\n"
14695                "                      bbb:f(a * bbbbbbbb)];");
14696 
14697   verifyFormat("[operation setCompletionBlock:^{\n"
14698                "  [self.delegate newDataAvailable];\n"
14699                "}];",
14700                getLLVMStyleWithColumns(60));
14701   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
14702                "  NSString *path = [self sessionFilePath];\n"
14703                "  if (path) {\n"
14704                "    // ...\n"
14705                "  }\n"
14706                "});");
14707   verifyFormat("[[SessionService sharedService]\n"
14708                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
14709                "      if (window) {\n"
14710                "        [self windowDidLoad:window];\n"
14711                "      } else {\n"
14712                "        [self errorLoadingWindow];\n"
14713                "      }\n"
14714                "    }];");
14715   verifyFormat("void (^largeBlock)(void) = ^{\n"
14716                "  // ...\n"
14717                "};\n",
14718                getLLVMStyleWithColumns(40));
14719   verifyFormat("[[SessionService sharedService]\n"
14720                "    loadWindowWithCompletionBlock: //\n"
14721                "        ^(SessionWindow *window) {\n"
14722                "          if (window) {\n"
14723                "            [self windowDidLoad:window];\n"
14724                "          } else {\n"
14725                "            [self errorLoadingWindow];\n"
14726                "          }\n"
14727                "        }];",
14728                getLLVMStyleWithColumns(60));
14729   verifyFormat("[myObject doSomethingWith:arg1\n"
14730                "    firstBlock:^(Foo *a) {\n"
14731                "      // ...\n"
14732                "      int i;\n"
14733                "    }\n"
14734                "    secondBlock:^(Bar *b) {\n"
14735                "      // ...\n"
14736                "      int i;\n"
14737                "    }\n"
14738                "    thirdBlock:^Foo(Bar *b) {\n"
14739                "      // ...\n"
14740                "      int i;\n"
14741                "    }];");
14742   verifyFormat("[myObject doSomethingWith:arg1\n"
14743                "               firstBlock:-1\n"
14744                "              secondBlock:^(Bar *b) {\n"
14745                "                // ...\n"
14746                "                int i;\n"
14747                "              }];");
14748 
14749   verifyFormat("f(^{\n"
14750                "  @autoreleasepool {\n"
14751                "    if (a) {\n"
14752                "      g();\n"
14753                "    }\n"
14754                "  }\n"
14755                "});");
14756   verifyFormat("Block b = ^int *(A *a, B *b) {}");
14757   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
14758                "};");
14759 
14760   FormatStyle FourIndent = getLLVMStyle();
14761   FourIndent.ObjCBlockIndentWidth = 4;
14762   verifyFormat("[operation setCompletionBlock:^{\n"
14763                "    [self onOperationDone];\n"
14764                "}];",
14765                FourIndent);
14766 }
14767 
14768 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
14769   FormatStyle ZeroColumn = getLLVMStyle();
14770   ZeroColumn.ColumnLimit = 0;
14771 
14772   verifyFormat("[[SessionService sharedService] "
14773                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
14774                "  if (window) {\n"
14775                "    [self windowDidLoad:window];\n"
14776                "  } else {\n"
14777                "    [self errorLoadingWindow];\n"
14778                "  }\n"
14779                "}];",
14780                ZeroColumn);
14781   EXPECT_EQ("[[SessionService sharedService]\n"
14782             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
14783             "      if (window) {\n"
14784             "        [self windowDidLoad:window];\n"
14785             "      } else {\n"
14786             "        [self errorLoadingWindow];\n"
14787             "      }\n"
14788             "    }];",
14789             format("[[SessionService sharedService]\n"
14790                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
14791                    "                if (window) {\n"
14792                    "    [self windowDidLoad:window];\n"
14793                    "  } else {\n"
14794                    "    [self errorLoadingWindow];\n"
14795                    "  }\n"
14796                    "}];",
14797                    ZeroColumn));
14798   verifyFormat("[myObject doSomethingWith:arg1\n"
14799                "    firstBlock:^(Foo *a) {\n"
14800                "      // ...\n"
14801                "      int i;\n"
14802                "    }\n"
14803                "    secondBlock:^(Bar *b) {\n"
14804                "      // ...\n"
14805                "      int i;\n"
14806                "    }\n"
14807                "    thirdBlock:^Foo(Bar *b) {\n"
14808                "      // ...\n"
14809                "      int i;\n"
14810                "    }];",
14811                ZeroColumn);
14812   verifyFormat("f(^{\n"
14813                "  @autoreleasepool {\n"
14814                "    if (a) {\n"
14815                "      g();\n"
14816                "    }\n"
14817                "  }\n"
14818                "});",
14819                ZeroColumn);
14820   verifyFormat("void (^largeBlock)(void) = ^{\n"
14821                "  // ...\n"
14822                "};",
14823                ZeroColumn);
14824 
14825   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
14826   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
14827             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
14828   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
14829   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
14830             "  int i;\n"
14831             "};",
14832             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
14833 }
14834 
14835 TEST_F(FormatTest, SupportsCRLF) {
14836   EXPECT_EQ("int a;\r\n"
14837             "int b;\r\n"
14838             "int c;\r\n",
14839             format("int a;\r\n"
14840                    "  int b;\r\n"
14841                    "    int c;\r\n",
14842                    getLLVMStyle()));
14843   EXPECT_EQ("int a;\r\n"
14844             "int b;\r\n"
14845             "int c;\r\n",
14846             format("int a;\r\n"
14847                    "  int b;\n"
14848                    "    int c;\r\n",
14849                    getLLVMStyle()));
14850   EXPECT_EQ("int a;\n"
14851             "int b;\n"
14852             "int c;\n",
14853             format("int a;\r\n"
14854                    "  int b;\n"
14855                    "    int c;\n",
14856                    getLLVMStyle()));
14857   EXPECT_EQ("\"aaaaaaa \"\r\n"
14858             "\"bbbbbbb\";\r\n",
14859             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
14860   EXPECT_EQ("#define A \\\r\n"
14861             "  b;      \\\r\n"
14862             "  c;      \\\r\n"
14863             "  d;\r\n",
14864             format("#define A \\\r\n"
14865                    "  b; \\\r\n"
14866                    "  c; d; \r\n",
14867                    getGoogleStyle()));
14868 
14869   EXPECT_EQ("/*\r\n"
14870             "multi line block comments\r\n"
14871             "should not introduce\r\n"
14872             "an extra carriage return\r\n"
14873             "*/\r\n",
14874             format("/*\r\n"
14875                    "multi line block comments\r\n"
14876                    "should not introduce\r\n"
14877                    "an extra carriage return\r\n"
14878                    "*/\r\n"));
14879   EXPECT_EQ("/*\r\n"
14880             "\r\n"
14881             "*/",
14882             format("/*\r\n"
14883                    "    \r\r\r\n"
14884                    "*/"));
14885 
14886   FormatStyle style = getLLVMStyle();
14887 
14888   style.DeriveLineEnding = true;
14889   style.UseCRLF = false;
14890   EXPECT_EQ("union FooBarBazQux {\n"
14891             "  int foo;\n"
14892             "  int bar;\n"
14893             "  int baz;\n"
14894             "};",
14895             format("union FooBarBazQux {\r\n"
14896                    "  int foo;\n"
14897                    "  int bar;\r\n"
14898                    "  int baz;\n"
14899                    "};",
14900                    style));
14901   style.UseCRLF = true;
14902   EXPECT_EQ("union FooBarBazQux {\r\n"
14903             "  int foo;\r\n"
14904             "  int bar;\r\n"
14905             "  int baz;\r\n"
14906             "};",
14907             format("union FooBarBazQux {\r\n"
14908                    "  int foo;\n"
14909                    "  int bar;\r\n"
14910                    "  int baz;\n"
14911                    "};",
14912                    style));
14913 
14914   style.DeriveLineEnding = false;
14915   style.UseCRLF = false;
14916   EXPECT_EQ("union FooBarBazQux {\n"
14917             "  int foo;\n"
14918             "  int bar;\n"
14919             "  int baz;\n"
14920             "  int qux;\n"
14921             "};",
14922             format("union FooBarBazQux {\r\n"
14923                    "  int foo;\n"
14924                    "  int bar;\r\n"
14925                    "  int baz;\n"
14926                    "  int qux;\r\n"
14927                    "};",
14928                    style));
14929   style.UseCRLF = true;
14930   EXPECT_EQ("union FooBarBazQux {\r\n"
14931             "  int foo;\r\n"
14932             "  int bar;\r\n"
14933             "  int baz;\r\n"
14934             "  int qux;\r\n"
14935             "};",
14936             format("union FooBarBazQux {\r\n"
14937                    "  int foo;\n"
14938                    "  int bar;\r\n"
14939                    "  int baz;\n"
14940                    "  int qux;\n"
14941                    "};",
14942                    style));
14943 
14944   style.DeriveLineEnding = true;
14945   style.UseCRLF = false;
14946   EXPECT_EQ("union FooBarBazQux {\r\n"
14947             "  int foo;\r\n"
14948             "  int bar;\r\n"
14949             "  int baz;\r\n"
14950             "  int qux;\r\n"
14951             "};",
14952             format("union FooBarBazQux {\r\n"
14953                    "  int foo;\n"
14954                    "  int bar;\r\n"
14955                    "  int baz;\n"
14956                    "  int qux;\r\n"
14957                    "};",
14958                    style));
14959   style.UseCRLF = true;
14960   EXPECT_EQ("union FooBarBazQux {\n"
14961             "  int foo;\n"
14962             "  int bar;\n"
14963             "  int baz;\n"
14964             "  int qux;\n"
14965             "};",
14966             format("union FooBarBazQux {\r\n"
14967                    "  int foo;\n"
14968                    "  int bar;\r\n"
14969                    "  int baz;\n"
14970                    "  int qux;\n"
14971                    "};",
14972                    style));
14973 }
14974 
14975 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
14976   verifyFormat("MY_CLASS(C) {\n"
14977                "  int i;\n"
14978                "  int j;\n"
14979                "};");
14980 }
14981 
14982 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
14983   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
14984   TwoIndent.ContinuationIndentWidth = 2;
14985 
14986   EXPECT_EQ("int i =\n"
14987             "  longFunction(\n"
14988             "    arg);",
14989             format("int i = longFunction(arg);", TwoIndent));
14990 
14991   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
14992   SixIndent.ContinuationIndentWidth = 6;
14993 
14994   EXPECT_EQ("int i =\n"
14995             "      longFunction(\n"
14996             "            arg);",
14997             format("int i = longFunction(arg);", SixIndent));
14998 }
14999 
15000 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
15001   FormatStyle Style = getLLVMStyle();
15002   verifyFormat("int Foo::getter(\n"
15003                "    //\n"
15004                ") const {\n"
15005                "  return foo;\n"
15006                "}",
15007                Style);
15008   verifyFormat("void Foo::setter(\n"
15009                "    //\n"
15010                ") {\n"
15011                "  foo = 1;\n"
15012                "}",
15013                Style);
15014 }
15015 
15016 TEST_F(FormatTest, SpacesInAngles) {
15017   FormatStyle Spaces = getLLVMStyle();
15018   Spaces.SpacesInAngles = true;
15019 
15020   verifyFormat("static_cast< int >(arg);", Spaces);
15021   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
15022   verifyFormat("f< int, float >();", Spaces);
15023   verifyFormat("template <> g() {}", Spaces);
15024   verifyFormat("template < std::vector< int > > f() {}", Spaces);
15025   verifyFormat("std::function< void(int, int) > fct;", Spaces);
15026   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
15027                Spaces);
15028 
15029   Spaces.Standard = FormatStyle::LS_Cpp03;
15030   Spaces.SpacesInAngles = true;
15031   verifyFormat("A< A< int > >();", Spaces);
15032 
15033   Spaces.SpacesInAngles = false;
15034   verifyFormat("A<A<int> >();", Spaces);
15035 
15036   Spaces.Standard = FormatStyle::LS_Cpp11;
15037   Spaces.SpacesInAngles = true;
15038   verifyFormat("A< A< int > >();", Spaces);
15039 
15040   Spaces.SpacesInAngles = false;
15041   verifyFormat("A<A<int>>();", Spaces);
15042 }
15043 
15044 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
15045   FormatStyle Style = getLLVMStyle();
15046   Style.SpaceAfterTemplateKeyword = false;
15047   verifyFormat("template<int> void foo();", Style);
15048 }
15049 
15050 TEST_F(FormatTest, TripleAngleBrackets) {
15051   verifyFormat("f<<<1, 1>>>();");
15052   verifyFormat("f<<<1, 1, 1, s>>>();");
15053   verifyFormat("f<<<a, b, c, d>>>();");
15054   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
15055   verifyFormat("f<param><<<1, 1>>>();");
15056   verifyFormat("f<1><<<1, 1>>>();");
15057   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
15058   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
15059                "aaaaaaaaaaa<<<\n    1, 1>>>();");
15060   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
15061                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
15062 }
15063 
15064 TEST_F(FormatTest, MergeLessLessAtEnd) {
15065   verifyFormat("<<");
15066   EXPECT_EQ("< < <", format("\\\n<<<"));
15067   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
15068                "aaallvm::outs() <<");
15069   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
15070                "aaaallvm::outs()\n    <<");
15071 }
15072 
15073 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
15074   std::string code = "#if A\n"
15075                      "#if B\n"
15076                      "a.\n"
15077                      "#endif\n"
15078                      "    a = 1;\n"
15079                      "#else\n"
15080                      "#endif\n"
15081                      "#if C\n"
15082                      "#else\n"
15083                      "#endif\n";
15084   EXPECT_EQ(code, format(code));
15085 }
15086 
15087 TEST_F(FormatTest, HandleConflictMarkers) {
15088   // Git/SVN conflict markers.
15089   EXPECT_EQ("int a;\n"
15090             "void f() {\n"
15091             "  callme(some(parameter1,\n"
15092             "<<<<<<< text by the vcs\n"
15093             "              parameter2),\n"
15094             "||||||| text by the vcs\n"
15095             "              parameter2),\n"
15096             "         parameter3,\n"
15097             "======= text by the vcs\n"
15098             "              parameter2, parameter3),\n"
15099             ">>>>>>> text by the vcs\n"
15100             "         otherparameter);\n",
15101             format("int a;\n"
15102                    "void f() {\n"
15103                    "  callme(some(parameter1,\n"
15104                    "<<<<<<< text by the vcs\n"
15105                    "  parameter2),\n"
15106                    "||||||| text by the vcs\n"
15107                    "  parameter2),\n"
15108                    "  parameter3,\n"
15109                    "======= text by the vcs\n"
15110                    "  parameter2,\n"
15111                    "  parameter3),\n"
15112                    ">>>>>>> text by the vcs\n"
15113                    "  otherparameter);\n"));
15114 
15115   // Perforce markers.
15116   EXPECT_EQ("void f() {\n"
15117             "  function(\n"
15118             ">>>> text by the vcs\n"
15119             "      parameter,\n"
15120             "==== text by the vcs\n"
15121             "      parameter,\n"
15122             "==== text by the vcs\n"
15123             "      parameter,\n"
15124             "<<<< text by the vcs\n"
15125             "      parameter);\n",
15126             format("void f() {\n"
15127                    "  function(\n"
15128                    ">>>> text by the vcs\n"
15129                    "  parameter,\n"
15130                    "==== text by the vcs\n"
15131                    "  parameter,\n"
15132                    "==== text by the vcs\n"
15133                    "  parameter,\n"
15134                    "<<<< text by the vcs\n"
15135                    "  parameter);\n"));
15136 
15137   EXPECT_EQ("<<<<<<<\n"
15138             "|||||||\n"
15139             "=======\n"
15140             ">>>>>>>",
15141             format("<<<<<<<\n"
15142                    "|||||||\n"
15143                    "=======\n"
15144                    ">>>>>>>"));
15145 
15146   EXPECT_EQ("<<<<<<<\n"
15147             "|||||||\n"
15148             "int i;\n"
15149             "=======\n"
15150             ">>>>>>>",
15151             format("<<<<<<<\n"
15152                    "|||||||\n"
15153                    "int i;\n"
15154                    "=======\n"
15155                    ">>>>>>>"));
15156 
15157   // FIXME: Handle parsing of macros around conflict markers correctly:
15158   EXPECT_EQ("#define Macro \\\n"
15159             "<<<<<<<\n"
15160             "Something \\\n"
15161             "|||||||\n"
15162             "Else \\\n"
15163             "=======\n"
15164             "Other \\\n"
15165             ">>>>>>>\n"
15166             "    End int i;\n",
15167             format("#define Macro \\\n"
15168                    "<<<<<<<\n"
15169                    "  Something \\\n"
15170                    "|||||||\n"
15171                    "  Else \\\n"
15172                    "=======\n"
15173                    "  Other \\\n"
15174                    ">>>>>>>\n"
15175                    "  End\n"
15176                    "int i;\n"));
15177 }
15178 
15179 TEST_F(FormatTest, DisableRegions) {
15180   EXPECT_EQ("int i;\n"
15181             "// clang-format off\n"
15182             "  int j;\n"
15183             "// clang-format on\n"
15184             "int k;",
15185             format(" int  i;\n"
15186                    "   // clang-format off\n"
15187                    "  int j;\n"
15188                    " // clang-format on\n"
15189                    "   int   k;"));
15190   EXPECT_EQ("int i;\n"
15191             "/* clang-format off */\n"
15192             "  int j;\n"
15193             "/* clang-format on */\n"
15194             "int k;",
15195             format(" int  i;\n"
15196                    "   /* clang-format off */\n"
15197                    "  int j;\n"
15198                    " /* clang-format on */\n"
15199                    "   int   k;"));
15200 
15201   // Don't reflow comments within disabled regions.
15202   EXPECT_EQ("// clang-format off\n"
15203             "// long long long long long long line\n"
15204             "/* clang-format on */\n"
15205             "/* long long long\n"
15206             " * long long long\n"
15207             " * line */\n"
15208             "int i;\n"
15209             "/* clang-format off */\n"
15210             "/* long long long long long long line */\n",
15211             format("// clang-format off\n"
15212                    "// long long long long long long line\n"
15213                    "/* clang-format on */\n"
15214                    "/* long long long long long long line */\n"
15215                    "int i;\n"
15216                    "/* clang-format off */\n"
15217                    "/* long long long long long long line */\n",
15218                    getLLVMStyleWithColumns(20)));
15219 }
15220 
15221 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
15222   format("? ) =");
15223   verifyNoCrash("#define a\\\n /**/}");
15224 }
15225 
15226 TEST_F(FormatTest, FormatsTableGenCode) {
15227   FormatStyle Style = getLLVMStyle();
15228   Style.Language = FormatStyle::LK_TableGen;
15229   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
15230 }
15231 
15232 TEST_F(FormatTest, ArrayOfTemplates) {
15233   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
15234             format("auto a = new unique_ptr<int > [ 10];"));
15235 
15236   FormatStyle Spaces = getLLVMStyle();
15237   Spaces.SpacesInSquareBrackets = true;
15238   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
15239             format("auto a = new unique_ptr<int > [10];", Spaces));
15240 }
15241 
15242 TEST_F(FormatTest, ArrayAsTemplateType) {
15243   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
15244             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
15245 
15246   FormatStyle Spaces = getLLVMStyle();
15247   Spaces.SpacesInSquareBrackets = true;
15248   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
15249             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
15250 }
15251 
15252 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
15253 
15254 TEST(FormatStyle, GetStyleWithEmptyFileName) {
15255   llvm::vfs::InMemoryFileSystem FS;
15256   auto Style1 = getStyle("file", "", "Google", "", &FS);
15257   ASSERT_TRUE((bool)Style1);
15258   ASSERT_EQ(*Style1, getGoogleStyle());
15259 }
15260 
15261 TEST(FormatStyle, GetStyleOfFile) {
15262   llvm::vfs::InMemoryFileSystem FS;
15263   // Test 1: format file in the same directory.
15264   ASSERT_TRUE(
15265       FS.addFile("/a/.clang-format", 0,
15266                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
15267   ASSERT_TRUE(
15268       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
15269   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
15270   ASSERT_TRUE((bool)Style1);
15271   ASSERT_EQ(*Style1, getLLVMStyle());
15272 
15273   // Test 2.1: fallback to default.
15274   ASSERT_TRUE(
15275       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
15276   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
15277   ASSERT_TRUE((bool)Style2);
15278   ASSERT_EQ(*Style2, getMozillaStyle());
15279 
15280   // Test 2.2: no format on 'none' fallback style.
15281   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
15282   ASSERT_TRUE((bool)Style2);
15283   ASSERT_EQ(*Style2, getNoStyle());
15284 
15285   // Test 2.3: format if config is found with no based style while fallback is
15286   // 'none'.
15287   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
15288                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
15289   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
15290   ASSERT_TRUE((bool)Style2);
15291   ASSERT_EQ(*Style2, getLLVMStyle());
15292 
15293   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
15294   Style2 = getStyle("{}", "a.h", "none", "", &FS);
15295   ASSERT_TRUE((bool)Style2);
15296   ASSERT_EQ(*Style2, getLLVMStyle());
15297 
15298   // Test 3: format file in parent directory.
15299   ASSERT_TRUE(
15300       FS.addFile("/c/.clang-format", 0,
15301                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
15302   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
15303                          llvm::MemoryBuffer::getMemBuffer("int i;")));
15304   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
15305   ASSERT_TRUE((bool)Style3);
15306   ASSERT_EQ(*Style3, getGoogleStyle());
15307 
15308   // Test 4: error on invalid fallback style
15309   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
15310   ASSERT_FALSE((bool)Style4);
15311   llvm::consumeError(Style4.takeError());
15312 
15313   // Test 5: error on invalid yaml on command line
15314   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
15315   ASSERT_FALSE((bool)Style5);
15316   llvm::consumeError(Style5.takeError());
15317 
15318   // Test 6: error on invalid style
15319   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
15320   ASSERT_FALSE((bool)Style6);
15321   llvm::consumeError(Style6.takeError());
15322 
15323   // Test 7: found config file, error on parsing it
15324   ASSERT_TRUE(
15325       FS.addFile("/d/.clang-format", 0,
15326                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
15327                                                   "InvalidKey: InvalidValue")));
15328   ASSERT_TRUE(
15329       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
15330   auto Style7 = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
15331   ASSERT_FALSE((bool)Style7);
15332   llvm::consumeError(Style7.takeError());
15333 
15334   // Test 8: inferred per-language defaults apply.
15335   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
15336   ASSERT_TRUE((bool)StyleTd);
15337   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
15338 }
15339 
15340 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
15341   // Column limit is 20.
15342   std::string Code = "Type *a =\n"
15343                      "    new Type();\n"
15344                      "g(iiiii, 0, jjjjj,\n"
15345                      "  0, kkkkk, 0, mm);\n"
15346                      "int  bad     = format   ;";
15347   std::string Expected = "auto a = new Type();\n"
15348                          "g(iiiii, nullptr,\n"
15349                          "  jjjjj, nullptr,\n"
15350                          "  kkkkk, nullptr,\n"
15351                          "  mm);\n"
15352                          "int  bad     = format   ;";
15353   FileID ID = Context.createInMemoryFile("format.cpp", Code);
15354   tooling::Replacements Replaces = toReplacements(
15355       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
15356                             "auto "),
15357        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
15358                             "nullptr"),
15359        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
15360                             "nullptr"),
15361        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
15362                             "nullptr")});
15363 
15364   format::FormatStyle Style = format::getLLVMStyle();
15365   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
15366   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
15367   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
15368       << llvm::toString(FormattedReplaces.takeError()) << "\n";
15369   auto Result = applyAllReplacements(Code, *FormattedReplaces);
15370   EXPECT_TRUE(static_cast<bool>(Result));
15371   EXPECT_EQ(Expected, *Result);
15372 }
15373 
15374 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
15375   std::string Code = "#include \"a.h\"\n"
15376                      "#include \"c.h\"\n"
15377                      "\n"
15378                      "int main() {\n"
15379                      "  return 0;\n"
15380                      "}";
15381   std::string Expected = "#include \"a.h\"\n"
15382                          "#include \"b.h\"\n"
15383                          "#include \"c.h\"\n"
15384                          "\n"
15385                          "int main() {\n"
15386                          "  return 0;\n"
15387                          "}";
15388   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
15389   tooling::Replacements Replaces = toReplacements(
15390       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
15391                             "#include \"b.h\"\n")});
15392 
15393   format::FormatStyle Style = format::getLLVMStyle();
15394   Style.SortIncludes = true;
15395   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
15396   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
15397       << llvm::toString(FormattedReplaces.takeError()) << "\n";
15398   auto Result = applyAllReplacements(Code, *FormattedReplaces);
15399   EXPECT_TRUE(static_cast<bool>(Result));
15400   EXPECT_EQ(Expected, *Result);
15401 }
15402 
15403 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
15404   EXPECT_EQ("using std::cin;\n"
15405             "using std::cout;",
15406             format("using std::cout;\n"
15407                    "using std::cin;",
15408                    getGoogleStyle()));
15409 }
15410 
15411 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
15412   format::FormatStyle Style = format::getLLVMStyle();
15413   Style.Standard = FormatStyle::LS_Cpp03;
15414   // cpp03 recognize this string as identifier u8 and literal character 'a'
15415   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
15416 }
15417 
15418 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
15419   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
15420   // all modes, including C++11, C++14 and C++17
15421   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
15422 }
15423 
15424 TEST_F(FormatTest, DoNotFormatLikelyXml) {
15425   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
15426   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
15427 }
15428 
15429 TEST_F(FormatTest, StructuredBindings) {
15430   // Structured bindings is a C++17 feature.
15431   // all modes, including C++11, C++14 and C++17
15432   verifyFormat("auto [a, b] = f();");
15433   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
15434   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
15435   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
15436   EXPECT_EQ("auto const volatile [a, b] = f();",
15437             format("auto  const   volatile[a, b] = f();"));
15438   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
15439   EXPECT_EQ("auto &[a, b, c] = f();",
15440             format("auto   &[  a  ,  b,c   ] = f();"));
15441   EXPECT_EQ("auto &&[a, b, c] = f();",
15442             format("auto   &&[  a  ,  b,c   ] = f();"));
15443   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
15444   EXPECT_EQ("auto const volatile &&[a, b] = f();",
15445             format("auto  const  volatile  &&[a, b] = f();"));
15446   EXPECT_EQ("auto const &&[a, b] = f();",
15447             format("auto  const   &&  [a, b] = f();"));
15448   EXPECT_EQ("const auto &[a, b] = f();",
15449             format("const  auto  &  [a, b] = f();"));
15450   EXPECT_EQ("const auto volatile &&[a, b] = f();",
15451             format("const  auto   volatile  &&[a, b] = f();"));
15452   EXPECT_EQ("volatile const auto &&[a, b] = f();",
15453             format("volatile  const  auto   &&[a, b] = f();"));
15454   EXPECT_EQ("const auto &&[a, b] = f();",
15455             format("const  auto  &&  [a, b] = f();"));
15456 
15457   // Make sure we don't mistake structured bindings for lambdas.
15458   FormatStyle PointerMiddle = getLLVMStyle();
15459   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
15460   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
15461   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
15462   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
15463   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
15464   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
15465   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
15466   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
15467   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
15468   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
15469   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
15470   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
15471   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
15472 
15473   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
15474             format("for (const auto   &&   [a, b] : some_range) {\n}"));
15475   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
15476             format("for (const auto   &   [a, b] : some_range) {\n}"));
15477   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
15478             format("for (const auto[a, b] : some_range) {\n}"));
15479   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
15480   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
15481   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
15482   EXPECT_EQ("auto const &[x, y](expr);",
15483             format("auto  const  &  [x,y]  (expr);"));
15484   EXPECT_EQ("auto const &&[x, y](expr);",
15485             format("auto  const  &&  [x,y]  (expr);"));
15486   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
15487   EXPECT_EQ("auto const &[x, y]{expr};",
15488             format("auto  const  &  [x,y]  {expr};"));
15489   EXPECT_EQ("auto const &&[x, y]{expr};",
15490             format("auto  const  &&  [x,y]  {expr};"));
15491 
15492   format::FormatStyle Spaces = format::getLLVMStyle();
15493   Spaces.SpacesInSquareBrackets = true;
15494   verifyFormat("auto [ a, b ] = f();", Spaces);
15495   verifyFormat("auto &&[ a, b ] = f();", Spaces);
15496   verifyFormat("auto &[ a, b ] = f();", Spaces);
15497   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
15498   verifyFormat("auto const &[ a, b ] = f();", Spaces);
15499 }
15500 
15501 TEST_F(FormatTest, FileAndCode) {
15502   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
15503   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
15504   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
15505   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
15506   EXPECT_EQ(FormatStyle::LK_ObjC,
15507             guessLanguage("foo.h", "@interface Foo\n@end\n"));
15508   EXPECT_EQ(
15509       FormatStyle::LK_ObjC,
15510       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
15511   EXPECT_EQ(FormatStyle::LK_ObjC,
15512             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
15513   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
15514   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
15515   EXPECT_EQ(FormatStyle::LK_ObjC,
15516             guessLanguage("foo", "@interface Foo\n@end\n"));
15517   EXPECT_EQ(FormatStyle::LK_ObjC,
15518             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
15519   EXPECT_EQ(
15520       FormatStyle::LK_ObjC,
15521       guessLanguage("foo.h",
15522                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
15523   EXPECT_EQ(
15524       FormatStyle::LK_Cpp,
15525       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
15526 }
15527 
15528 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
15529   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
15530   EXPECT_EQ(FormatStyle::LK_ObjC,
15531             guessLanguage("foo.h", "array[[calculator getIndex]];"));
15532   EXPECT_EQ(FormatStyle::LK_Cpp,
15533             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
15534   EXPECT_EQ(
15535       FormatStyle::LK_Cpp,
15536       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
15537   EXPECT_EQ(FormatStyle::LK_ObjC,
15538             guessLanguage("foo.h", "[[noreturn foo] bar];"));
15539   EXPECT_EQ(FormatStyle::LK_Cpp,
15540             guessLanguage("foo.h", "[[clang::fallthrough]];"));
15541   EXPECT_EQ(FormatStyle::LK_ObjC,
15542             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
15543   EXPECT_EQ(FormatStyle::LK_Cpp,
15544             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
15545   EXPECT_EQ(FormatStyle::LK_Cpp,
15546             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
15547   EXPECT_EQ(FormatStyle::LK_ObjC,
15548             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
15549   EXPECT_EQ(FormatStyle::LK_Cpp,
15550             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
15551   EXPECT_EQ(
15552       FormatStyle::LK_Cpp,
15553       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
15554   EXPECT_EQ(
15555       FormatStyle::LK_Cpp,
15556       guessLanguage("foo.h",
15557                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
15558   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
15559 }
15560 
15561 TEST_F(FormatTest, GuessLanguageWithCaret) {
15562   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
15563   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
15564   EXPECT_EQ(FormatStyle::LK_ObjC,
15565             guessLanguage("foo.h", "int(^)(char, float);"));
15566   EXPECT_EQ(FormatStyle::LK_ObjC,
15567             guessLanguage("foo.h", "int(^foo)(char, float);"));
15568   EXPECT_EQ(FormatStyle::LK_ObjC,
15569             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
15570   EXPECT_EQ(FormatStyle::LK_ObjC,
15571             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
15572   EXPECT_EQ(
15573       FormatStyle::LK_ObjC,
15574       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
15575 }
15576 
15577 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
15578   // ASM symbolic names are identifiers that must be surrounded by [] without
15579   // space in between:
15580   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
15581 
15582   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
15583   verifyFormat(R"(//
15584 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
15585 )");
15586 
15587   // A list of several ASM symbolic names.
15588   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
15589 
15590   // ASM symbolic names in inline ASM with inputs and outputs.
15591   verifyFormat(R"(//
15592 asm("cmoveq %1, %2, %[result]"
15593     : [result] "=r"(result)
15594     : "r"(test), "r"(new), "[result]"(old));
15595 )");
15596 
15597   // ASM symbolic names in inline ASM with no outputs.
15598   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
15599 }
15600 
15601 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
15602   EXPECT_EQ(FormatStyle::LK_Cpp,
15603             guessLanguage("foo.h", "void f() {\n"
15604                                    "  asm (\"mov %[e], %[d]\"\n"
15605                                    "     : [d] \"=rm\" (d)\n"
15606                                    "       [e] \"rm\" (*e));\n"
15607                                    "}"));
15608   EXPECT_EQ(FormatStyle::LK_Cpp,
15609             guessLanguage("foo.h", "void f() {\n"
15610                                    "  _asm (\"mov %[e], %[d]\"\n"
15611                                    "     : [d] \"=rm\" (d)\n"
15612                                    "       [e] \"rm\" (*e));\n"
15613                                    "}"));
15614   EXPECT_EQ(FormatStyle::LK_Cpp,
15615             guessLanguage("foo.h", "void f() {\n"
15616                                    "  __asm (\"mov %[e], %[d]\"\n"
15617                                    "     : [d] \"=rm\" (d)\n"
15618                                    "       [e] \"rm\" (*e));\n"
15619                                    "}"));
15620   EXPECT_EQ(FormatStyle::LK_Cpp,
15621             guessLanguage("foo.h", "void f() {\n"
15622                                    "  __asm__ (\"mov %[e], %[d]\"\n"
15623                                    "     : [d] \"=rm\" (d)\n"
15624                                    "       [e] \"rm\" (*e));\n"
15625                                    "}"));
15626   EXPECT_EQ(FormatStyle::LK_Cpp,
15627             guessLanguage("foo.h", "void f() {\n"
15628                                    "  asm (\"mov %[e], %[d]\"\n"
15629                                    "     : [d] \"=rm\" (d),\n"
15630                                    "       [e] \"rm\" (*e));\n"
15631                                    "}"));
15632   EXPECT_EQ(FormatStyle::LK_Cpp,
15633             guessLanguage("foo.h", "void f() {\n"
15634                                    "  asm volatile (\"mov %[e], %[d]\"\n"
15635                                    "     : [d] \"=rm\" (d)\n"
15636                                    "       [e] \"rm\" (*e));\n"
15637                                    "}"));
15638 }
15639 
15640 TEST_F(FormatTest, GuessLanguageWithChildLines) {
15641   EXPECT_EQ(FormatStyle::LK_Cpp,
15642             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
15643   EXPECT_EQ(FormatStyle::LK_ObjC,
15644             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
15645   EXPECT_EQ(
15646       FormatStyle::LK_Cpp,
15647       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
15648   EXPECT_EQ(
15649       FormatStyle::LK_ObjC,
15650       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
15651 }
15652 
15653 TEST_F(FormatTest, TypenameMacros) {
15654   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
15655 
15656   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
15657   FormatStyle Google = getGoogleStyleWithColumns(0);
15658   Google.TypenameMacros = TypenameMacros;
15659   verifyFormat("struct foo {\n"
15660                "  int bar;\n"
15661                "  TAILQ_ENTRY(a) bleh;\n"
15662                "};",
15663                Google);
15664 
15665   FormatStyle Macros = getLLVMStyle();
15666   Macros.TypenameMacros = TypenameMacros;
15667 
15668   verifyFormat("STACK_OF(int) a;", Macros);
15669   verifyFormat("STACK_OF(int) *a;", Macros);
15670   verifyFormat("STACK_OF(int const *) *a;", Macros);
15671   verifyFormat("STACK_OF(int *const) *a;", Macros);
15672   verifyFormat("STACK_OF(int, string) a;", Macros);
15673   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
15674   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
15675   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
15676   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
15677 
15678   Macros.PointerAlignment = FormatStyle::PAS_Left;
15679   verifyFormat("STACK_OF(int)* a;", Macros);
15680   verifyFormat("STACK_OF(int*)* a;", Macros);
15681 }
15682 
15683 TEST_F(FormatTest, AmbersandInLamda) {
15684   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
15685   FormatStyle AlignStyle = getLLVMStyle();
15686   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
15687   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
15688   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
15689   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
15690 }
15691 
15692 TEST_F(FormatTest, SpacesInConditionalStatement) {
15693   FormatStyle Spaces = getLLVMStyle();
15694   Spaces.SpacesInConditionalStatement = true;
15695   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
15696   verifyFormat("if ( !a )\n  return;", Spaces);
15697   verifyFormat("if ( a )\n  return;", Spaces);
15698   verifyFormat("if constexpr ( a )\n  return;", Spaces);
15699   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
15700   verifyFormat("while ( a )\n  return;", Spaces);
15701   verifyFormat("while ( (a && b) )\n  return;", Spaces);
15702   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
15703   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
15704   // Check that space on the left of "::" is inserted as expected at beginning
15705   // of condition.
15706   verifyFormat("while ( ::func() )\n  return;", Spaces);
15707 }
15708 
15709 TEST_F(FormatTest, AlternativeOperators) {
15710   // Test case for ensuring alternate operators are not
15711   // combined with their right most neighbour.
15712   verifyFormat("int a and b;");
15713   verifyFormat("int a and_eq b;");
15714   verifyFormat("int a bitand b;");
15715   verifyFormat("int a bitor b;");
15716   verifyFormat("int a compl b;");
15717   verifyFormat("int a not b;");
15718   verifyFormat("int a not_eq b;");
15719   verifyFormat("int a or b;");
15720   verifyFormat("int a xor b;");
15721   verifyFormat("int a xor_eq b;");
15722   verifyFormat("return this not_eq bitand other;");
15723   verifyFormat("bool operator not_eq(const X bitand other)");
15724 
15725   verifyFormat("int a and 5;");
15726   verifyFormat("int a and_eq 5;");
15727   verifyFormat("int a bitand 5;");
15728   verifyFormat("int a bitor 5;");
15729   verifyFormat("int a compl 5;");
15730   verifyFormat("int a not 5;");
15731   verifyFormat("int a not_eq 5;");
15732   verifyFormat("int a or 5;");
15733   verifyFormat("int a xor 5;");
15734   verifyFormat("int a xor_eq 5;");
15735 
15736   verifyFormat("int a compl(5);");
15737   verifyFormat("int a not(5);");
15738 
15739   /* FIXME handle alternate tokens
15740    * https://en.cppreference.com/w/cpp/language/operator_alternative
15741   // alternative tokens
15742   verifyFormat("compl foo();");     //  ~foo();
15743   verifyFormat("foo() <%%>;");      // foo();
15744   verifyFormat("void foo() <%%>;"); // void foo(){}
15745   verifyFormat("int a <:1:>;");     // int a[1];[
15746   verifyFormat("%:define ABC abc"); // #define ABC abc
15747   verifyFormat("%:%:");             // ##
15748   */
15749 }
15750 
15751 TEST_F(FormatTest, STLWhileNotDefineChed) {
15752   verifyFormat("#if defined(while)\n"
15753                "#define while EMIT WARNING C4005\n"
15754                "#endif // while");
15755 }
15756 
15757 TEST_F(FormatTest, OperatorSpacing) {
15758   FormatStyle Style = getLLVMStyle();
15759   Style.PointerAlignment = FormatStyle::PAS_Right;
15760   verifyFormat("Foo::operator*();", Style);
15761   verifyFormat("Foo::operator void *();", Style);
15762   verifyFormat("Foo::operator void **();", Style);
15763   verifyFormat("Foo::operator void *&();", Style);
15764   verifyFormat("Foo::operator void *&&();", Style);
15765   verifyFormat("Foo::operator()(void *);", Style);
15766   verifyFormat("Foo::operator*(void *);", Style);
15767   verifyFormat("Foo::operator*();", Style);
15768   verifyFormat("Foo::operator**();", Style);
15769   verifyFormat("Foo::operator&();", Style);
15770   verifyFormat("Foo::operator<int> *();", Style);
15771   verifyFormat("Foo::operator<Foo> *();", Style);
15772   verifyFormat("Foo::operator<int> **();", Style);
15773   verifyFormat("Foo::operator<Foo> **();", Style);
15774   verifyFormat("Foo::operator<int> &();", Style);
15775   verifyFormat("Foo::operator<Foo> &();", Style);
15776   verifyFormat("Foo::operator<int> &&();", Style);
15777   verifyFormat("Foo::operator<Foo> &&();", Style);
15778   verifyFormat("Foo::operator<int> *&();", Style);
15779   verifyFormat("Foo::operator<Foo> *&();", Style);
15780   verifyFormat("Foo::operator<int> *&&();", Style);
15781   verifyFormat("Foo::operator<Foo> *&&();", Style);
15782   verifyFormat("operator*(int (*)(), class Foo);", Style);
15783 
15784   verifyFormat("Foo::operator&();", Style);
15785   verifyFormat("Foo::operator void &();", Style);
15786   verifyFormat("Foo::operator()(void &);", Style);
15787   verifyFormat("Foo::operator&(void &);", Style);
15788   verifyFormat("Foo::operator&();", Style);
15789   verifyFormat("operator&(int (&)(), class Foo);", Style);
15790 
15791   verifyFormat("Foo::operator&&();", Style);
15792   verifyFormat("Foo::operator**();", Style);
15793   verifyFormat("Foo::operator void &&();", Style);
15794   verifyFormat("Foo::operator()(void &&);", Style);
15795   verifyFormat("Foo::operator&&(void &&);", Style);
15796   verifyFormat("Foo::operator&&();", Style);
15797   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
15798   verifyFormat("operator const nsTArrayRight<E> &()", Style);
15799   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
15800                Style);
15801   verifyFormat("operator void **()", Style);
15802   verifyFormat("operator const FooRight<Object> &()", Style);
15803   verifyFormat("operator const FooRight<Object> *()", Style);
15804   verifyFormat("operator const FooRight<Object> **()", Style);
15805   verifyFormat("operator const FooRight<Object> *&()", Style);
15806   verifyFormat("operator const FooRight<Object> *&&()", Style);
15807 
15808   Style.PointerAlignment = FormatStyle::PAS_Left;
15809   verifyFormat("Foo::operator*();", Style);
15810   verifyFormat("Foo::operator**();", Style);
15811   verifyFormat("Foo::operator void*();", Style);
15812   verifyFormat("Foo::operator void**();", Style);
15813   verifyFormat("Foo::operator void*&();", Style);
15814   verifyFormat("Foo::operator/*comment*/ void*();", Style);
15815   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
15816   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
15817   verifyFormat("Foo::operator()(void*);", Style);
15818   verifyFormat("Foo::operator*(void*);", Style);
15819   verifyFormat("Foo::operator*();", Style);
15820   verifyFormat("Foo::operator<int>*();", Style);
15821   verifyFormat("Foo::operator<Foo>*();", Style);
15822   verifyFormat("Foo::operator<int>**();", Style);
15823   verifyFormat("Foo::operator<Foo>**();", Style);
15824   verifyFormat("Foo::operator<Foo>*&();", Style);
15825   verifyFormat("Foo::operator<int>&();", Style);
15826   verifyFormat("Foo::operator<Foo>&();", Style);
15827   verifyFormat("Foo::operator<int>&&();", Style);
15828   verifyFormat("Foo::operator<Foo>&&();", Style);
15829   verifyFormat("Foo::operator<int>*&();", Style);
15830   verifyFormat("Foo::operator<Foo>*&();", Style);
15831   verifyFormat("operator*(int (*)(), class Foo);", Style);
15832 
15833   verifyFormat("Foo::operator&();", Style);
15834   verifyFormat("Foo::operator void&();", Style);
15835   verifyFormat("Foo::operator/*comment*/ void&();", Style);
15836   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
15837   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
15838   verifyFormat("Foo::operator()(void&);", Style);
15839   verifyFormat("Foo::operator&(void&);", Style);
15840   verifyFormat("Foo::operator&();", Style);
15841   verifyFormat("operator&(int (&)(), class Foo);", Style);
15842 
15843   verifyFormat("Foo::operator&&();", Style);
15844   verifyFormat("Foo::operator void&&();", Style);
15845   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
15846   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
15847   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
15848   verifyFormat("Foo::operator()(void&&);", Style);
15849   verifyFormat("Foo::operator&&(void&&);", Style);
15850   verifyFormat("Foo::operator&&();", Style);
15851   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
15852   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
15853   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
15854                Style);
15855   verifyFormat("operator void**()", Style);
15856   verifyFormat("operator const FooLeft<Object>&()", Style);
15857   verifyFormat("operator const FooLeft<Object>*()", Style);
15858   verifyFormat("operator const FooLeft<Object>**()", Style);
15859   verifyFormat("operator const FooLeft<Object>*&()", Style);
15860   verifyFormat("operator const FooLeft<Object>*&&()", Style);
15861 
15862   // PR45107
15863   verifyFormat("operator Vector<String>&();", Style);
15864   verifyFormat("operator const Vector<String>&();", Style);
15865   verifyFormat("operator foo::Bar*();", Style);
15866   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
15867   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
15868                Style);
15869 
15870   Style.PointerAlignment = FormatStyle::PAS_Middle;
15871   verifyFormat("Foo::operator*();", Style);
15872   verifyFormat("Foo::operator void *();", Style);
15873   verifyFormat("Foo::operator()(void *);", Style);
15874   verifyFormat("Foo::operator*(void *);", Style);
15875   verifyFormat("Foo::operator*();", Style);
15876   verifyFormat("operator*(int (*)(), class Foo);", Style);
15877 
15878   verifyFormat("Foo::operator&();", Style);
15879   verifyFormat("Foo::operator void &();", Style);
15880   verifyFormat("Foo::operator()(void &);", Style);
15881   verifyFormat("Foo::operator&(void &);", Style);
15882   verifyFormat("Foo::operator&();", Style);
15883   verifyFormat("operator&(int (&)(), class Foo);", Style);
15884 
15885   verifyFormat("Foo::operator&&();", Style);
15886   verifyFormat("Foo::operator void &&();", Style);
15887   verifyFormat("Foo::operator()(void &&);", Style);
15888   verifyFormat("Foo::operator&&(void &&);", Style);
15889   verifyFormat("Foo::operator&&();", Style);
15890   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
15891 }
15892 
15893 } // namespace
15894 } // namespace format
15895 } // namespace clang
15896