1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/Format/Format.h"
10 
11 #include "../Tooling/ReplacementTest.h"
12 #include "FormatTestUtils.h"
13 
14 #include "llvm/Support/Debug.h"
15 #include "llvm/Support/MemoryBuffer.h"
16 #include "gtest/gtest.h"
17 
18 #define DEBUG_TYPE "format-test"
19 
20 using clang::tooling::ReplacementTest;
21 using clang::tooling::toReplacements;
22 using testing::internal::ScopedTrace;
23 
24 namespace clang {
25 namespace format {
26 namespace {
27 
28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
29 
30 class FormatTest : public ::testing::Test {
31 protected:
32   enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck };
33 
34   std::string format(llvm::StringRef Code,
35                      const FormatStyle &Style = getLLVMStyle(),
36                      StatusCheck CheckComplete = SC_ExpectComplete) {
37     LLVM_DEBUG(llvm::errs() << "---\n");
38     LLVM_DEBUG(llvm::errs() << Code << "\n\n");
39     std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
40     FormattingAttemptStatus Status;
41     tooling::Replacements Replaces =
42         reformat(Style, Code, Ranges, "<stdin>", &Status);
43     if (CheckComplete != SC_DoNotCheck) {
44       bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete;
45       EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete)
46           << Code << "\n\n";
47     }
48     ReplacementCount = Replaces.size();
49     auto Result = applyAllReplacements(Code, Replaces);
50     EXPECT_TRUE(static_cast<bool>(Result));
51     LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
52     return *Result;
53   }
54 
55   FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) {
56     Style.ColumnLimit = ColumnLimit;
57     return Style;
58   }
59 
60   FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
61     return getStyleWithColumns(getLLVMStyle(), ColumnLimit);
62   }
63 
64   FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
65     return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
66   }
67 
68   void _verifyFormat(const char *File, int Line, llvm::StringRef Expected,
69                      llvm::StringRef Code,
70                      const FormatStyle &Style = getLLVMStyle()) {
71     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
72     EXPECT_EQ(Expected.str(), format(Expected, Style))
73         << "Expected code is not stable";
74     EXPECT_EQ(Expected.str(), format(Code, Style));
75     if (Style.Language == FormatStyle::LK_Cpp) {
76       // Objective-C++ is a superset of C++, so everything checked for C++
77       // needs to be checked for Objective-C++ as well.
78       FormatStyle ObjCStyle = Style;
79       ObjCStyle.Language = FormatStyle::LK_ObjC;
80       EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle));
81     }
82   }
83 
84   void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
85                      const FormatStyle &Style = getLLVMStyle()) {
86     _verifyFormat(File, Line, Code, test::messUp(Code), Style);
87   }
88 
89   void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code,
90                                const FormatStyle &Style = getLLVMStyle()) {
91     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
92     EXPECT_EQ(Code.str(),
93               format(test::messUp(Code), Style, SC_ExpectIncomplete));
94   }
95 
96   void _verifyIndependentOfContext(const char *File, int Line,
97                                    llvm::StringRef Text,
98                                    const FormatStyle &Style = getLLVMStyle()) {
99     _verifyFormat(File, Line, Text, Style);
100     _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(),
101                   Style);
102   }
103 
104   /// \brief Verify that clang-format does not crash on the given input.
105   void verifyNoCrash(llvm::StringRef Code,
106                      const FormatStyle &Style = getLLVMStyle()) {
107     format(Code, Style, SC_DoNotCheck);
108   }
109 
110   int ReplacementCount;
111 };
112 
113 #define verifyIndependentOfContext(...)                                        \
114   _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__)
115 #define verifyIncompleteFormat(...)                                            \
116   _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle())
119 
120 TEST_F(FormatTest, MessUp) {
121   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
122   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
123   EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
124   EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
125   EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
126 }
127 
128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
129   EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
130 }
131 
132 TEST_F(FormatTest, LLVMStyleOverride) {
133   EXPECT_EQ(FormatStyle::LK_Proto,
134             getLLVMStyle(FormatStyle::LK_Proto).Language);
135 }
136 
137 //===----------------------------------------------------------------------===//
138 // Basic function tests.
139 //===----------------------------------------------------------------------===//
140 
141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
142   EXPECT_EQ(";", format(";"));
143 }
144 
145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
146   EXPECT_EQ("int i;", format("  int i;"));
147   EXPECT_EQ("\nint i;", format(" \n\t \v \f  int i;"));
148   EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
149   EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
150 }
151 
152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
153   EXPECT_EQ("int i;", format("int\ni;"));
154 }
155 
156 TEST_F(FormatTest, FormatsNestedBlockStatements) {
157   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
158 }
159 
160 TEST_F(FormatTest, FormatsNestedCall) {
161   verifyFormat("Method(f1, f2(f3));");
162   verifyFormat("Method(f1(f2, f3()));");
163   verifyFormat("Method(f1(f2, (f3())));");
164 }
165 
166 TEST_F(FormatTest, NestedNameSpecifiers) {
167   verifyFormat("vector<::Type> v;");
168   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
169   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
170   verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
171   verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
172   verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
173   verifyFormat("bool a = 2 < ::SomeFunction();");
174   verifyFormat("ALWAYS_INLINE ::std::string getName();");
175   verifyFormat("some::string getName();");
176 }
177 
178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
179   EXPECT_EQ("if (a) {\n"
180             "  f();\n"
181             "}",
182             format("if(a){f();}"));
183   EXPECT_EQ(4, ReplacementCount);
184   EXPECT_EQ("if (a) {\n"
185             "  f();\n"
186             "}",
187             format("if (a) {\n"
188                    "  f();\n"
189                    "}"));
190   EXPECT_EQ(0, ReplacementCount);
191   EXPECT_EQ("/*\r\n"
192             "\r\n"
193             "*/\r\n",
194             format("/*\r\n"
195                    "\r\n"
196                    "*/\r\n"));
197   EXPECT_EQ(0, ReplacementCount);
198 }
199 
200 TEST_F(FormatTest, RemovesEmptyLines) {
201   EXPECT_EQ("class C {\n"
202             "  int i;\n"
203             "};",
204             format("class C {\n"
205                    " int i;\n"
206                    "\n"
207                    "};"));
208 
209   // Don't remove empty lines at the start of namespaces or extern "C" blocks.
210   EXPECT_EQ("namespace N {\n"
211             "\n"
212             "int i;\n"
213             "}",
214             format("namespace N {\n"
215                    "\n"
216                    "int    i;\n"
217                    "}",
218                    getGoogleStyle()));
219   EXPECT_EQ("/* something */ namespace N {\n"
220             "\n"
221             "int i;\n"
222             "}",
223             format("/* something */ namespace N {\n"
224                    "\n"
225                    "int    i;\n"
226                    "}",
227                    getGoogleStyle()));
228   EXPECT_EQ("inline namespace N {\n"
229             "\n"
230             "int i;\n"
231             "}",
232             format("inline namespace N {\n"
233                    "\n"
234                    "int    i;\n"
235                    "}",
236                    getGoogleStyle()));
237   EXPECT_EQ("/* something */ inline namespace N {\n"
238             "\n"
239             "int i;\n"
240             "}",
241             format("/* something */ inline namespace N {\n"
242                    "\n"
243                    "int    i;\n"
244                    "}",
245                    getGoogleStyle()));
246   EXPECT_EQ("export namespace N {\n"
247             "\n"
248             "int i;\n"
249             "}",
250             format("export namespace N {\n"
251                    "\n"
252                    "int    i;\n"
253                    "}",
254                    getGoogleStyle()));
255   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
256             "\n"
257             "int i;\n"
258             "}",
259             format("extern /**/ \"C\" /**/ {\n"
260                    "\n"
261                    "int    i;\n"
262                    "}",
263                    getGoogleStyle()));
264 
265   // ...but do keep inlining and removing empty lines for non-block extern "C"
266   // functions.
267   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
268   EXPECT_EQ("extern \"C\" int f() {\n"
269             "  int i = 42;\n"
270             "  return i;\n"
271             "}",
272             format("extern \"C\" int f() {\n"
273                    "\n"
274                    "  int i = 42;\n"
275                    "  return i;\n"
276                    "}",
277                    getGoogleStyle()));
278 
279   // Remove empty lines at the beginning and end of blocks.
280   EXPECT_EQ("void f() {\n"
281             "\n"
282             "  if (a) {\n"
283             "\n"
284             "    f();\n"
285             "  }\n"
286             "}",
287             format("void f() {\n"
288                    "\n"
289                    "  if (a) {\n"
290                    "\n"
291                    "    f();\n"
292                    "\n"
293                    "  }\n"
294                    "\n"
295                    "}",
296                    getLLVMStyle()));
297   EXPECT_EQ("void f() {\n"
298             "  if (a) {\n"
299             "    f();\n"
300             "  }\n"
301             "}",
302             format("void f() {\n"
303                    "\n"
304                    "  if (a) {\n"
305                    "\n"
306                    "    f();\n"
307                    "\n"
308                    "  }\n"
309                    "\n"
310                    "}",
311                    getGoogleStyle()));
312 
313   // Don't remove empty lines in more complex control statements.
314   EXPECT_EQ("void f() {\n"
315             "  if (a) {\n"
316             "    f();\n"
317             "\n"
318             "  } else if (b) {\n"
319             "    f();\n"
320             "  }\n"
321             "}",
322             format("void f() {\n"
323                    "  if (a) {\n"
324                    "    f();\n"
325                    "\n"
326                    "  } else if (b) {\n"
327                    "    f();\n"
328                    "\n"
329                    "  }\n"
330                    "\n"
331                    "}"));
332 
333   // Don't remove empty lines before namespace endings.
334   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
335   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
336   EXPECT_EQ("namespace {\n"
337             "int i;\n"
338             "\n"
339             "}",
340             format("namespace {\n"
341                    "int i;\n"
342                    "\n"
343                    "}",
344                    LLVMWithNoNamespaceFix));
345   EXPECT_EQ("namespace {\n"
346             "int i;\n"
347             "}",
348             format("namespace {\n"
349                    "int i;\n"
350                    "}",
351                    LLVMWithNoNamespaceFix));
352   EXPECT_EQ("namespace {\n"
353             "int i;\n"
354             "\n"
355             "};",
356             format("namespace {\n"
357                    "int i;\n"
358                    "\n"
359                    "};",
360                    LLVMWithNoNamespaceFix));
361   EXPECT_EQ("namespace {\n"
362             "int i;\n"
363             "};",
364             format("namespace {\n"
365                    "int i;\n"
366                    "};",
367                    LLVMWithNoNamespaceFix));
368   EXPECT_EQ("namespace {\n"
369             "int i;\n"
370             "\n"
371             "}",
372             format("namespace {\n"
373                    "int i;\n"
374                    "\n"
375                    "}"));
376   EXPECT_EQ("namespace {\n"
377             "int i;\n"
378             "\n"
379             "} // namespace",
380             format("namespace {\n"
381                    "int i;\n"
382                    "\n"
383                    "}  // namespace"));
384 
385   FormatStyle Style = getLLVMStyle();
386   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
387   Style.MaxEmptyLinesToKeep = 2;
388   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
389   Style.BraceWrapping.AfterClass = true;
390   Style.BraceWrapping.AfterFunction = true;
391   Style.KeepEmptyLinesAtTheStartOfBlocks = false;
392 
393   EXPECT_EQ("class Foo\n"
394             "{\n"
395             "  Foo() {}\n"
396             "\n"
397             "  void funk() {}\n"
398             "};",
399             format("class Foo\n"
400                    "{\n"
401                    "  Foo()\n"
402                    "  {\n"
403                    "  }\n"
404                    "\n"
405                    "  void funk() {}\n"
406                    "};",
407                    Style));
408 }
409 
410 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
411   verifyFormat("x = (a) and (b);");
412   verifyFormat("x = (a) or (b);");
413   verifyFormat("x = (a) bitand (b);");
414   verifyFormat("x = (a) bitor (b);");
415   verifyFormat("x = (a) not_eq (b);");
416   verifyFormat("x = (a) and_eq (b);");
417   verifyFormat("x = (a) or_eq (b);");
418   verifyFormat("x = (a) xor (b);");
419 }
420 
421 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
422   verifyFormat("x = compl(a);");
423   verifyFormat("x = not(a);");
424   verifyFormat("x = bitand(a);");
425   // Unary operator must not be merged with the next identifier
426   verifyFormat("x = compl a;");
427   verifyFormat("x = not a;");
428   verifyFormat("x = bitand a;");
429 }
430 
431 //===----------------------------------------------------------------------===//
432 // Tests for control statements.
433 //===----------------------------------------------------------------------===//
434 
435 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
436   verifyFormat("if (true)\n  f();\ng();");
437   verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
438   verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
439   verifyFormat("if constexpr (true)\n"
440                "  f();\ng();");
441   verifyFormat("if CONSTEXPR (true)\n"
442                "  f();\ng();");
443   verifyFormat("if constexpr (a)\n"
444                "  if constexpr (b)\n"
445                "    if constexpr (c)\n"
446                "      g();\n"
447                "h();");
448   verifyFormat("if CONSTEXPR (a)\n"
449                "  if CONSTEXPR (b)\n"
450                "    if CONSTEXPR (c)\n"
451                "      g();\n"
452                "h();");
453   verifyFormat("if constexpr (a)\n"
454                "  if constexpr (b) {\n"
455                "    f();\n"
456                "  }\n"
457                "g();");
458   verifyFormat("if CONSTEXPR (a)\n"
459                "  if CONSTEXPR (b) {\n"
460                "    f();\n"
461                "  }\n"
462                "g();");
463 
464   FormatStyle AllowsMergedIf = getLLVMStyle();
465   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
466   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
467       FormatStyle::SIS_WithoutElse;
468   verifyFormat("if (a)\n"
469                "  // comment\n"
470                "  f();",
471                AllowsMergedIf);
472   verifyFormat("{\n"
473                "  if (a)\n"
474                "  label:\n"
475                "    f();\n"
476                "}",
477                AllowsMergedIf);
478   verifyFormat("#define A \\\n"
479                "  if (a)  \\\n"
480                "  label:  \\\n"
481                "    f()",
482                AllowsMergedIf);
483   verifyFormat("if (a)\n"
484                "  ;",
485                AllowsMergedIf);
486   verifyFormat("if (a)\n"
487                "  if (b) return;",
488                AllowsMergedIf);
489 
490   verifyFormat("if (a) // Can't merge this\n"
491                "  f();\n",
492                AllowsMergedIf);
493   verifyFormat("if (a) /* still don't merge */\n"
494                "  f();",
495                AllowsMergedIf);
496   verifyFormat("if (a) { // Never merge this\n"
497                "  f();\n"
498                "}",
499                AllowsMergedIf);
500   verifyFormat("if (a) { /* Never merge this */\n"
501                "  f();\n"
502                "}",
503                AllowsMergedIf);
504 
505   AllowsMergedIf.ColumnLimit = 14;
506   verifyFormat("if (a) return;", AllowsMergedIf);
507   verifyFormat("if (aaaaaaaaa)\n"
508                "  return;",
509                AllowsMergedIf);
510 
511   AllowsMergedIf.ColumnLimit = 13;
512   verifyFormat("if (a)\n  return;", AllowsMergedIf);
513 }
514 
515 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
516   FormatStyle AllowsMergedIf = getLLVMStyle();
517   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
518   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
519       FormatStyle::SIS_WithoutElse;
520   verifyFormat("if (a)\n"
521                "  f();\n"
522                "else {\n"
523                "  g();\n"
524                "}",
525                AllowsMergedIf);
526   verifyFormat("if (a)\n"
527                "  f();\n"
528                "else\n"
529                "  g();\n",
530                AllowsMergedIf);
531 
532   AllowsMergedIf.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
533 
534   verifyFormat("if (a) f();\n"
535                "else {\n"
536                "  g();\n"
537                "}",
538                AllowsMergedIf);
539   verifyFormat("if (a) f();\n"
540                "else {\n"
541                "  if (a) f();\n"
542                "  else {\n"
543                "    g();\n"
544                "  }\n"
545                "  g();\n"
546                "}",
547                AllowsMergedIf);
548 }
549 
550 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
551   FormatStyle AllowsMergedLoops = getLLVMStyle();
552   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
553   verifyFormat("while (true) continue;", AllowsMergedLoops);
554   verifyFormat("for (;;) continue;", AllowsMergedLoops);
555   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
556   verifyFormat("while (true)\n"
557                "  ;",
558                AllowsMergedLoops);
559   verifyFormat("for (;;)\n"
560                "  ;",
561                AllowsMergedLoops);
562   verifyFormat("for (;;)\n"
563                "  for (;;) continue;",
564                AllowsMergedLoops);
565   verifyFormat("for (;;) // Can't merge this\n"
566                "  continue;",
567                AllowsMergedLoops);
568   verifyFormat("for (;;) /* still don't merge */\n"
569                "  continue;",
570                AllowsMergedLoops);
571   verifyFormat("do a++;\n"
572                "while (true);",
573                AllowsMergedLoops);
574   verifyFormat("do /* Don't merge */\n"
575                "  a++;\n"
576                "while (true);",
577                AllowsMergedLoops);
578   verifyFormat("do // Don't merge\n"
579                "  a++;\n"
580                "while (true);",
581                AllowsMergedLoops);
582   verifyFormat("do\n"
583                "  // Don't merge\n"
584                "  a++;\n"
585                "while (true);",
586                AllowsMergedLoops);
587   // Without braces labels are interpreted differently.
588   verifyFormat("{\n"
589                "  do\n"
590                "  label:\n"
591                "    a++;\n"
592                "  while (true);\n"
593                "}",
594                AllowsMergedLoops);
595 }
596 
597 TEST_F(FormatTest, FormatShortBracedStatements) {
598   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
599   AllowSimpleBracedStatements.ColumnLimit = 40;
600   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
601       FormatStyle::SBS_Always;
602 
603   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
604       FormatStyle::SIS_WithoutElse;
605   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
606 
607   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
608   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
609   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
610 
611   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
612   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
613   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
614   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
615   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
616   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
617   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
618   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
619   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
620   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
621   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
622                AllowSimpleBracedStatements);
623   verifyFormat("if (true) {\n"
624                "  ffffffffffffffffffffffff();\n"
625                "}",
626                AllowSimpleBracedStatements);
627   verifyFormat("if (true) {\n"
628                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
629                "}",
630                AllowSimpleBracedStatements);
631   verifyFormat("if (true) { //\n"
632                "  f();\n"
633                "}",
634                AllowSimpleBracedStatements);
635   verifyFormat("if (true) {\n"
636                "  f();\n"
637                "  f();\n"
638                "}",
639                AllowSimpleBracedStatements);
640   verifyFormat("if (true) {\n"
641                "  f();\n"
642                "} else {\n"
643                "  f();\n"
644                "}",
645                AllowSimpleBracedStatements);
646 
647   verifyFormat("struct A2 {\n"
648                "  int X;\n"
649                "};",
650                AllowSimpleBracedStatements);
651   verifyFormat("typedef struct A2 {\n"
652                "  int X;\n"
653                "} A2_t;",
654                AllowSimpleBracedStatements);
655   verifyFormat("template <int> struct A2 {\n"
656                "  struct B {};\n"
657                "};",
658                AllowSimpleBracedStatements);
659 
660   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
661       FormatStyle::SIS_Never;
662   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
663   verifyFormat("if (true) {\n"
664                "  f();\n"
665                "}",
666                AllowSimpleBracedStatements);
667   verifyFormat("if (true) {\n"
668                "  f();\n"
669                "} else {\n"
670                "  f();\n"
671                "}",
672                AllowSimpleBracedStatements);
673 
674   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
675   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
676   verifyFormat("while (true) {\n"
677                "  f();\n"
678                "}",
679                AllowSimpleBracedStatements);
680   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
681   verifyFormat("for (;;) {\n"
682                "  f();\n"
683                "}",
684                AllowSimpleBracedStatements);
685 
686   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
687       FormatStyle::SIS_WithoutElse;
688   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
689   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
690       FormatStyle::BWACS_Always;
691 
692   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
693   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
694   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
695   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
696   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
697   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
698   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
699   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
700   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
701   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
702   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
703                AllowSimpleBracedStatements);
704   verifyFormat("if (true)\n"
705                "{\n"
706                "  ffffffffffffffffffffffff();\n"
707                "}",
708                AllowSimpleBracedStatements);
709   verifyFormat("if (true)\n"
710                "{\n"
711                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
712                "}",
713                AllowSimpleBracedStatements);
714   verifyFormat("if (true)\n"
715                "{ //\n"
716                "  f();\n"
717                "}",
718                AllowSimpleBracedStatements);
719   verifyFormat("if (true)\n"
720                "{\n"
721                "  f();\n"
722                "  f();\n"
723                "}",
724                AllowSimpleBracedStatements);
725   verifyFormat("if (true)\n"
726                "{\n"
727                "  f();\n"
728                "} else\n"
729                "{\n"
730                "  f();\n"
731                "}",
732                AllowSimpleBracedStatements);
733 
734   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
735       FormatStyle::SIS_Never;
736   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
737   verifyFormat("if (true)\n"
738                "{\n"
739                "  f();\n"
740                "}",
741                AllowSimpleBracedStatements);
742   verifyFormat("if (true)\n"
743                "{\n"
744                "  f();\n"
745                "} else\n"
746                "{\n"
747                "  f();\n"
748                "}",
749                AllowSimpleBracedStatements);
750 
751   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
752   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
753   verifyFormat("while (true)\n"
754                "{\n"
755                "  f();\n"
756                "}",
757                AllowSimpleBracedStatements);
758   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
759   verifyFormat("for (;;)\n"
760                "{\n"
761                "  f();\n"
762                "}",
763                AllowSimpleBracedStatements);
764 }
765 
766 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
767   FormatStyle Style = getLLVMStyleWithColumns(60);
768   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
769   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
770   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
771   EXPECT_EQ("#define A                                                  \\\n"
772             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
773             "  {                                                        \\\n"
774             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
775             "  }\n"
776             "X;",
777             format("#define A \\\n"
778                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
779                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
780                    "   }\n"
781                    "X;",
782                    Style));
783 }
784 
785 TEST_F(FormatTest, ParseIfElse) {
786   verifyFormat("if (true)\n"
787                "  if (true)\n"
788                "    if (true)\n"
789                "      f();\n"
790                "    else\n"
791                "      g();\n"
792                "  else\n"
793                "    h();\n"
794                "else\n"
795                "  i();");
796   verifyFormat("if (true)\n"
797                "  if (true)\n"
798                "    if (true) {\n"
799                "      if (true)\n"
800                "        f();\n"
801                "    } else {\n"
802                "      g();\n"
803                "    }\n"
804                "  else\n"
805                "    h();\n"
806                "else {\n"
807                "  i();\n"
808                "}");
809   verifyFormat("if (true)\n"
810                "  if constexpr (true)\n"
811                "    if (true) {\n"
812                "      if constexpr (true)\n"
813                "        f();\n"
814                "    } else {\n"
815                "      g();\n"
816                "    }\n"
817                "  else\n"
818                "    h();\n"
819                "else {\n"
820                "  i();\n"
821                "}");
822   verifyFormat("if (true)\n"
823                "  if CONSTEXPR (true)\n"
824                "    if (true) {\n"
825                "      if CONSTEXPR (true)\n"
826                "        f();\n"
827                "    } else {\n"
828                "      g();\n"
829                "    }\n"
830                "  else\n"
831                "    h();\n"
832                "else {\n"
833                "  i();\n"
834                "}");
835   verifyFormat("void f() {\n"
836                "  if (a) {\n"
837                "  } else {\n"
838                "  }\n"
839                "}");
840 }
841 
842 TEST_F(FormatTest, ElseIf) {
843   verifyFormat("if (a) {\n} else if (b) {\n}");
844   verifyFormat("if (a)\n"
845                "  f();\n"
846                "else if (b)\n"
847                "  g();\n"
848                "else\n"
849                "  h();");
850   verifyFormat("if constexpr (a)\n"
851                "  f();\n"
852                "else if constexpr (b)\n"
853                "  g();\n"
854                "else\n"
855                "  h();");
856   verifyFormat("if CONSTEXPR (a)\n"
857                "  f();\n"
858                "else if CONSTEXPR (b)\n"
859                "  g();\n"
860                "else\n"
861                "  h();");
862   verifyFormat("if (a) {\n"
863                "  f();\n"
864                "}\n"
865                "// or else ..\n"
866                "else {\n"
867                "  g()\n"
868                "}");
869 
870   verifyFormat("if (a) {\n"
871                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
872                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
873                "}");
874   verifyFormat("if (a) {\n"
875                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
876                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
877                "}");
878   verifyFormat("if (a) {\n"
879                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
880                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
881                "}");
882   verifyFormat("if (a) {\n"
883                "} else if (\n"
884                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
885                "}",
886                getLLVMStyleWithColumns(62));
887   verifyFormat("if (a) {\n"
888                "} else if constexpr (\n"
889                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
890                "}",
891                getLLVMStyleWithColumns(62));
892   verifyFormat("if (a) {\n"
893                "} else if CONSTEXPR (\n"
894                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
895                "}",
896                getLLVMStyleWithColumns(62));
897 }
898 
899 TEST_F(FormatTest, FormatsForLoop) {
900   verifyFormat(
901       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
902       "     ++VeryVeryLongLoopVariable)\n"
903       "  ;");
904   verifyFormat("for (;;)\n"
905                "  f();");
906   verifyFormat("for (;;) {\n}");
907   verifyFormat("for (;;) {\n"
908                "  f();\n"
909                "}");
910   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
911 
912   verifyFormat(
913       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
914       "                                          E = UnwrappedLines.end();\n"
915       "     I != E; ++I) {\n}");
916 
917   verifyFormat(
918       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
919       "     ++IIIII) {\n}");
920   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
921                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
922                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
923   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
924                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
925                "         E = FD->getDeclsInPrototypeScope().end();\n"
926                "     I != E; ++I) {\n}");
927   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
928                "         I = Container.begin(),\n"
929                "         E = Container.end();\n"
930                "     I != E; ++I) {\n}",
931                getLLVMStyleWithColumns(76));
932 
933   verifyFormat(
934       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
935       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
936       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
937       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
938       "     ++aaaaaaaaaaa) {\n}");
939   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
940                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
941                "     ++i) {\n}");
942   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
943                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
944                "}");
945   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
946                "         aaaaaaaaaa);\n"
947                "     iter; ++iter) {\n"
948                "}");
949   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
950                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
951                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
952                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
953 
954   // These should not be formatted as Objective-C for-in loops.
955   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
956   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
957   verifyFormat("Foo *x;\nfor (x in y) {\n}");
958   verifyFormat(
959       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
960 
961   FormatStyle NoBinPacking = getLLVMStyle();
962   NoBinPacking.BinPackParameters = false;
963   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
964                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
965                "                                           aaaaaaaaaaaaaaaa,\n"
966                "                                           aaaaaaaaaaaaaaaa,\n"
967                "                                           aaaaaaaaaaaaaaaa);\n"
968                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
969                "}",
970                NoBinPacking);
971   verifyFormat(
972       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
973       "                                          E = UnwrappedLines.end();\n"
974       "     I != E;\n"
975       "     ++I) {\n}",
976       NoBinPacking);
977 
978   FormatStyle AlignLeft = getLLVMStyle();
979   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
980   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
981 }
982 
983 TEST_F(FormatTest, RangeBasedForLoops) {
984   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
985                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
986   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
987                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
988   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
989                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
990   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
991                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
992 }
993 
994 TEST_F(FormatTest, ForEachLoops) {
995   verifyFormat("void f() {\n"
996                "  foreach (Item *item, itemlist) {}\n"
997                "  Q_FOREACH (Item *item, itemlist) {}\n"
998                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
999                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
1000                "}");
1001 
1002   FormatStyle Style = getLLVMStyle();
1003   Style.SpaceBeforeParens =
1004       FormatStyle::SBPO_ControlStatementsExceptForEachMacros;
1005   verifyFormat("void f() {\n"
1006                "  foreach(Item *item, itemlist) {}\n"
1007                "  Q_FOREACH(Item *item, itemlist) {}\n"
1008                "  BOOST_FOREACH(Item *item, itemlist) {}\n"
1009                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
1010                "}",
1011                Style);
1012 
1013   // As function-like macros.
1014   verifyFormat("#define foreach(x, y)\n"
1015                "#define Q_FOREACH(x, y)\n"
1016                "#define BOOST_FOREACH(x, y)\n"
1017                "#define UNKNOWN_FOREACH(x, y)\n");
1018 
1019   // Not as function-like macros.
1020   verifyFormat("#define foreach (x, y)\n"
1021                "#define Q_FOREACH (x, y)\n"
1022                "#define BOOST_FOREACH (x, y)\n"
1023                "#define UNKNOWN_FOREACH (x, y)\n");
1024 
1025   // handle microsoft non standard extension
1026   verifyFormat("for each (char c in x->MyStringProperty)");
1027 }
1028 
1029 TEST_F(FormatTest, FormatsWhileLoop) {
1030   verifyFormat("while (true) {\n}");
1031   verifyFormat("while (true)\n"
1032                "  f();");
1033   verifyFormat("while () {\n}");
1034   verifyFormat("while () {\n"
1035                "  f();\n"
1036                "}");
1037 }
1038 
1039 TEST_F(FormatTest, FormatsDoWhile) {
1040   verifyFormat("do {\n"
1041                "  do_something();\n"
1042                "} while (something());");
1043   verifyFormat("do\n"
1044                "  do_something();\n"
1045                "while (something());");
1046 }
1047 
1048 TEST_F(FormatTest, FormatsSwitchStatement) {
1049   verifyFormat("switch (x) {\n"
1050                "case 1:\n"
1051                "  f();\n"
1052                "  break;\n"
1053                "case kFoo:\n"
1054                "case ns::kBar:\n"
1055                "case kBaz:\n"
1056                "  break;\n"
1057                "default:\n"
1058                "  g();\n"
1059                "  break;\n"
1060                "}");
1061   verifyFormat("switch (x) {\n"
1062                "case 1: {\n"
1063                "  f();\n"
1064                "  break;\n"
1065                "}\n"
1066                "case 2: {\n"
1067                "  break;\n"
1068                "}\n"
1069                "}");
1070   verifyFormat("switch (x) {\n"
1071                "case 1: {\n"
1072                "  f();\n"
1073                "  {\n"
1074                "    g();\n"
1075                "    h();\n"
1076                "  }\n"
1077                "  break;\n"
1078                "}\n"
1079                "}");
1080   verifyFormat("switch (x) {\n"
1081                "case 1: {\n"
1082                "  f();\n"
1083                "  if (foo) {\n"
1084                "    g();\n"
1085                "    h();\n"
1086                "  }\n"
1087                "  break;\n"
1088                "}\n"
1089                "}");
1090   verifyFormat("switch (x) {\n"
1091                "case 1: {\n"
1092                "  f();\n"
1093                "  g();\n"
1094                "} break;\n"
1095                "}");
1096   verifyFormat("switch (test)\n"
1097                "  ;");
1098   verifyFormat("switch (x) {\n"
1099                "default: {\n"
1100                "  // Do nothing.\n"
1101                "}\n"
1102                "}");
1103   verifyFormat("switch (x) {\n"
1104                "// comment\n"
1105                "// if 1, do f()\n"
1106                "case 1:\n"
1107                "  f();\n"
1108                "}");
1109   verifyFormat("switch (x) {\n"
1110                "case 1:\n"
1111                "  // Do amazing stuff\n"
1112                "  {\n"
1113                "    f();\n"
1114                "    g();\n"
1115                "  }\n"
1116                "  break;\n"
1117                "}");
1118   verifyFormat("#define A          \\\n"
1119                "  switch (x) {     \\\n"
1120                "  case a:          \\\n"
1121                "    foo = b;       \\\n"
1122                "  }",
1123                getLLVMStyleWithColumns(20));
1124   verifyFormat("#define OPERATION_CASE(name)           \\\n"
1125                "  case OP_name:                        \\\n"
1126                "    return operations::Operation##name\n",
1127                getLLVMStyleWithColumns(40));
1128   verifyFormat("switch (x) {\n"
1129                "case 1:;\n"
1130                "default:;\n"
1131                "  int i;\n"
1132                "}");
1133 
1134   verifyGoogleFormat("switch (x) {\n"
1135                      "  case 1:\n"
1136                      "    f();\n"
1137                      "    break;\n"
1138                      "  case kFoo:\n"
1139                      "  case ns::kBar:\n"
1140                      "  case kBaz:\n"
1141                      "    break;\n"
1142                      "  default:\n"
1143                      "    g();\n"
1144                      "    break;\n"
1145                      "}");
1146   verifyGoogleFormat("switch (x) {\n"
1147                      "  case 1: {\n"
1148                      "    f();\n"
1149                      "    break;\n"
1150                      "  }\n"
1151                      "}");
1152   verifyGoogleFormat("switch (test)\n"
1153                      "  ;");
1154 
1155   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
1156                      "  case OP_name:              \\\n"
1157                      "    return operations::Operation##name\n");
1158   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
1159                      "  // Get the correction operation class.\n"
1160                      "  switch (OpCode) {\n"
1161                      "    CASE(Add);\n"
1162                      "    CASE(Subtract);\n"
1163                      "    default:\n"
1164                      "      return operations::Unknown;\n"
1165                      "  }\n"
1166                      "#undef OPERATION_CASE\n"
1167                      "}");
1168   verifyFormat("DEBUG({\n"
1169                "  switch (x) {\n"
1170                "  case A:\n"
1171                "    f();\n"
1172                "    break;\n"
1173                "    // fallthrough\n"
1174                "  case B:\n"
1175                "    g();\n"
1176                "    break;\n"
1177                "  }\n"
1178                "});");
1179   EXPECT_EQ("DEBUG({\n"
1180             "  switch (x) {\n"
1181             "  case A:\n"
1182             "    f();\n"
1183             "    break;\n"
1184             "  // On B:\n"
1185             "  case B:\n"
1186             "    g();\n"
1187             "    break;\n"
1188             "  }\n"
1189             "});",
1190             format("DEBUG({\n"
1191                    "  switch (x) {\n"
1192                    "  case A:\n"
1193                    "    f();\n"
1194                    "    break;\n"
1195                    "  // On B:\n"
1196                    "  case B:\n"
1197                    "    g();\n"
1198                    "    break;\n"
1199                    "  }\n"
1200                    "});",
1201                    getLLVMStyle()));
1202   EXPECT_EQ("switch (n) {\n"
1203             "case 0: {\n"
1204             "  return false;\n"
1205             "}\n"
1206             "default: {\n"
1207             "  return true;\n"
1208             "}\n"
1209             "}",
1210             format("switch (n)\n"
1211                    "{\n"
1212                    "case 0: {\n"
1213                    "  return false;\n"
1214                    "}\n"
1215                    "default: {\n"
1216                    "  return true;\n"
1217                    "}\n"
1218                    "}",
1219                    getLLVMStyle()));
1220   verifyFormat("switch (a) {\n"
1221                "case (b):\n"
1222                "  return;\n"
1223                "}");
1224 
1225   verifyFormat("switch (a) {\n"
1226                "case some_namespace::\n"
1227                "    some_constant:\n"
1228                "  return;\n"
1229                "}",
1230                getLLVMStyleWithColumns(34));
1231 
1232   FormatStyle Style = getLLVMStyle();
1233   Style.IndentCaseLabels = true;
1234   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1235   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1236   Style.BraceWrapping.AfterCaseLabel = true;
1237   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1238   EXPECT_EQ("switch (n)\n"
1239             "{\n"
1240             "  case 0:\n"
1241             "  {\n"
1242             "    return false;\n"
1243             "  }\n"
1244             "  default:\n"
1245             "  {\n"
1246             "    return true;\n"
1247             "  }\n"
1248             "}",
1249             format("switch (n) {\n"
1250                    "  case 0: {\n"
1251                    "    return false;\n"
1252                    "  }\n"
1253                    "  default: {\n"
1254                    "    return true;\n"
1255                    "  }\n"
1256                    "}",
1257                    Style));
1258   Style.BraceWrapping.AfterCaseLabel = false;
1259   EXPECT_EQ("switch (n)\n"
1260             "{\n"
1261             "  case 0: {\n"
1262             "    return false;\n"
1263             "  }\n"
1264             "  default: {\n"
1265             "    return true;\n"
1266             "  }\n"
1267             "}",
1268             format("switch (n) {\n"
1269                    "  case 0:\n"
1270                    "  {\n"
1271                    "    return false;\n"
1272                    "  }\n"
1273                    "  default:\n"
1274                    "  {\n"
1275                    "    return true;\n"
1276                    "  }\n"
1277                    "}",
1278                    Style));
1279   Style.IndentCaseLabels = false;
1280   Style.IndentCaseBlocks = true;
1281   EXPECT_EQ("switch (n)\n"
1282             "{\n"
1283             "case 0:\n"
1284             "  {\n"
1285             "    return false;\n"
1286             "  }\n"
1287             "case 1:\n"
1288             "  break;\n"
1289             "default:\n"
1290             "  {\n"
1291             "    return true;\n"
1292             "  }\n"
1293             "}",
1294             format("switch (n) {\n"
1295                    "case 0: {\n"
1296                    "  return false;\n"
1297                    "}\n"
1298                    "case 1:\n"
1299                    "  break;\n"
1300                    "default: {\n"
1301                    "  return true;\n"
1302                    "}\n"
1303                    "}",
1304                    Style));
1305   Style.IndentCaseLabels = true;
1306   Style.IndentCaseBlocks = true;
1307   EXPECT_EQ("switch (n)\n"
1308             "{\n"
1309             "  case 0:\n"
1310             "    {\n"
1311             "      return false;\n"
1312             "    }\n"
1313             "  case 1:\n"
1314             "    break;\n"
1315             "  default:\n"
1316             "    {\n"
1317             "      return true;\n"
1318             "    }\n"
1319             "}",
1320             format("switch (n) {\n"
1321                    "case 0: {\n"
1322                    "  return false;\n"
1323                    "}\n"
1324                    "case 1:\n"
1325                    "  break;\n"
1326                    "default: {\n"
1327                    "  return true;\n"
1328                    "}\n"
1329                    "}",
1330                    Style));
1331 }
1332 
1333 TEST_F(FormatTest, CaseRanges) {
1334   verifyFormat("switch (x) {\n"
1335                "case 'A' ... 'Z':\n"
1336                "case 1 ... 5:\n"
1337                "case a ... b:\n"
1338                "  break;\n"
1339                "}");
1340 }
1341 
1342 TEST_F(FormatTest, ShortEnums) {
1343   FormatStyle Style = getLLVMStyle();
1344   Style.AllowShortEnumsOnASingleLine = true;
1345   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
1346   Style.AllowShortEnumsOnASingleLine = false;
1347   verifyFormat("enum\n"
1348                "{\n"
1349                "  A,\n"
1350                "  B,\n"
1351                "  C\n"
1352                "} ShortEnum1, ShortEnum2;",
1353                Style);
1354 }
1355 
1356 TEST_F(FormatTest, ShortCaseLabels) {
1357   FormatStyle Style = getLLVMStyle();
1358   Style.AllowShortCaseLabelsOnASingleLine = true;
1359   verifyFormat("switch (a) {\n"
1360                "case 1: x = 1; break;\n"
1361                "case 2: return;\n"
1362                "case 3:\n"
1363                "case 4:\n"
1364                "case 5: return;\n"
1365                "case 6: // comment\n"
1366                "  return;\n"
1367                "case 7:\n"
1368                "  // comment\n"
1369                "  return;\n"
1370                "case 8:\n"
1371                "  x = 8; // comment\n"
1372                "  break;\n"
1373                "default: y = 1; break;\n"
1374                "}",
1375                Style);
1376   verifyFormat("switch (a) {\n"
1377                "case 0: return; // comment\n"
1378                "case 1: break;  // comment\n"
1379                "case 2: return;\n"
1380                "// comment\n"
1381                "case 3: return;\n"
1382                "// comment 1\n"
1383                "// comment 2\n"
1384                "// comment 3\n"
1385                "case 4: break; /* comment */\n"
1386                "case 5:\n"
1387                "  // comment\n"
1388                "  break;\n"
1389                "case 6: /* comment */ x = 1; break;\n"
1390                "case 7: x = /* comment */ 1; break;\n"
1391                "case 8:\n"
1392                "  x = 1; /* comment */\n"
1393                "  break;\n"
1394                "case 9:\n"
1395                "  break; // comment line 1\n"
1396                "         // comment line 2\n"
1397                "}",
1398                Style);
1399   EXPECT_EQ("switch (a) {\n"
1400             "case 1:\n"
1401             "  x = 8;\n"
1402             "  // fall through\n"
1403             "case 2: x = 8;\n"
1404             "// comment\n"
1405             "case 3:\n"
1406             "  return; /* comment line 1\n"
1407             "           * comment line 2 */\n"
1408             "case 4: i = 8;\n"
1409             "// something else\n"
1410             "#if FOO\n"
1411             "case 5: break;\n"
1412             "#endif\n"
1413             "}",
1414             format("switch (a) {\n"
1415                    "case 1: x = 8;\n"
1416                    "  // fall through\n"
1417                    "case 2:\n"
1418                    "  x = 8;\n"
1419                    "// comment\n"
1420                    "case 3:\n"
1421                    "  return; /* comment line 1\n"
1422                    "           * comment line 2 */\n"
1423                    "case 4:\n"
1424                    "  i = 8;\n"
1425                    "// something else\n"
1426                    "#if FOO\n"
1427                    "case 5: break;\n"
1428                    "#endif\n"
1429                    "}",
1430                    Style));
1431   EXPECT_EQ("switch (a) {\n"
1432             "case 0:\n"
1433             "  return; // long long long long long long long long long long "
1434             "long long comment\n"
1435             "          // line\n"
1436             "}",
1437             format("switch (a) {\n"
1438                    "case 0: return; // long long long long long long long long "
1439                    "long long long long comment line\n"
1440                    "}",
1441                    Style));
1442   EXPECT_EQ("switch (a) {\n"
1443             "case 0:\n"
1444             "  return; /* long long long long long long long long long long "
1445             "long long comment\n"
1446             "             line */\n"
1447             "}",
1448             format("switch (a) {\n"
1449                    "case 0: return; /* long long long long long long long long "
1450                    "long long long long comment line */\n"
1451                    "}",
1452                    Style));
1453   verifyFormat("switch (a) {\n"
1454                "#if FOO\n"
1455                "case 0: return 0;\n"
1456                "#endif\n"
1457                "}",
1458                Style);
1459   verifyFormat("switch (a) {\n"
1460                "case 1: {\n"
1461                "}\n"
1462                "case 2: {\n"
1463                "  return;\n"
1464                "}\n"
1465                "case 3: {\n"
1466                "  x = 1;\n"
1467                "  return;\n"
1468                "}\n"
1469                "case 4:\n"
1470                "  if (x)\n"
1471                "    return;\n"
1472                "}",
1473                Style);
1474   Style.ColumnLimit = 21;
1475   verifyFormat("switch (a) {\n"
1476                "case 1: x = 1; break;\n"
1477                "case 2: return;\n"
1478                "case 3:\n"
1479                "case 4:\n"
1480                "case 5: return;\n"
1481                "default:\n"
1482                "  y = 1;\n"
1483                "  break;\n"
1484                "}",
1485                Style);
1486   Style.ColumnLimit = 80;
1487   Style.AllowShortCaseLabelsOnASingleLine = false;
1488   Style.IndentCaseLabels = true;
1489   EXPECT_EQ("switch (n) {\n"
1490             "  default /*comments*/:\n"
1491             "    return true;\n"
1492             "  case 0:\n"
1493             "    return false;\n"
1494             "}",
1495             format("switch (n) {\n"
1496                    "default/*comments*/:\n"
1497                    "  return true;\n"
1498                    "case 0:\n"
1499                    "  return false;\n"
1500                    "}",
1501                    Style));
1502   Style.AllowShortCaseLabelsOnASingleLine = true;
1503   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1504   Style.BraceWrapping.AfterCaseLabel = true;
1505   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1506   EXPECT_EQ("switch (n)\n"
1507             "{\n"
1508             "  case 0:\n"
1509             "  {\n"
1510             "    return false;\n"
1511             "  }\n"
1512             "  default:\n"
1513             "  {\n"
1514             "    return true;\n"
1515             "  }\n"
1516             "}",
1517             format("switch (n) {\n"
1518                    "  case 0: {\n"
1519                    "    return false;\n"
1520                    "  }\n"
1521                    "  default:\n"
1522                    "  {\n"
1523                    "    return true;\n"
1524                    "  }\n"
1525                    "}",
1526                    Style));
1527 }
1528 
1529 TEST_F(FormatTest, FormatsLabels) {
1530   verifyFormat("void f() {\n"
1531                "  some_code();\n"
1532                "test_label:\n"
1533                "  some_other_code();\n"
1534                "  {\n"
1535                "    some_more_code();\n"
1536                "  another_label:\n"
1537                "    some_more_code();\n"
1538                "  }\n"
1539                "}");
1540   verifyFormat("{\n"
1541                "  some_code();\n"
1542                "test_label:\n"
1543                "  some_other_code();\n"
1544                "}");
1545   verifyFormat("{\n"
1546                "  some_code();\n"
1547                "test_label:;\n"
1548                "  int i = 0;\n"
1549                "}");
1550   FormatStyle Style = getLLVMStyle();
1551   Style.IndentGotoLabels = false;
1552   verifyFormat("void f() {\n"
1553                "  some_code();\n"
1554                "test_label:\n"
1555                "  some_other_code();\n"
1556                "  {\n"
1557                "    some_more_code();\n"
1558                "another_label:\n"
1559                "    some_more_code();\n"
1560                "  }\n"
1561                "}",
1562                Style);
1563   verifyFormat("{\n"
1564                "  some_code();\n"
1565                "test_label:\n"
1566                "  some_other_code();\n"
1567                "}",
1568                Style);
1569   verifyFormat("{\n"
1570                "  some_code();\n"
1571                "test_label:;\n"
1572                "  int i = 0;\n"
1573                "}");
1574 }
1575 
1576 TEST_F(FormatTest, MultiLineControlStatements) {
1577   FormatStyle Style = getLLVMStyle();
1578   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
1579   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
1580   Style.ColumnLimit = 20;
1581   // Short lines should keep opening brace on same line.
1582   EXPECT_EQ("if (foo) {\n"
1583             "  bar();\n"
1584             "}",
1585             format("if(foo){bar();}", Style));
1586   EXPECT_EQ("if (foo) {\n"
1587             "  bar();\n"
1588             "} else {\n"
1589             "  baz();\n"
1590             "}",
1591             format("if(foo){bar();}else{baz();}", Style));
1592   EXPECT_EQ("if (foo && bar) {\n"
1593             "  baz();\n"
1594             "}",
1595             format("if(foo&&bar){baz();}", Style));
1596   EXPECT_EQ("if (foo) {\n"
1597             "  bar();\n"
1598             "} else if (baz) {\n"
1599             "  quux();\n"
1600             "}",
1601             format("if(foo){bar();}else if(baz){quux();}", Style));
1602   EXPECT_EQ(
1603       "if (foo) {\n"
1604       "  bar();\n"
1605       "} else if (baz) {\n"
1606       "  quux();\n"
1607       "} else {\n"
1608       "  foobar();\n"
1609       "}",
1610       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
1611   EXPECT_EQ("for (;;) {\n"
1612             "  foo();\n"
1613             "}",
1614             format("for(;;){foo();}"));
1615   EXPECT_EQ("while (1) {\n"
1616             "  foo();\n"
1617             "}",
1618             format("while(1){foo();}", Style));
1619   EXPECT_EQ("switch (foo) {\n"
1620             "case bar:\n"
1621             "  return;\n"
1622             "}",
1623             format("switch(foo){case bar:return;}", Style));
1624   EXPECT_EQ("try {\n"
1625             "  foo();\n"
1626             "} catch (...) {\n"
1627             "  bar();\n"
1628             "}",
1629             format("try{foo();}catch(...){bar();}", Style));
1630   EXPECT_EQ("do {\n"
1631             "  foo();\n"
1632             "} while (bar &&\n"
1633             "         baz);",
1634             format("do{foo();}while(bar&&baz);", Style));
1635   // Long lines should put opening brace on new line.
1636   EXPECT_EQ("if (foo && bar &&\n"
1637             "    baz)\n"
1638             "{\n"
1639             "  quux();\n"
1640             "}",
1641             format("if(foo&&bar&&baz){quux();}", Style));
1642   EXPECT_EQ("if (foo && bar &&\n"
1643             "    baz)\n"
1644             "{\n"
1645             "  quux();\n"
1646             "}",
1647             format("if (foo && bar &&\n"
1648                    "    baz) {\n"
1649                    "  quux();\n"
1650                    "}",
1651                    Style));
1652   EXPECT_EQ("if (foo) {\n"
1653             "  bar();\n"
1654             "} else if (baz ||\n"
1655             "           quux)\n"
1656             "{\n"
1657             "  foobar();\n"
1658             "}",
1659             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
1660   EXPECT_EQ(
1661       "if (foo) {\n"
1662       "  bar();\n"
1663       "} else if (baz ||\n"
1664       "           quux)\n"
1665       "{\n"
1666       "  foobar();\n"
1667       "} else {\n"
1668       "  barbaz();\n"
1669       "}",
1670       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
1671              Style));
1672   EXPECT_EQ("for (int i = 0;\n"
1673             "     i < 10; ++i)\n"
1674             "{\n"
1675             "  foo();\n"
1676             "}",
1677             format("for(int i=0;i<10;++i){foo();}", Style));
1678   EXPECT_EQ("foreach (int i,\n"
1679             "         list)\n"
1680             "{\n"
1681             "  foo();\n"
1682             "}",
1683             format("foreach(int i, list){foo();}", Style));
1684   Style.ColumnLimit =
1685       40; // to concentrate at brace wrapping, not line wrap due to column limit
1686   EXPECT_EQ("foreach (int i, list) {\n"
1687             "  foo();\n"
1688             "}",
1689             format("foreach(int i, list){foo();}", Style));
1690   Style.ColumnLimit =
1691       20; // to concentrate at brace wrapping, not line wrap due to column limit
1692   EXPECT_EQ("while (foo || bar ||\n"
1693             "       baz)\n"
1694             "{\n"
1695             "  quux();\n"
1696             "}",
1697             format("while(foo||bar||baz){quux();}", Style));
1698   EXPECT_EQ("switch (\n"
1699             "    foo = barbaz)\n"
1700             "{\n"
1701             "case quux:\n"
1702             "  return;\n"
1703             "}",
1704             format("switch(foo=barbaz){case quux:return;}", Style));
1705   EXPECT_EQ("try {\n"
1706             "  foo();\n"
1707             "} catch (\n"
1708             "    Exception &bar)\n"
1709             "{\n"
1710             "  baz();\n"
1711             "}",
1712             format("try{foo();}catch(Exception&bar){baz();}", Style));
1713   Style.ColumnLimit =
1714       40; // to concentrate at brace wrapping, not line wrap due to column limit
1715   EXPECT_EQ("try {\n"
1716             "  foo();\n"
1717             "} catch (Exception &bar) {\n"
1718             "  baz();\n"
1719             "}",
1720             format("try{foo();}catch(Exception&bar){baz();}", Style));
1721   Style.ColumnLimit =
1722       20; // to concentrate at brace wrapping, not line wrap due to column limit
1723 
1724   Style.BraceWrapping.BeforeElse = true;
1725   EXPECT_EQ(
1726       "if (foo) {\n"
1727       "  bar();\n"
1728       "}\n"
1729       "else if (baz ||\n"
1730       "         quux)\n"
1731       "{\n"
1732       "  foobar();\n"
1733       "}\n"
1734       "else {\n"
1735       "  barbaz();\n"
1736       "}",
1737       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
1738              Style));
1739 
1740   Style.BraceWrapping.BeforeCatch = true;
1741   EXPECT_EQ("try {\n"
1742             "  foo();\n"
1743             "}\n"
1744             "catch (...) {\n"
1745             "  baz();\n"
1746             "}",
1747             format("try{foo();}catch(...){baz();}", Style));
1748 }
1749 
1750 TEST_F(FormatTest, BeforeWhile) {
1751   FormatStyle Style = getLLVMStyle();
1752   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
1753 
1754   verifyFormat("do {\n"
1755                "  foo();\n"
1756                "} while (1);",
1757                Style);
1758   Style.BraceWrapping.BeforeWhile = true;
1759   verifyFormat("do {\n"
1760                "  foo();\n"
1761                "}\n"
1762                "while (1);",
1763                Style);
1764 }
1765 
1766 //===----------------------------------------------------------------------===//
1767 // Tests for classes, namespaces, etc.
1768 //===----------------------------------------------------------------------===//
1769 
1770 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
1771   verifyFormat("class A {};");
1772 }
1773 
1774 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
1775   verifyFormat("class A {\n"
1776                "public:\n"
1777                "public: // comment\n"
1778                "protected:\n"
1779                "private:\n"
1780                "  void f() {}\n"
1781                "};");
1782   verifyFormat("export class A {\n"
1783                "public:\n"
1784                "public: // comment\n"
1785                "protected:\n"
1786                "private:\n"
1787                "  void f() {}\n"
1788                "};");
1789   verifyGoogleFormat("class A {\n"
1790                      " public:\n"
1791                      " protected:\n"
1792                      " private:\n"
1793                      "  void f() {}\n"
1794                      "};");
1795   verifyGoogleFormat("export class A {\n"
1796                      " public:\n"
1797                      " protected:\n"
1798                      " private:\n"
1799                      "  void f() {}\n"
1800                      "};");
1801   verifyFormat("class A {\n"
1802                "public slots:\n"
1803                "  void f1() {}\n"
1804                "public Q_SLOTS:\n"
1805                "  void f2() {}\n"
1806                "protected slots:\n"
1807                "  void f3() {}\n"
1808                "protected Q_SLOTS:\n"
1809                "  void f4() {}\n"
1810                "private slots:\n"
1811                "  void f5() {}\n"
1812                "private Q_SLOTS:\n"
1813                "  void f6() {}\n"
1814                "signals:\n"
1815                "  void g1();\n"
1816                "Q_SIGNALS:\n"
1817                "  void g2();\n"
1818                "};");
1819 
1820   // Don't interpret 'signals' the wrong way.
1821   verifyFormat("signals.set();");
1822   verifyFormat("for (Signals signals : f()) {\n}");
1823   verifyFormat("{\n"
1824                "  signals.set(); // This needs indentation.\n"
1825                "}");
1826   verifyFormat("void f() {\n"
1827                "label:\n"
1828                "  signals.baz();\n"
1829                "}");
1830 }
1831 
1832 TEST_F(FormatTest, SeparatesLogicalBlocks) {
1833   EXPECT_EQ("class A {\n"
1834             "public:\n"
1835             "  void f();\n"
1836             "\n"
1837             "private:\n"
1838             "  void g() {}\n"
1839             "  // test\n"
1840             "protected:\n"
1841             "  int h;\n"
1842             "};",
1843             format("class A {\n"
1844                    "public:\n"
1845                    "void f();\n"
1846                    "private:\n"
1847                    "void g() {}\n"
1848                    "// test\n"
1849                    "protected:\n"
1850                    "int h;\n"
1851                    "};"));
1852   EXPECT_EQ("class A {\n"
1853             "protected:\n"
1854             "public:\n"
1855             "  void f();\n"
1856             "};",
1857             format("class A {\n"
1858                    "protected:\n"
1859                    "\n"
1860                    "public:\n"
1861                    "\n"
1862                    "  void f();\n"
1863                    "};"));
1864 
1865   // Even ensure proper spacing inside macros.
1866   EXPECT_EQ("#define B     \\\n"
1867             "  class A {   \\\n"
1868             "   protected: \\\n"
1869             "   public:    \\\n"
1870             "    void f(); \\\n"
1871             "  };",
1872             format("#define B     \\\n"
1873                    "  class A {   \\\n"
1874                    "   protected: \\\n"
1875                    "              \\\n"
1876                    "   public:    \\\n"
1877                    "              \\\n"
1878                    "    void f(); \\\n"
1879                    "  };",
1880                    getGoogleStyle()));
1881   // But don't remove empty lines after macros ending in access specifiers.
1882   EXPECT_EQ("#define A private:\n"
1883             "\n"
1884             "int i;",
1885             format("#define A         private:\n"
1886                    "\n"
1887                    "int              i;"));
1888 }
1889 
1890 TEST_F(FormatTest, FormatsClasses) {
1891   verifyFormat("class A : public B {};");
1892   verifyFormat("class A : public ::B {};");
1893 
1894   verifyFormat(
1895       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1896       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1897   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
1898                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1899                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1900   verifyFormat(
1901       "class A : public B, public C, public D, public E, public F {};");
1902   verifyFormat("class AAAAAAAAAAAA : public B,\n"
1903                "                     public C,\n"
1904                "                     public D,\n"
1905                "                     public E,\n"
1906                "                     public F,\n"
1907                "                     public G {};");
1908 
1909   verifyFormat("class\n"
1910                "    ReallyReallyLongClassName {\n"
1911                "  int i;\n"
1912                "};",
1913                getLLVMStyleWithColumns(32));
1914   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
1915                "                           aaaaaaaaaaaaaaaa> {};");
1916   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
1917                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
1918                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
1919   verifyFormat("template <class R, class C>\n"
1920                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
1921                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
1922   verifyFormat("class ::A::B {};");
1923 }
1924 
1925 TEST_F(FormatTest, BreakInheritanceStyle) {
1926   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
1927   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
1928       FormatStyle::BILS_BeforeComma;
1929   verifyFormat("class MyClass : public X {};",
1930                StyleWithInheritanceBreakBeforeComma);
1931   verifyFormat("class MyClass\n"
1932                "    : public X\n"
1933                "    , public Y {};",
1934                StyleWithInheritanceBreakBeforeComma);
1935   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
1936                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
1937                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
1938                StyleWithInheritanceBreakBeforeComma);
1939   verifyFormat("struct aaaaaaaaaaaaa\n"
1940                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
1941                "          aaaaaaaaaaaaaaaa> {};",
1942                StyleWithInheritanceBreakBeforeComma);
1943 
1944   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
1945   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
1946       FormatStyle::BILS_AfterColon;
1947   verifyFormat("class MyClass : public X {};",
1948                StyleWithInheritanceBreakAfterColon);
1949   verifyFormat("class MyClass : public X, public Y {};",
1950                StyleWithInheritanceBreakAfterColon);
1951   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
1952                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1953                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
1954                StyleWithInheritanceBreakAfterColon);
1955   verifyFormat("struct aaaaaaaaaaaaa :\n"
1956                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
1957                "        aaaaaaaaaaaaaaaa> {};",
1958                StyleWithInheritanceBreakAfterColon);
1959 }
1960 
1961 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
1962   verifyFormat("class A {\n} a, b;");
1963   verifyFormat("struct A {\n} a, b;");
1964   verifyFormat("union A {\n} a;");
1965 }
1966 
1967 TEST_F(FormatTest, FormatsEnum) {
1968   verifyFormat("enum {\n"
1969                "  Zero,\n"
1970                "  One = 1,\n"
1971                "  Two = One + 1,\n"
1972                "  Three = (One + Two),\n"
1973                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1974                "  Five = (One, Two, Three, Four, 5)\n"
1975                "};");
1976   verifyGoogleFormat("enum {\n"
1977                      "  Zero,\n"
1978                      "  One = 1,\n"
1979                      "  Two = One + 1,\n"
1980                      "  Three = (One + Two),\n"
1981                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1982                      "  Five = (One, Two, Three, Four, 5)\n"
1983                      "};");
1984   verifyFormat("enum Enum {};");
1985   verifyFormat("enum {};");
1986   verifyFormat("enum X E {} d;");
1987   verifyFormat("enum __attribute__((...)) E {} d;");
1988   verifyFormat("enum __declspec__((...)) E {} d;");
1989   verifyFormat("enum {\n"
1990                "  Bar = Foo<int, int>::value\n"
1991                "};",
1992                getLLVMStyleWithColumns(30));
1993 
1994   verifyFormat("enum ShortEnum { A, B, C };");
1995   verifyGoogleFormat("enum ShortEnum { A, B, C };");
1996 
1997   EXPECT_EQ("enum KeepEmptyLines {\n"
1998             "  ONE,\n"
1999             "\n"
2000             "  TWO,\n"
2001             "\n"
2002             "  THREE\n"
2003             "}",
2004             format("enum KeepEmptyLines {\n"
2005                    "  ONE,\n"
2006                    "\n"
2007                    "  TWO,\n"
2008                    "\n"
2009                    "\n"
2010                    "  THREE\n"
2011                    "}"));
2012   verifyFormat("enum E { // comment\n"
2013                "  ONE,\n"
2014                "  TWO\n"
2015                "};\n"
2016                "int i;");
2017 
2018   FormatStyle EightIndent = getLLVMStyle();
2019   EightIndent.IndentWidth = 8;
2020   verifyFormat("enum {\n"
2021                "        VOID,\n"
2022                "        CHAR,\n"
2023                "        SHORT,\n"
2024                "        INT,\n"
2025                "        LONG,\n"
2026                "        SIGNED,\n"
2027                "        UNSIGNED,\n"
2028                "        BOOL,\n"
2029                "        FLOAT,\n"
2030                "        DOUBLE,\n"
2031                "        COMPLEX\n"
2032                "};",
2033                EightIndent);
2034 
2035   // Not enums.
2036   verifyFormat("enum X f() {\n"
2037                "  a();\n"
2038                "  return 42;\n"
2039                "}");
2040   verifyFormat("enum X Type::f() {\n"
2041                "  a();\n"
2042                "  return 42;\n"
2043                "}");
2044   verifyFormat("enum ::X f() {\n"
2045                "  a();\n"
2046                "  return 42;\n"
2047                "}");
2048   verifyFormat("enum ns::X f() {\n"
2049                "  a();\n"
2050                "  return 42;\n"
2051                "}");
2052 }
2053 
2054 TEST_F(FormatTest, FormatsEnumsWithErrors) {
2055   verifyFormat("enum Type {\n"
2056                "  One = 0; // These semicolons should be commas.\n"
2057                "  Two = 1;\n"
2058                "};");
2059   verifyFormat("namespace n {\n"
2060                "enum Type {\n"
2061                "  One,\n"
2062                "  Two, // missing };\n"
2063                "  int i;\n"
2064                "}\n"
2065                "void g() {}");
2066 }
2067 
2068 TEST_F(FormatTest, FormatsEnumStruct) {
2069   verifyFormat("enum struct {\n"
2070                "  Zero,\n"
2071                "  One = 1,\n"
2072                "  Two = One + 1,\n"
2073                "  Three = (One + Two),\n"
2074                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2075                "  Five = (One, Two, Three, Four, 5)\n"
2076                "};");
2077   verifyFormat("enum struct Enum {};");
2078   verifyFormat("enum struct {};");
2079   verifyFormat("enum struct X E {} d;");
2080   verifyFormat("enum struct __attribute__((...)) E {} d;");
2081   verifyFormat("enum struct __declspec__((...)) E {} d;");
2082   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
2083 }
2084 
2085 TEST_F(FormatTest, FormatsEnumClass) {
2086   verifyFormat("enum class {\n"
2087                "  Zero,\n"
2088                "  One = 1,\n"
2089                "  Two = One + 1,\n"
2090                "  Three = (One + Two),\n"
2091                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2092                "  Five = (One, Two, Three, Four, 5)\n"
2093                "};");
2094   verifyFormat("enum class Enum {};");
2095   verifyFormat("enum class {};");
2096   verifyFormat("enum class X E {} d;");
2097   verifyFormat("enum class __attribute__((...)) E {} d;");
2098   verifyFormat("enum class __declspec__((...)) E {} d;");
2099   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
2100 }
2101 
2102 TEST_F(FormatTest, FormatsEnumTypes) {
2103   verifyFormat("enum X : int {\n"
2104                "  A, // Force multiple lines.\n"
2105                "  B\n"
2106                "};");
2107   verifyFormat("enum X : int { A, B };");
2108   verifyFormat("enum X : std::uint32_t { A, B };");
2109 }
2110 
2111 TEST_F(FormatTest, FormatsTypedefEnum) {
2112   FormatStyle Style = getLLVMStyle();
2113   Style.ColumnLimit = 40;
2114   verifyFormat("typedef enum {} EmptyEnum;");
2115   verifyFormat("typedef enum { A, B, C } ShortEnum;");
2116   verifyFormat("typedef enum {\n"
2117                "  ZERO = 0,\n"
2118                "  ONE = 1,\n"
2119                "  TWO = 2,\n"
2120                "  THREE = 3\n"
2121                "} LongEnum;",
2122                Style);
2123   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2124   Style.BraceWrapping.AfterEnum = true;
2125   verifyFormat("typedef enum {} EmptyEnum;");
2126   verifyFormat("typedef enum { A, B, C } ShortEnum;");
2127   verifyFormat("typedef enum\n"
2128                "{\n"
2129                "  ZERO = 0,\n"
2130                "  ONE = 1,\n"
2131                "  TWO = 2,\n"
2132                "  THREE = 3\n"
2133                "} LongEnum;",
2134                Style);
2135 }
2136 
2137 TEST_F(FormatTest, FormatsNSEnums) {
2138   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
2139   verifyGoogleFormat(
2140       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
2141   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
2142                      "  // Information about someDecentlyLongValue.\n"
2143                      "  someDecentlyLongValue,\n"
2144                      "  // Information about anotherDecentlyLongValue.\n"
2145                      "  anotherDecentlyLongValue,\n"
2146                      "  // Information about aThirdDecentlyLongValue.\n"
2147                      "  aThirdDecentlyLongValue\n"
2148                      "};");
2149   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
2150                      "  // Information about someDecentlyLongValue.\n"
2151                      "  someDecentlyLongValue,\n"
2152                      "  // Information about anotherDecentlyLongValue.\n"
2153                      "  anotherDecentlyLongValue,\n"
2154                      "  // Information about aThirdDecentlyLongValue.\n"
2155                      "  aThirdDecentlyLongValue\n"
2156                      "};");
2157   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
2158                      "  a = 1,\n"
2159                      "  b = 2,\n"
2160                      "  c = 3,\n"
2161                      "};");
2162   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
2163                      "  a = 1,\n"
2164                      "  b = 2,\n"
2165                      "  c = 3,\n"
2166                      "};");
2167   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
2168                      "  a = 1,\n"
2169                      "  b = 2,\n"
2170                      "  c = 3,\n"
2171                      "};");
2172   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
2173                      "  a = 1,\n"
2174                      "  b = 2,\n"
2175                      "  c = 3,\n"
2176                      "};");
2177 }
2178 
2179 TEST_F(FormatTest, FormatsBitfields) {
2180   verifyFormat("struct Bitfields {\n"
2181                "  unsigned sClass : 8;\n"
2182                "  unsigned ValueKind : 2;\n"
2183                "};");
2184   verifyFormat("struct A {\n"
2185                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
2186                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
2187                "};");
2188   verifyFormat("struct MyStruct {\n"
2189                "  uchar data;\n"
2190                "  uchar : 8;\n"
2191                "  uchar : 8;\n"
2192                "  uchar other;\n"
2193                "};");
2194   FormatStyle Style = getLLVMStyle();
2195   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
2196   verifyFormat("struct Bitfields {\n"
2197                "  unsigned sClass:8;\n"
2198                "  unsigned ValueKind:2;\n"
2199                "  uchar other;\n"
2200                "};",
2201                Style);
2202   verifyFormat("struct A {\n"
2203                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
2204                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
2205                "};",
2206                Style);
2207   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
2208   verifyFormat("struct Bitfields {\n"
2209                "  unsigned sClass :8;\n"
2210                "  unsigned ValueKind :2;\n"
2211                "  uchar other;\n"
2212                "};",
2213                Style);
2214   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
2215   verifyFormat("struct Bitfields {\n"
2216                "  unsigned sClass: 8;\n"
2217                "  unsigned ValueKind: 2;\n"
2218                "  uchar other;\n"
2219                "};",
2220                Style);
2221 }
2222 
2223 TEST_F(FormatTest, FormatsNamespaces) {
2224   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
2225   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
2226 
2227   verifyFormat("namespace some_namespace {\n"
2228                "class A {};\n"
2229                "void f() { f(); }\n"
2230                "}",
2231                LLVMWithNoNamespaceFix);
2232   verifyFormat("namespace N::inline D {\n"
2233                "class A {};\n"
2234                "void f() { f(); }\n"
2235                "}",
2236                LLVMWithNoNamespaceFix);
2237   verifyFormat("namespace N::inline D::E {\n"
2238                "class A {};\n"
2239                "void f() { f(); }\n"
2240                "}",
2241                LLVMWithNoNamespaceFix);
2242   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
2243                "class A {};\n"
2244                "void f() { f(); }\n"
2245                "}",
2246                LLVMWithNoNamespaceFix);
2247   verifyFormat("/* something */ namespace some_namespace {\n"
2248                "class A {};\n"
2249                "void f() { f(); }\n"
2250                "}",
2251                LLVMWithNoNamespaceFix);
2252   verifyFormat("namespace {\n"
2253                "class A {};\n"
2254                "void f() { f(); }\n"
2255                "}",
2256                LLVMWithNoNamespaceFix);
2257   verifyFormat("/* something */ namespace {\n"
2258                "class A {};\n"
2259                "void f() { f(); }\n"
2260                "}",
2261                LLVMWithNoNamespaceFix);
2262   verifyFormat("inline namespace X {\n"
2263                "class A {};\n"
2264                "void f() { f(); }\n"
2265                "}",
2266                LLVMWithNoNamespaceFix);
2267   verifyFormat("/* something */ inline namespace X {\n"
2268                "class A {};\n"
2269                "void f() { f(); }\n"
2270                "}",
2271                LLVMWithNoNamespaceFix);
2272   verifyFormat("export namespace X {\n"
2273                "class A {};\n"
2274                "void f() { f(); }\n"
2275                "}",
2276                LLVMWithNoNamespaceFix);
2277   verifyFormat("using namespace some_namespace;\n"
2278                "class A {};\n"
2279                "void f() { f(); }",
2280                LLVMWithNoNamespaceFix);
2281 
2282   // This code is more common than we thought; if we
2283   // layout this correctly the semicolon will go into
2284   // its own line, which is undesirable.
2285   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
2286   verifyFormat("namespace {\n"
2287                "class A {};\n"
2288                "};",
2289                LLVMWithNoNamespaceFix);
2290 
2291   verifyFormat("namespace {\n"
2292                "int SomeVariable = 0; // comment\n"
2293                "} // namespace",
2294                LLVMWithNoNamespaceFix);
2295   EXPECT_EQ("#ifndef HEADER_GUARD\n"
2296             "#define HEADER_GUARD\n"
2297             "namespace my_namespace {\n"
2298             "int i;\n"
2299             "} // my_namespace\n"
2300             "#endif // HEADER_GUARD",
2301             format("#ifndef HEADER_GUARD\n"
2302                    " #define HEADER_GUARD\n"
2303                    "   namespace my_namespace {\n"
2304                    "int i;\n"
2305                    "}    // my_namespace\n"
2306                    "#endif    // HEADER_GUARD",
2307                    LLVMWithNoNamespaceFix));
2308 
2309   EXPECT_EQ("namespace A::B {\n"
2310             "class C {};\n"
2311             "}",
2312             format("namespace A::B {\n"
2313                    "class C {};\n"
2314                    "}",
2315                    LLVMWithNoNamespaceFix));
2316 
2317   FormatStyle Style = getLLVMStyle();
2318   Style.NamespaceIndentation = FormatStyle::NI_All;
2319   EXPECT_EQ("namespace out {\n"
2320             "  int i;\n"
2321             "  namespace in {\n"
2322             "    int i;\n"
2323             "  } // namespace in\n"
2324             "} // namespace out",
2325             format("namespace out {\n"
2326                    "int i;\n"
2327                    "namespace in {\n"
2328                    "int i;\n"
2329                    "} // namespace in\n"
2330                    "} // namespace out",
2331                    Style));
2332 
2333   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2334   EXPECT_EQ("namespace out {\n"
2335             "int i;\n"
2336             "namespace in {\n"
2337             "  int i;\n"
2338             "} // namespace in\n"
2339             "} // namespace out",
2340             format("namespace out {\n"
2341                    "int i;\n"
2342                    "namespace in {\n"
2343                    "int i;\n"
2344                    "} // namespace in\n"
2345                    "} // namespace out",
2346                    Style));
2347 }
2348 
2349 TEST_F(FormatTest, NamespaceMacros) {
2350   FormatStyle Style = getLLVMStyle();
2351   Style.NamespaceMacros.push_back("TESTSUITE");
2352 
2353   verifyFormat("TESTSUITE(A) {\n"
2354                "int foo();\n"
2355                "} // TESTSUITE(A)",
2356                Style);
2357 
2358   verifyFormat("TESTSUITE(A, B) {\n"
2359                "int foo();\n"
2360                "} // TESTSUITE(A)",
2361                Style);
2362 
2363   // Properly indent according to NamespaceIndentation style
2364   Style.NamespaceIndentation = FormatStyle::NI_All;
2365   verifyFormat("TESTSUITE(A) {\n"
2366                "  int foo();\n"
2367                "} // TESTSUITE(A)",
2368                Style);
2369   verifyFormat("TESTSUITE(A) {\n"
2370                "  namespace B {\n"
2371                "    int foo();\n"
2372                "  } // namespace B\n"
2373                "} // TESTSUITE(A)",
2374                Style);
2375   verifyFormat("namespace A {\n"
2376                "  TESTSUITE(B) {\n"
2377                "    int foo();\n"
2378                "  } // TESTSUITE(B)\n"
2379                "} // namespace A",
2380                Style);
2381 
2382   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2383   verifyFormat("TESTSUITE(A) {\n"
2384                "TESTSUITE(B) {\n"
2385                "  int foo();\n"
2386                "} // TESTSUITE(B)\n"
2387                "} // TESTSUITE(A)",
2388                Style);
2389   verifyFormat("TESTSUITE(A) {\n"
2390                "namespace B {\n"
2391                "  int foo();\n"
2392                "} // namespace B\n"
2393                "} // TESTSUITE(A)",
2394                Style);
2395   verifyFormat("namespace A {\n"
2396                "TESTSUITE(B) {\n"
2397                "  int foo();\n"
2398                "} // TESTSUITE(B)\n"
2399                "} // namespace A",
2400                Style);
2401 
2402   // Properly merge namespace-macros blocks in CompactNamespaces mode
2403   Style.NamespaceIndentation = FormatStyle::NI_None;
2404   Style.CompactNamespaces = true;
2405   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
2406                "}} // TESTSUITE(A::B)",
2407                Style);
2408 
2409   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2410             "}} // TESTSUITE(out::in)",
2411             format("TESTSUITE(out) {\n"
2412                    "TESTSUITE(in) {\n"
2413                    "} // TESTSUITE(in)\n"
2414                    "} // TESTSUITE(out)",
2415                    Style));
2416 
2417   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2418             "}} // TESTSUITE(out::in)",
2419             format("TESTSUITE(out) {\n"
2420                    "TESTSUITE(in) {\n"
2421                    "} // TESTSUITE(in)\n"
2422                    "} // TESTSUITE(out)",
2423                    Style));
2424 
2425   // Do not merge different namespaces/macros
2426   EXPECT_EQ("namespace out {\n"
2427             "TESTSUITE(in) {\n"
2428             "} // TESTSUITE(in)\n"
2429             "} // namespace out",
2430             format("namespace out {\n"
2431                    "TESTSUITE(in) {\n"
2432                    "} // TESTSUITE(in)\n"
2433                    "} // namespace out",
2434                    Style));
2435   EXPECT_EQ("TESTSUITE(out) {\n"
2436             "namespace in {\n"
2437             "} // namespace in\n"
2438             "} // TESTSUITE(out)",
2439             format("TESTSUITE(out) {\n"
2440                    "namespace in {\n"
2441                    "} // namespace in\n"
2442                    "} // TESTSUITE(out)",
2443                    Style));
2444   Style.NamespaceMacros.push_back("FOOBAR");
2445   EXPECT_EQ("TESTSUITE(out) {\n"
2446             "FOOBAR(in) {\n"
2447             "} // FOOBAR(in)\n"
2448             "} // TESTSUITE(out)",
2449             format("TESTSUITE(out) {\n"
2450                    "FOOBAR(in) {\n"
2451                    "} // FOOBAR(in)\n"
2452                    "} // TESTSUITE(out)",
2453                    Style));
2454 }
2455 
2456 TEST_F(FormatTest, FormatsCompactNamespaces) {
2457   FormatStyle Style = getLLVMStyle();
2458   Style.CompactNamespaces = true;
2459   Style.NamespaceMacros.push_back("TESTSUITE");
2460 
2461   verifyFormat("namespace A { namespace B {\n"
2462                "}} // namespace A::B",
2463                Style);
2464 
2465   EXPECT_EQ("namespace out { namespace in {\n"
2466             "}} // namespace out::in",
2467             format("namespace out {\n"
2468                    "namespace in {\n"
2469                    "} // namespace in\n"
2470                    "} // namespace out",
2471                    Style));
2472 
2473   // Only namespaces which have both consecutive opening and end get compacted
2474   EXPECT_EQ("namespace out {\n"
2475             "namespace in1 {\n"
2476             "} // namespace in1\n"
2477             "namespace in2 {\n"
2478             "} // namespace in2\n"
2479             "} // namespace out",
2480             format("namespace out {\n"
2481                    "namespace in1 {\n"
2482                    "} // namespace in1\n"
2483                    "namespace in2 {\n"
2484                    "} // namespace in2\n"
2485                    "} // namespace out",
2486                    Style));
2487 
2488   EXPECT_EQ("namespace out {\n"
2489             "int i;\n"
2490             "namespace in {\n"
2491             "int j;\n"
2492             "} // namespace in\n"
2493             "int k;\n"
2494             "} // namespace out",
2495             format("namespace out { int i;\n"
2496                    "namespace in { int j; } // namespace in\n"
2497                    "int k; } // namespace out",
2498                    Style));
2499 
2500   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
2501             "}}} // namespace A::B::C\n",
2502             format("namespace A { namespace B {\n"
2503                    "namespace C {\n"
2504                    "}} // namespace B::C\n"
2505                    "} // namespace A\n",
2506                    Style));
2507 
2508   Style.ColumnLimit = 40;
2509   EXPECT_EQ("namespace aaaaaaaaaa {\n"
2510             "namespace bbbbbbbbbb {\n"
2511             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
2512             format("namespace aaaaaaaaaa {\n"
2513                    "namespace bbbbbbbbbb {\n"
2514                    "} // namespace bbbbbbbbbb\n"
2515                    "} // namespace aaaaaaaaaa",
2516                    Style));
2517 
2518   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
2519             "namespace cccccc {\n"
2520             "}}} // namespace aaaaaa::bbbbbb::cccccc",
2521             format("namespace aaaaaa {\n"
2522                    "namespace bbbbbb {\n"
2523                    "namespace cccccc {\n"
2524                    "} // namespace cccccc\n"
2525                    "} // namespace bbbbbb\n"
2526                    "} // namespace aaaaaa",
2527                    Style));
2528   Style.ColumnLimit = 80;
2529 
2530   // Extra semicolon after 'inner' closing brace prevents merging
2531   EXPECT_EQ("namespace out { namespace in {\n"
2532             "}; } // namespace out::in",
2533             format("namespace out {\n"
2534                    "namespace in {\n"
2535                    "}; // namespace in\n"
2536                    "} // namespace out",
2537                    Style));
2538 
2539   // Extra semicolon after 'outer' closing brace is conserved
2540   EXPECT_EQ("namespace out { namespace in {\n"
2541             "}}; // namespace out::in",
2542             format("namespace out {\n"
2543                    "namespace in {\n"
2544                    "} // namespace in\n"
2545                    "}; // namespace out",
2546                    Style));
2547 
2548   Style.NamespaceIndentation = FormatStyle::NI_All;
2549   EXPECT_EQ("namespace out { namespace in {\n"
2550             "  int i;\n"
2551             "}} // namespace out::in",
2552             format("namespace out {\n"
2553                    "namespace in {\n"
2554                    "int i;\n"
2555                    "} // namespace in\n"
2556                    "} // namespace out",
2557                    Style));
2558   EXPECT_EQ("namespace out { namespace mid {\n"
2559             "  namespace in {\n"
2560             "    int j;\n"
2561             "  } // namespace in\n"
2562             "  int k;\n"
2563             "}} // namespace out::mid",
2564             format("namespace out { namespace mid {\n"
2565                    "namespace in { int j; } // namespace in\n"
2566                    "int k; }} // namespace out::mid",
2567                    Style));
2568 
2569   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2570   EXPECT_EQ("namespace out { namespace in {\n"
2571             "  int i;\n"
2572             "}} // namespace out::in",
2573             format("namespace out {\n"
2574                    "namespace in {\n"
2575                    "int i;\n"
2576                    "} // namespace in\n"
2577                    "} // namespace out",
2578                    Style));
2579   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
2580             "  int i;\n"
2581             "}}} // namespace out::mid::in",
2582             format("namespace out {\n"
2583                    "namespace mid {\n"
2584                    "namespace in {\n"
2585                    "int i;\n"
2586                    "} // namespace in\n"
2587                    "} // namespace mid\n"
2588                    "} // namespace out",
2589                    Style));
2590 }
2591 
2592 TEST_F(FormatTest, FormatsExternC) {
2593   verifyFormat("extern \"C\" {\nint a;");
2594   verifyFormat("extern \"C\" {}");
2595   verifyFormat("extern \"C\" {\n"
2596                "int foo();\n"
2597                "}");
2598   verifyFormat("extern \"C\" int foo() {}");
2599   verifyFormat("extern \"C\" int foo();");
2600   verifyFormat("extern \"C\" int foo() {\n"
2601                "  int i = 42;\n"
2602                "  return i;\n"
2603                "}");
2604 
2605   FormatStyle Style = getLLVMStyle();
2606   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2607   Style.BraceWrapping.AfterFunction = true;
2608   verifyFormat("extern \"C\" int foo() {}", Style);
2609   verifyFormat("extern \"C\" int foo();", Style);
2610   verifyFormat("extern \"C\" int foo()\n"
2611                "{\n"
2612                "  int i = 42;\n"
2613                "  return i;\n"
2614                "}",
2615                Style);
2616 
2617   Style.BraceWrapping.AfterExternBlock = true;
2618   Style.BraceWrapping.SplitEmptyRecord = false;
2619   verifyFormat("extern \"C\"\n"
2620                "{}",
2621                Style);
2622   verifyFormat("extern \"C\"\n"
2623                "{\n"
2624                "  int foo();\n"
2625                "}",
2626                Style);
2627 }
2628 
2629 TEST_F(FormatTest, IndentExternBlockStyle) {
2630   FormatStyle Style = getLLVMStyle();
2631   Style.IndentWidth = 2;
2632 
2633   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
2634   verifyFormat("extern \"C\" { /*9*/\n}", Style);
2635   verifyFormat("extern \"C\" {\n"
2636                "  int foo10();\n"
2637                "}",
2638                Style);
2639 
2640   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
2641   verifyFormat("extern \"C\" { /*11*/\n}", Style);
2642   verifyFormat("extern \"C\" {\n"
2643                "int foo12();\n"
2644                "}",
2645                Style);
2646 
2647   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
2648   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2649   Style.BraceWrapping.AfterExternBlock = true;
2650   verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
2651   verifyFormat("extern \"C\"\n{\n"
2652                "  int foo14();\n"
2653                "}",
2654                Style);
2655 
2656   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
2657   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2658   Style.BraceWrapping.AfterExternBlock = false;
2659   verifyFormat("extern \"C\" { /*15*/\n}", Style);
2660   verifyFormat("extern \"C\" {\n"
2661                "int foo16();\n"
2662                "}",
2663                Style);
2664 }
2665 
2666 TEST_F(FormatTest, FormatsInlineASM) {
2667   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
2668   verifyFormat("asm(\"nop\" ::: \"memory\");");
2669   verifyFormat(
2670       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
2671       "    \"cpuid\\n\\t\"\n"
2672       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
2673       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
2674       "    : \"a\"(value));");
2675   EXPECT_EQ(
2676       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
2677       "  __asm {\n"
2678       "        mov     edx,[that] // vtable in edx\n"
2679       "        mov     eax,methodIndex\n"
2680       "        call    [edx][eax*4] // stdcall\n"
2681       "  }\n"
2682       "}",
2683       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
2684              "    __asm {\n"
2685              "        mov     edx,[that] // vtable in edx\n"
2686              "        mov     eax,methodIndex\n"
2687              "        call    [edx][eax*4] // stdcall\n"
2688              "    }\n"
2689              "}"));
2690   EXPECT_EQ("_asm {\n"
2691             "  xor eax, eax;\n"
2692             "  cpuid;\n"
2693             "}",
2694             format("_asm {\n"
2695                    "  xor eax, eax;\n"
2696                    "  cpuid;\n"
2697                    "}"));
2698   verifyFormat("void function() {\n"
2699                "  // comment\n"
2700                "  asm(\"\");\n"
2701                "}");
2702   EXPECT_EQ("__asm {\n"
2703             "}\n"
2704             "int i;",
2705             format("__asm   {\n"
2706                    "}\n"
2707                    "int   i;"));
2708 }
2709 
2710 TEST_F(FormatTest, FormatTryCatch) {
2711   verifyFormat("try {\n"
2712                "  throw a * b;\n"
2713                "} catch (int a) {\n"
2714                "  // Do nothing.\n"
2715                "} catch (...) {\n"
2716                "  exit(42);\n"
2717                "}");
2718 
2719   // Function-level try statements.
2720   verifyFormat("int f() try { return 4; } catch (...) {\n"
2721                "  return 5;\n"
2722                "}");
2723   verifyFormat("class A {\n"
2724                "  int a;\n"
2725                "  A() try : a(0) {\n"
2726                "  } catch (...) {\n"
2727                "    throw;\n"
2728                "  }\n"
2729                "};\n");
2730   verifyFormat("class A {\n"
2731                "  int a;\n"
2732                "  A() try : a(0), b{1} {\n"
2733                "  } catch (...) {\n"
2734                "    throw;\n"
2735                "  }\n"
2736                "};\n");
2737   verifyFormat("class A {\n"
2738                "  int a;\n"
2739                "  A() try : a(0), b{1}, c{2} {\n"
2740                "  } catch (...) {\n"
2741                "    throw;\n"
2742                "  }\n"
2743                "};\n");
2744   verifyFormat("class A {\n"
2745                "  int a;\n"
2746                "  A() try : a(0), b{1}, c{2} {\n"
2747                "    { // New scope.\n"
2748                "    }\n"
2749                "  } catch (...) {\n"
2750                "    throw;\n"
2751                "  }\n"
2752                "};\n");
2753 
2754   // Incomplete try-catch blocks.
2755   verifyIncompleteFormat("try {} catch (");
2756 }
2757 
2758 TEST_F(FormatTest, FormatTryAsAVariable) {
2759   verifyFormat("int try;");
2760   verifyFormat("int try, size;");
2761   verifyFormat("try = foo();");
2762   verifyFormat("if (try < size) {\n  return true;\n}");
2763 
2764   verifyFormat("int catch;");
2765   verifyFormat("int catch, size;");
2766   verifyFormat("catch = foo();");
2767   verifyFormat("if (catch < size) {\n  return true;\n}");
2768 
2769   FormatStyle Style = getLLVMStyle();
2770   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2771   Style.BraceWrapping.AfterFunction = true;
2772   Style.BraceWrapping.BeforeCatch = true;
2773   verifyFormat("try {\n"
2774                "  int bar = 1;\n"
2775                "}\n"
2776                "catch (...) {\n"
2777                "  int bar = 1;\n"
2778                "}",
2779                Style);
2780   verifyFormat("#if NO_EX\n"
2781                "try\n"
2782                "#endif\n"
2783                "{\n"
2784                "}\n"
2785                "#if NO_EX\n"
2786                "catch (...) {\n"
2787                "}",
2788                Style);
2789   verifyFormat("try /* abc */ {\n"
2790                "  int bar = 1;\n"
2791                "}\n"
2792                "catch (...) {\n"
2793                "  int bar = 1;\n"
2794                "}",
2795                Style);
2796   verifyFormat("try\n"
2797                "// abc\n"
2798                "{\n"
2799                "  int bar = 1;\n"
2800                "}\n"
2801                "catch (...) {\n"
2802                "  int bar = 1;\n"
2803                "}",
2804                Style);
2805 }
2806 
2807 TEST_F(FormatTest, FormatSEHTryCatch) {
2808   verifyFormat("__try {\n"
2809                "  int a = b * c;\n"
2810                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
2811                "  // Do nothing.\n"
2812                "}");
2813 
2814   verifyFormat("__try {\n"
2815                "  int a = b * c;\n"
2816                "} __finally {\n"
2817                "  // Do nothing.\n"
2818                "}");
2819 
2820   verifyFormat("DEBUG({\n"
2821                "  __try {\n"
2822                "  } __finally {\n"
2823                "  }\n"
2824                "});\n");
2825 }
2826 
2827 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
2828   verifyFormat("try {\n"
2829                "  f();\n"
2830                "} catch {\n"
2831                "  g();\n"
2832                "}");
2833   verifyFormat("try {\n"
2834                "  f();\n"
2835                "} catch (A a) MACRO(x) {\n"
2836                "  g();\n"
2837                "} catch (B b) MACRO(x) {\n"
2838                "  g();\n"
2839                "}");
2840 }
2841 
2842 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
2843   FormatStyle Style = getLLVMStyle();
2844   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
2845                           FormatStyle::BS_WebKit}) {
2846     Style.BreakBeforeBraces = BraceStyle;
2847     verifyFormat("try {\n"
2848                  "  // something\n"
2849                  "} catch (...) {\n"
2850                  "  // something\n"
2851                  "}",
2852                  Style);
2853   }
2854   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
2855   verifyFormat("try {\n"
2856                "  // something\n"
2857                "}\n"
2858                "catch (...) {\n"
2859                "  // something\n"
2860                "}",
2861                Style);
2862   verifyFormat("__try {\n"
2863                "  // something\n"
2864                "}\n"
2865                "__finally {\n"
2866                "  // something\n"
2867                "}",
2868                Style);
2869   verifyFormat("@try {\n"
2870                "  // something\n"
2871                "}\n"
2872                "@finally {\n"
2873                "  // something\n"
2874                "}",
2875                Style);
2876   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
2877   verifyFormat("try\n"
2878                "{\n"
2879                "  // something\n"
2880                "}\n"
2881                "catch (...)\n"
2882                "{\n"
2883                "  // something\n"
2884                "}",
2885                Style);
2886   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
2887   verifyFormat("try\n"
2888                "  {\n"
2889                "  // something white\n"
2890                "  }\n"
2891                "catch (...)\n"
2892                "  {\n"
2893                "  // something white\n"
2894                "  }",
2895                Style);
2896   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2897   verifyFormat("try\n"
2898                "  {\n"
2899                "    // something\n"
2900                "  }\n"
2901                "catch (...)\n"
2902                "  {\n"
2903                "    // something\n"
2904                "  }",
2905                Style);
2906   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2907   Style.BraceWrapping.BeforeCatch = true;
2908   verifyFormat("try {\n"
2909                "  // something\n"
2910                "}\n"
2911                "catch (...) {\n"
2912                "  // something\n"
2913                "}",
2914                Style);
2915 }
2916 
2917 TEST_F(FormatTest, StaticInitializers) {
2918   verifyFormat("static SomeClass SC = {1, 'a'};");
2919 
2920   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
2921                "    100000000, "
2922                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
2923 
2924   // Here, everything other than the "}" would fit on a line.
2925   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
2926                "    10000000000000000000000000};");
2927   EXPECT_EQ("S s = {a,\n"
2928             "\n"
2929             "       b};",
2930             format("S s = {\n"
2931                    "  a,\n"
2932                    "\n"
2933                    "  b\n"
2934                    "};"));
2935 
2936   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
2937   // line. However, the formatting looks a bit off and this probably doesn't
2938   // happen often in practice.
2939   verifyFormat("static int Variable[1] = {\n"
2940                "    {1000000000000000000000000000000000000}};",
2941                getLLVMStyleWithColumns(40));
2942 }
2943 
2944 TEST_F(FormatTest, DesignatedInitializers) {
2945   verifyFormat("const struct A a = {.a = 1, .b = 2};");
2946   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
2947                "                    .bbbbbbbbbb = 2,\n"
2948                "                    .cccccccccc = 3,\n"
2949                "                    .dddddddddd = 4,\n"
2950                "                    .eeeeeeeeee = 5};");
2951   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2952                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
2953                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
2954                "    .ccccccccccccccccccccccccccc = 3,\n"
2955                "    .ddddddddddddddddddddddddddd = 4,\n"
2956                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
2957 
2958   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
2959 
2960   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
2961   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
2962                "                    [2] = bbbbbbbbbb,\n"
2963                "                    [3] = cccccccccc,\n"
2964                "                    [4] = dddddddddd,\n"
2965                "                    [5] = eeeeeeeeee};");
2966   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2967                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2968                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
2969                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
2970                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
2971                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
2972 }
2973 
2974 TEST_F(FormatTest, NestedStaticInitializers) {
2975   verifyFormat("static A x = {{{}}};\n");
2976   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
2977                "               {init1, init2, init3, init4}}};",
2978                getLLVMStyleWithColumns(50));
2979 
2980   verifyFormat("somes Status::global_reps[3] = {\n"
2981                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2982                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2983                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
2984                getLLVMStyleWithColumns(60));
2985   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
2986                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2987                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2988                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
2989   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
2990                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
2991                "rect.fTop}};");
2992 
2993   verifyFormat(
2994       "SomeArrayOfSomeType a = {\n"
2995       "    {{1, 2, 3},\n"
2996       "     {1, 2, 3},\n"
2997       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
2998       "      333333333333333333333333333333},\n"
2999       "     {1, 2, 3},\n"
3000       "     {1, 2, 3}}};");
3001   verifyFormat(
3002       "SomeArrayOfSomeType a = {\n"
3003       "    {{1, 2, 3}},\n"
3004       "    {{1, 2, 3}},\n"
3005       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
3006       "      333333333333333333333333333333}},\n"
3007       "    {{1, 2, 3}},\n"
3008       "    {{1, 2, 3}}};");
3009 
3010   verifyFormat("struct {\n"
3011                "  unsigned bit;\n"
3012                "  const char *const name;\n"
3013                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
3014                "                 {kOsWin, \"Windows\"},\n"
3015                "                 {kOsLinux, \"Linux\"},\n"
3016                "                 {kOsCrOS, \"Chrome OS\"}};");
3017   verifyFormat("struct {\n"
3018                "  unsigned bit;\n"
3019                "  const char *const name;\n"
3020                "} kBitsToOs[] = {\n"
3021                "    {kOsMac, \"Mac\"},\n"
3022                "    {kOsWin, \"Windows\"},\n"
3023                "    {kOsLinux, \"Linux\"},\n"
3024                "    {kOsCrOS, \"Chrome OS\"},\n"
3025                "};");
3026 }
3027 
3028 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
3029   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3030                "                      \\\n"
3031                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
3032 }
3033 
3034 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
3035   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
3036                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
3037 
3038   // Do break defaulted and deleted functions.
3039   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
3040                "    default;",
3041                getLLVMStyleWithColumns(40));
3042   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
3043                "    delete;",
3044                getLLVMStyleWithColumns(40));
3045 }
3046 
3047 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
3048   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
3049                getLLVMStyleWithColumns(40));
3050   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
3051                getLLVMStyleWithColumns(40));
3052   EXPECT_EQ("#define Q                              \\\n"
3053             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
3054             "  \"aaaaaaaa.cpp\"",
3055             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
3056                    getLLVMStyleWithColumns(40)));
3057 }
3058 
3059 TEST_F(FormatTest, UnderstandsLinePPDirective) {
3060   EXPECT_EQ("# 123 \"A string literal\"",
3061             format("   #     123    \"A string literal\""));
3062 }
3063 
3064 TEST_F(FormatTest, LayoutUnknownPPDirective) {
3065   EXPECT_EQ("#;", format("#;"));
3066   verifyFormat("#\n;\n;\n;");
3067 }
3068 
3069 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
3070   EXPECT_EQ("#line 42 \"test\"\n",
3071             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
3072   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
3073                                     getLLVMStyleWithColumns(12)));
3074 }
3075 
3076 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
3077   EXPECT_EQ("#line 42 \"test\"",
3078             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
3079   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
3080 }
3081 
3082 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
3083   verifyFormat("#define A \\x20");
3084   verifyFormat("#define A \\ x20");
3085   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
3086   verifyFormat("#define A ''");
3087   verifyFormat("#define A ''qqq");
3088   verifyFormat("#define A `qqq");
3089   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
3090   EXPECT_EQ("const char *c = STRINGIFY(\n"
3091             "\\na : b);",
3092             format("const char * c = STRINGIFY(\n"
3093                    "\\na : b);"));
3094 
3095   verifyFormat("a\r\\");
3096   verifyFormat("a\v\\");
3097   verifyFormat("a\f\\");
3098 }
3099 
3100 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
3101   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
3102   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
3103   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
3104   // FIXME: We never break before the macro name.
3105   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
3106 
3107   verifyFormat("#define A A\n#define A A");
3108   verifyFormat("#define A(X) A\n#define A A");
3109 
3110   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
3111   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
3112 }
3113 
3114 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
3115   EXPECT_EQ("// somecomment\n"
3116             "#include \"a.h\"\n"
3117             "#define A(  \\\n"
3118             "    A, B)\n"
3119             "#include \"b.h\"\n"
3120             "// somecomment\n",
3121             format("  // somecomment\n"
3122                    "  #include \"a.h\"\n"
3123                    "#define A(A,\\\n"
3124                    "    B)\n"
3125                    "    #include \"b.h\"\n"
3126                    " // somecomment\n",
3127                    getLLVMStyleWithColumns(13)));
3128 }
3129 
3130 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
3131 
3132 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
3133   EXPECT_EQ("#define A    \\\n"
3134             "  c;         \\\n"
3135             "  e;\n"
3136             "f;",
3137             format("#define A c; e;\n"
3138                    "f;",
3139                    getLLVMStyleWithColumns(14)));
3140 }
3141 
3142 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
3143 
3144 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
3145   EXPECT_EQ("int x,\n"
3146             "#define A\n"
3147             "    y;",
3148             format("int x,\n#define A\ny;"));
3149 }
3150 
3151 TEST_F(FormatTest, HashInMacroDefinition) {
3152   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
3153   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
3154   verifyFormat("#define A  \\\n"
3155                "  {        \\\n"
3156                "    f(#c); \\\n"
3157                "  }",
3158                getLLVMStyleWithColumns(11));
3159 
3160   verifyFormat("#define A(X)         \\\n"
3161                "  void function##X()",
3162                getLLVMStyleWithColumns(22));
3163 
3164   verifyFormat("#define A(a, b, c)   \\\n"
3165                "  void a##b##c()",
3166                getLLVMStyleWithColumns(22));
3167 
3168   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
3169 }
3170 
3171 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
3172   EXPECT_EQ("#define A (x)", format("#define A (x)"));
3173   EXPECT_EQ("#define A(x)", format("#define A(x)"));
3174 
3175   FormatStyle Style = getLLVMStyle();
3176   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
3177   verifyFormat("#define true ((foo)1)", Style);
3178   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
3179   verifyFormat("#define false((foo)0)", Style);
3180 }
3181 
3182 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
3183   EXPECT_EQ("#define A b;", format("#define A \\\n"
3184                                    "          \\\n"
3185                                    "  b;",
3186                                    getLLVMStyleWithColumns(25)));
3187   EXPECT_EQ("#define A \\\n"
3188             "          \\\n"
3189             "  a;      \\\n"
3190             "  b;",
3191             format("#define A \\\n"
3192                    "          \\\n"
3193                    "  a;      \\\n"
3194                    "  b;",
3195                    getLLVMStyleWithColumns(11)));
3196   EXPECT_EQ("#define A \\\n"
3197             "  a;      \\\n"
3198             "          \\\n"
3199             "  b;",
3200             format("#define A \\\n"
3201                    "  a;      \\\n"
3202                    "          \\\n"
3203                    "  b;",
3204                    getLLVMStyleWithColumns(11)));
3205 }
3206 
3207 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
3208   verifyIncompleteFormat("#define A :");
3209   verifyFormat("#define SOMECASES  \\\n"
3210                "  case 1:          \\\n"
3211                "  case 2\n",
3212                getLLVMStyleWithColumns(20));
3213   verifyFormat("#define MACRO(a) \\\n"
3214                "  if (a)         \\\n"
3215                "    f();         \\\n"
3216                "  else           \\\n"
3217                "    g()",
3218                getLLVMStyleWithColumns(18));
3219   verifyFormat("#define A template <typename T>");
3220   verifyIncompleteFormat("#define STR(x) #x\n"
3221                          "f(STR(this_is_a_string_literal{));");
3222   verifyFormat("#pragma omp threadprivate( \\\n"
3223                "    y)), // expected-warning",
3224                getLLVMStyleWithColumns(28));
3225   verifyFormat("#d, = };");
3226   verifyFormat("#if \"a");
3227   verifyIncompleteFormat("({\n"
3228                          "#define b     \\\n"
3229                          "  }           \\\n"
3230                          "  a\n"
3231                          "a",
3232                          getLLVMStyleWithColumns(15));
3233   verifyFormat("#define A     \\\n"
3234                "  {           \\\n"
3235                "    {\n"
3236                "#define B     \\\n"
3237                "  }           \\\n"
3238                "  }",
3239                getLLVMStyleWithColumns(15));
3240   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
3241   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
3242   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
3243   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
3244 }
3245 
3246 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
3247   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
3248   EXPECT_EQ("class A : public QObject {\n"
3249             "  Q_OBJECT\n"
3250             "\n"
3251             "  A() {}\n"
3252             "};",
3253             format("class A  :  public QObject {\n"
3254                    "     Q_OBJECT\n"
3255                    "\n"
3256                    "  A() {\n}\n"
3257                    "}  ;"));
3258   EXPECT_EQ("MACRO\n"
3259             "/*static*/ int i;",
3260             format("MACRO\n"
3261                    " /*static*/ int   i;"));
3262   EXPECT_EQ("SOME_MACRO\n"
3263             "namespace {\n"
3264             "void f();\n"
3265             "} // namespace",
3266             format("SOME_MACRO\n"
3267                    "  namespace    {\n"
3268                    "void   f(  );\n"
3269                    "} // namespace"));
3270   // Only if the identifier contains at least 5 characters.
3271   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
3272   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
3273   // Only if everything is upper case.
3274   EXPECT_EQ("class A : public QObject {\n"
3275             "  Q_Object A() {}\n"
3276             "};",
3277             format("class A  :  public QObject {\n"
3278                    "     Q_Object\n"
3279                    "  A() {\n}\n"
3280                    "}  ;"));
3281 
3282   // Only if the next line can actually start an unwrapped line.
3283   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
3284             format("SOME_WEIRD_LOG_MACRO\n"
3285                    "<< SomeThing;"));
3286 
3287   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
3288                "(n, buffers))\n",
3289                getChromiumStyle(FormatStyle::LK_Cpp));
3290 
3291   // See PR41483
3292   EXPECT_EQ("/**/ FOO(a)\n"
3293             "FOO(b)",
3294             format("/**/ FOO(a)\n"
3295                    "FOO(b)"));
3296 }
3297 
3298 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
3299   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
3300             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
3301             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
3302             "class X {};\n"
3303             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
3304             "int *createScopDetectionPass() { return 0; }",
3305             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
3306                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
3307                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
3308                    "  class X {};\n"
3309                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
3310                    "  int *createScopDetectionPass() { return 0; }"));
3311   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
3312   // braces, so that inner block is indented one level more.
3313   EXPECT_EQ("int q() {\n"
3314             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3315             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3316             "  IPC_END_MESSAGE_MAP()\n"
3317             "}",
3318             format("int q() {\n"
3319                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3320                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3321                    "  IPC_END_MESSAGE_MAP()\n"
3322                    "}"));
3323 
3324   // Same inside macros.
3325   EXPECT_EQ("#define LIST(L) \\\n"
3326             "  L(A)          \\\n"
3327             "  L(B)          \\\n"
3328             "  L(C)",
3329             format("#define LIST(L) \\\n"
3330                    "  L(A) \\\n"
3331                    "  L(B) \\\n"
3332                    "  L(C)",
3333                    getGoogleStyle()));
3334 
3335   // These must not be recognized as macros.
3336   EXPECT_EQ("int q() {\n"
3337             "  f(x);\n"
3338             "  f(x) {}\n"
3339             "  f(x)->g();\n"
3340             "  f(x)->*g();\n"
3341             "  f(x).g();\n"
3342             "  f(x) = x;\n"
3343             "  f(x) += x;\n"
3344             "  f(x) -= x;\n"
3345             "  f(x) *= x;\n"
3346             "  f(x) /= x;\n"
3347             "  f(x) %= x;\n"
3348             "  f(x) &= x;\n"
3349             "  f(x) |= x;\n"
3350             "  f(x) ^= x;\n"
3351             "  f(x) >>= x;\n"
3352             "  f(x) <<= x;\n"
3353             "  f(x)[y].z();\n"
3354             "  LOG(INFO) << x;\n"
3355             "  ifstream(x) >> x;\n"
3356             "}\n",
3357             format("int q() {\n"
3358                    "  f(x)\n;\n"
3359                    "  f(x)\n {}\n"
3360                    "  f(x)\n->g();\n"
3361                    "  f(x)\n->*g();\n"
3362                    "  f(x)\n.g();\n"
3363                    "  f(x)\n = x;\n"
3364                    "  f(x)\n += x;\n"
3365                    "  f(x)\n -= x;\n"
3366                    "  f(x)\n *= x;\n"
3367                    "  f(x)\n /= x;\n"
3368                    "  f(x)\n %= x;\n"
3369                    "  f(x)\n &= x;\n"
3370                    "  f(x)\n |= x;\n"
3371                    "  f(x)\n ^= x;\n"
3372                    "  f(x)\n >>= x;\n"
3373                    "  f(x)\n <<= x;\n"
3374                    "  f(x)\n[y].z();\n"
3375                    "  LOG(INFO)\n << x;\n"
3376                    "  ifstream(x)\n >> x;\n"
3377                    "}\n"));
3378   EXPECT_EQ("int q() {\n"
3379             "  F(x)\n"
3380             "  if (1) {\n"
3381             "  }\n"
3382             "  F(x)\n"
3383             "  while (1) {\n"
3384             "  }\n"
3385             "  F(x)\n"
3386             "  G(x);\n"
3387             "  F(x)\n"
3388             "  try {\n"
3389             "    Q();\n"
3390             "  } catch (...) {\n"
3391             "  }\n"
3392             "}\n",
3393             format("int q() {\n"
3394                    "F(x)\n"
3395                    "if (1) {}\n"
3396                    "F(x)\n"
3397                    "while (1) {}\n"
3398                    "F(x)\n"
3399                    "G(x);\n"
3400                    "F(x)\n"
3401                    "try { Q(); } catch (...) {}\n"
3402                    "}\n"));
3403   EXPECT_EQ("class A {\n"
3404             "  A() : t(0) {}\n"
3405             "  A(int i) noexcept() : {}\n"
3406             "  A(X x)\n" // FIXME: function-level try blocks are broken.
3407             "  try : t(0) {\n"
3408             "  } catch (...) {\n"
3409             "  }\n"
3410             "};",
3411             format("class A {\n"
3412                    "  A()\n : t(0) {}\n"
3413                    "  A(int i)\n noexcept() : {}\n"
3414                    "  A(X x)\n"
3415                    "  try : t(0) {} catch (...) {}\n"
3416                    "};"));
3417   FormatStyle Style = getLLVMStyle();
3418   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3419   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
3420   Style.BraceWrapping.AfterFunction = true;
3421   EXPECT_EQ("void f()\n"
3422             "try\n"
3423             "{\n"
3424             "}",
3425             format("void f() try {\n"
3426                    "}",
3427                    Style));
3428   EXPECT_EQ("class SomeClass {\n"
3429             "public:\n"
3430             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3431             "};",
3432             format("class SomeClass {\n"
3433                    "public:\n"
3434                    "  SomeClass()\n"
3435                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3436                    "};"));
3437   EXPECT_EQ("class SomeClass {\n"
3438             "public:\n"
3439             "  SomeClass()\n"
3440             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3441             "};",
3442             format("class SomeClass {\n"
3443                    "public:\n"
3444                    "  SomeClass()\n"
3445                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3446                    "};",
3447                    getLLVMStyleWithColumns(40)));
3448 
3449   verifyFormat("MACRO(>)");
3450 
3451   // Some macros contain an implicit semicolon.
3452   Style = getLLVMStyle();
3453   Style.StatementMacros.push_back("FOO");
3454   verifyFormat("FOO(a) int b = 0;");
3455   verifyFormat("FOO(a)\n"
3456                "int b = 0;",
3457                Style);
3458   verifyFormat("FOO(a);\n"
3459                "int b = 0;",
3460                Style);
3461   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
3462                "int b = 0;",
3463                Style);
3464   verifyFormat("FOO()\n"
3465                "int b = 0;",
3466                Style);
3467   verifyFormat("FOO\n"
3468                "int b = 0;",
3469                Style);
3470   verifyFormat("void f() {\n"
3471                "  FOO(a)\n"
3472                "  return a;\n"
3473                "}",
3474                Style);
3475   verifyFormat("FOO(a)\n"
3476                "FOO(b)",
3477                Style);
3478   verifyFormat("int a = 0;\n"
3479                "FOO(b)\n"
3480                "int c = 0;",
3481                Style);
3482   verifyFormat("int a = 0;\n"
3483                "int x = FOO(a)\n"
3484                "int b = 0;",
3485                Style);
3486   verifyFormat("void foo(int a) { FOO(a) }\n"
3487                "uint32_t bar() {}",
3488                Style);
3489 }
3490 
3491 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
3492   verifyFormat("#define A \\\n"
3493                "  f({     \\\n"
3494                "    g();  \\\n"
3495                "  });",
3496                getLLVMStyleWithColumns(11));
3497 }
3498 
3499 TEST_F(FormatTest, IndentPreprocessorDirectives) {
3500   FormatStyle Style = getLLVMStyle();
3501   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
3502   Style.ColumnLimit = 40;
3503   verifyFormat("#ifdef _WIN32\n"
3504                "#define A 0\n"
3505                "#ifdef VAR2\n"
3506                "#define B 1\n"
3507                "#include <someheader.h>\n"
3508                "#define MACRO                          \\\n"
3509                "  some_very_long_func_aaaaaaaaaa();\n"
3510                "#endif\n"
3511                "#else\n"
3512                "#define A 1\n"
3513                "#endif",
3514                Style);
3515   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
3516   verifyFormat("#ifdef _WIN32\n"
3517                "#  define A 0\n"
3518                "#  ifdef VAR2\n"
3519                "#    define B 1\n"
3520                "#    include <someheader.h>\n"
3521                "#    define MACRO                      \\\n"
3522                "      some_very_long_func_aaaaaaaaaa();\n"
3523                "#  endif\n"
3524                "#else\n"
3525                "#  define A 1\n"
3526                "#endif",
3527                Style);
3528   verifyFormat("#if A\n"
3529                "#  define MACRO                        \\\n"
3530                "    void a(int x) {                    \\\n"
3531                "      b();                             \\\n"
3532                "      c();                             \\\n"
3533                "      d();                             \\\n"
3534                "      e();                             \\\n"
3535                "      f();                             \\\n"
3536                "    }\n"
3537                "#endif",
3538                Style);
3539   // Comments before include guard.
3540   verifyFormat("// file comment\n"
3541                "// file comment\n"
3542                "#ifndef HEADER_H\n"
3543                "#define HEADER_H\n"
3544                "code();\n"
3545                "#endif",
3546                Style);
3547   // Test with include guards.
3548   verifyFormat("#ifndef HEADER_H\n"
3549                "#define HEADER_H\n"
3550                "code();\n"
3551                "#endif",
3552                Style);
3553   // Include guards must have a #define with the same variable immediately
3554   // after #ifndef.
3555   verifyFormat("#ifndef NOT_GUARD\n"
3556                "#  define FOO\n"
3557                "code();\n"
3558                "#endif",
3559                Style);
3560 
3561   // Include guards must cover the entire file.
3562   verifyFormat("code();\n"
3563                "code();\n"
3564                "#ifndef NOT_GUARD\n"
3565                "#  define NOT_GUARD\n"
3566                "code();\n"
3567                "#endif",
3568                Style);
3569   verifyFormat("#ifndef NOT_GUARD\n"
3570                "#  define NOT_GUARD\n"
3571                "code();\n"
3572                "#endif\n"
3573                "code();",
3574                Style);
3575   // Test with trailing blank lines.
3576   verifyFormat("#ifndef HEADER_H\n"
3577                "#define HEADER_H\n"
3578                "code();\n"
3579                "#endif\n",
3580                Style);
3581   // Include guards don't have #else.
3582   verifyFormat("#ifndef NOT_GUARD\n"
3583                "#  define NOT_GUARD\n"
3584                "code();\n"
3585                "#else\n"
3586                "#endif",
3587                Style);
3588   verifyFormat("#ifndef NOT_GUARD\n"
3589                "#  define NOT_GUARD\n"
3590                "code();\n"
3591                "#elif FOO\n"
3592                "#endif",
3593                Style);
3594   // Non-identifier #define after potential include guard.
3595   verifyFormat("#ifndef FOO\n"
3596                "#  define 1\n"
3597                "#endif\n",
3598                Style);
3599   // #if closes past last non-preprocessor line.
3600   verifyFormat("#ifndef FOO\n"
3601                "#define FOO\n"
3602                "#if 1\n"
3603                "int i;\n"
3604                "#  define A 0\n"
3605                "#endif\n"
3606                "#endif\n",
3607                Style);
3608   // Don't crash if there is an #elif directive without a condition.
3609   verifyFormat("#if 1\n"
3610                "int x;\n"
3611                "#elif\n"
3612                "int y;\n"
3613                "#else\n"
3614                "int z;\n"
3615                "#endif",
3616                Style);
3617   // FIXME: This doesn't handle the case where there's code between the
3618   // #ifndef and #define but all other conditions hold. This is because when
3619   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
3620   // previous code line yet, so we can't detect it.
3621   EXPECT_EQ("#ifndef NOT_GUARD\n"
3622             "code();\n"
3623             "#define NOT_GUARD\n"
3624             "code();\n"
3625             "#endif",
3626             format("#ifndef NOT_GUARD\n"
3627                    "code();\n"
3628                    "#  define NOT_GUARD\n"
3629                    "code();\n"
3630                    "#endif",
3631                    Style));
3632   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
3633   // be outside an include guard. Examples are #pragma once and
3634   // #pragma GCC diagnostic, or anything else that does not change the meaning
3635   // of the file if it's included multiple times.
3636   EXPECT_EQ("#ifdef WIN32\n"
3637             "#  pragma once\n"
3638             "#endif\n"
3639             "#ifndef HEADER_H\n"
3640             "#  define HEADER_H\n"
3641             "code();\n"
3642             "#endif",
3643             format("#ifdef WIN32\n"
3644                    "#  pragma once\n"
3645                    "#endif\n"
3646                    "#ifndef HEADER_H\n"
3647                    "#define HEADER_H\n"
3648                    "code();\n"
3649                    "#endif",
3650                    Style));
3651   // FIXME: This does not detect when there is a single non-preprocessor line
3652   // in front of an include-guard-like structure where other conditions hold
3653   // because ScopedLineState hides the line.
3654   EXPECT_EQ("code();\n"
3655             "#ifndef HEADER_H\n"
3656             "#define HEADER_H\n"
3657             "code();\n"
3658             "#endif",
3659             format("code();\n"
3660                    "#ifndef HEADER_H\n"
3661                    "#  define HEADER_H\n"
3662                    "code();\n"
3663                    "#endif",
3664                    Style));
3665   // Keep comments aligned with #, otherwise indent comments normally. These
3666   // tests cannot use verifyFormat because messUp manipulates leading
3667   // whitespace.
3668   {
3669     const char *Expected = ""
3670                            "void f() {\n"
3671                            "#if 1\n"
3672                            "// Preprocessor aligned.\n"
3673                            "#  define A 0\n"
3674                            "  // Code. Separated by blank line.\n"
3675                            "\n"
3676                            "#  define B 0\n"
3677                            "  // Code. Not aligned with #\n"
3678                            "#  define C 0\n"
3679                            "#endif";
3680     const char *ToFormat = ""
3681                            "void f() {\n"
3682                            "#if 1\n"
3683                            "// Preprocessor aligned.\n"
3684                            "#  define A 0\n"
3685                            "// Code. Separated by blank line.\n"
3686                            "\n"
3687                            "#  define B 0\n"
3688                            "   // Code. Not aligned with #\n"
3689                            "#  define C 0\n"
3690                            "#endif";
3691     EXPECT_EQ(Expected, format(ToFormat, Style));
3692     EXPECT_EQ(Expected, format(Expected, Style));
3693   }
3694   // Keep block quotes aligned.
3695   {
3696     const char *Expected = ""
3697                            "void f() {\n"
3698                            "#if 1\n"
3699                            "/* Preprocessor aligned. */\n"
3700                            "#  define A 0\n"
3701                            "  /* Code. Separated by blank line. */\n"
3702                            "\n"
3703                            "#  define B 0\n"
3704                            "  /* Code. Not aligned with # */\n"
3705                            "#  define C 0\n"
3706                            "#endif";
3707     const char *ToFormat = ""
3708                            "void f() {\n"
3709                            "#if 1\n"
3710                            "/* Preprocessor aligned. */\n"
3711                            "#  define A 0\n"
3712                            "/* Code. Separated by blank line. */\n"
3713                            "\n"
3714                            "#  define B 0\n"
3715                            "   /* Code. Not aligned with # */\n"
3716                            "#  define C 0\n"
3717                            "#endif";
3718     EXPECT_EQ(Expected, format(ToFormat, Style));
3719     EXPECT_EQ(Expected, format(Expected, Style));
3720   }
3721   // Keep comments aligned with un-indented directives.
3722   {
3723     const char *Expected = ""
3724                            "void f() {\n"
3725                            "// Preprocessor aligned.\n"
3726                            "#define A 0\n"
3727                            "  // Code. Separated by blank line.\n"
3728                            "\n"
3729                            "#define B 0\n"
3730                            "  // Code. Not aligned with #\n"
3731                            "#define C 0\n";
3732     const char *ToFormat = ""
3733                            "void f() {\n"
3734                            "// Preprocessor aligned.\n"
3735                            "#define A 0\n"
3736                            "// Code. Separated by blank line.\n"
3737                            "\n"
3738                            "#define B 0\n"
3739                            "   // Code. Not aligned with #\n"
3740                            "#define C 0\n";
3741     EXPECT_EQ(Expected, format(ToFormat, Style));
3742     EXPECT_EQ(Expected, format(Expected, Style));
3743   }
3744   // Test AfterHash with tabs.
3745   {
3746     FormatStyle Tabbed = Style;
3747     Tabbed.UseTab = FormatStyle::UT_Always;
3748     Tabbed.IndentWidth = 8;
3749     Tabbed.TabWidth = 8;
3750     verifyFormat("#ifdef _WIN32\n"
3751                  "#\tdefine A 0\n"
3752                  "#\tifdef VAR2\n"
3753                  "#\t\tdefine B 1\n"
3754                  "#\t\tinclude <someheader.h>\n"
3755                  "#\t\tdefine MACRO          \\\n"
3756                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
3757                  "#\tendif\n"
3758                  "#else\n"
3759                  "#\tdefine A 1\n"
3760                  "#endif",
3761                  Tabbed);
3762   }
3763 
3764   // Regression test: Multiline-macro inside include guards.
3765   verifyFormat("#ifndef HEADER_H\n"
3766                "#define HEADER_H\n"
3767                "#define A()        \\\n"
3768                "  int i;           \\\n"
3769                "  int j;\n"
3770                "#endif // HEADER_H",
3771                getLLVMStyleWithColumns(20));
3772 
3773   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
3774   // Basic before hash indent tests
3775   verifyFormat("#ifdef _WIN32\n"
3776                "  #define A 0\n"
3777                "  #ifdef VAR2\n"
3778                "    #define B 1\n"
3779                "    #include <someheader.h>\n"
3780                "    #define MACRO                      \\\n"
3781                "      some_very_long_func_aaaaaaaaaa();\n"
3782                "  #endif\n"
3783                "#else\n"
3784                "  #define A 1\n"
3785                "#endif",
3786                Style);
3787   verifyFormat("#if A\n"
3788                "  #define MACRO                        \\\n"
3789                "    void a(int x) {                    \\\n"
3790                "      b();                             \\\n"
3791                "      c();                             \\\n"
3792                "      d();                             \\\n"
3793                "      e();                             \\\n"
3794                "      f();                             \\\n"
3795                "    }\n"
3796                "#endif",
3797                Style);
3798   // Keep comments aligned with indented directives. These
3799   // tests cannot use verifyFormat because messUp manipulates leading
3800   // whitespace.
3801   {
3802     const char *Expected = "void f() {\n"
3803                            "// Aligned to preprocessor.\n"
3804                            "#if 1\n"
3805                            "  // Aligned to code.\n"
3806                            "  int a;\n"
3807                            "  #if 1\n"
3808                            "    // Aligned to preprocessor.\n"
3809                            "    #define A 0\n"
3810                            "  // Aligned to code.\n"
3811                            "  int b;\n"
3812                            "  #endif\n"
3813                            "#endif\n"
3814                            "}";
3815     const char *ToFormat = "void f() {\n"
3816                            "// Aligned to preprocessor.\n"
3817                            "#if 1\n"
3818                            "// Aligned to code.\n"
3819                            "int a;\n"
3820                            "#if 1\n"
3821                            "// Aligned to preprocessor.\n"
3822                            "#define A 0\n"
3823                            "// Aligned to code.\n"
3824                            "int b;\n"
3825                            "#endif\n"
3826                            "#endif\n"
3827                            "}";
3828     EXPECT_EQ(Expected, format(ToFormat, Style));
3829     EXPECT_EQ(Expected, format(Expected, Style));
3830   }
3831   {
3832     const char *Expected = "void f() {\n"
3833                            "/* Aligned to preprocessor. */\n"
3834                            "#if 1\n"
3835                            "  /* Aligned to code. */\n"
3836                            "  int a;\n"
3837                            "  #if 1\n"
3838                            "    /* Aligned to preprocessor. */\n"
3839                            "    #define A 0\n"
3840                            "  /* Aligned to code. */\n"
3841                            "  int b;\n"
3842                            "  #endif\n"
3843                            "#endif\n"
3844                            "}";
3845     const char *ToFormat = "void f() {\n"
3846                            "/* Aligned to preprocessor. */\n"
3847                            "#if 1\n"
3848                            "/* Aligned to code. */\n"
3849                            "int a;\n"
3850                            "#if 1\n"
3851                            "/* Aligned to preprocessor. */\n"
3852                            "#define A 0\n"
3853                            "/* Aligned to code. */\n"
3854                            "int b;\n"
3855                            "#endif\n"
3856                            "#endif\n"
3857                            "}";
3858     EXPECT_EQ(Expected, format(ToFormat, Style));
3859     EXPECT_EQ(Expected, format(Expected, Style));
3860   }
3861 
3862   // Test single comment before preprocessor
3863   verifyFormat("// Comment\n"
3864                "\n"
3865                "#if 1\n"
3866                "#endif",
3867                Style);
3868 }
3869 
3870 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
3871   verifyFormat("{\n  { a #c; }\n}");
3872 }
3873 
3874 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
3875   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
3876             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
3877   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
3878             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
3879 }
3880 
3881 TEST_F(FormatTest, EscapedNewlines) {
3882   FormatStyle Narrow = getLLVMStyleWithColumns(11);
3883   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
3884             format("#define A \\\nint i;\\\n  int j;", Narrow));
3885   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
3886   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3887   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
3888   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
3889 
3890   FormatStyle AlignLeft = getLLVMStyle();
3891   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
3892   EXPECT_EQ("#define MACRO(x) \\\n"
3893             "private:         \\\n"
3894             "  int x(int a);\n",
3895             format("#define MACRO(x) \\\n"
3896                    "private:         \\\n"
3897                    "  int x(int a);\n",
3898                    AlignLeft));
3899 
3900   // CRLF line endings
3901   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
3902             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
3903   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
3904   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3905   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
3906   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
3907   EXPECT_EQ("#define MACRO(x) \\\r\n"
3908             "private:         \\\r\n"
3909             "  int x(int a);\r\n",
3910             format("#define MACRO(x) \\\r\n"
3911                    "private:         \\\r\n"
3912                    "  int x(int a);\r\n",
3913                    AlignLeft));
3914 
3915   FormatStyle DontAlign = getLLVMStyle();
3916   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
3917   DontAlign.MaxEmptyLinesToKeep = 3;
3918   // FIXME: can't use verifyFormat here because the newline before
3919   // "public:" is not inserted the first time it's reformatted
3920   EXPECT_EQ("#define A \\\n"
3921             "  class Foo { \\\n"
3922             "    void bar(); \\\n"
3923             "\\\n"
3924             "\\\n"
3925             "\\\n"
3926             "  public: \\\n"
3927             "    void baz(); \\\n"
3928             "  };",
3929             format("#define A \\\n"
3930                    "  class Foo { \\\n"
3931                    "    void bar(); \\\n"
3932                    "\\\n"
3933                    "\\\n"
3934                    "\\\n"
3935                    "  public: \\\n"
3936                    "    void baz(); \\\n"
3937                    "  };",
3938                    DontAlign));
3939 }
3940 
3941 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
3942   verifyFormat("#define A \\\n"
3943                "  int v(  \\\n"
3944                "      a); \\\n"
3945                "  int i;",
3946                getLLVMStyleWithColumns(11));
3947 }
3948 
3949 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
3950   EXPECT_EQ(
3951       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3952       "                      \\\n"
3953       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3954       "\n"
3955       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3956       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
3957       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
3958              "\\\n"
3959              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3960              "  \n"
3961              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3962              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
3963 }
3964 
3965 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
3966   EXPECT_EQ("int\n"
3967             "#define A\n"
3968             "    a;",
3969             format("int\n#define A\na;"));
3970   verifyFormat("functionCallTo(\n"
3971                "    someOtherFunction(\n"
3972                "        withSomeParameters, whichInSequence,\n"
3973                "        areLongerThanALine(andAnotherCall,\n"
3974                "#define A B\n"
3975                "                           withMoreParamters,\n"
3976                "                           whichStronglyInfluenceTheLayout),\n"
3977                "        andMoreParameters),\n"
3978                "    trailing);",
3979                getLLVMStyleWithColumns(69));
3980   verifyFormat("Foo::Foo()\n"
3981                "#ifdef BAR\n"
3982                "    : baz(0)\n"
3983                "#endif\n"
3984                "{\n"
3985                "}");
3986   verifyFormat("void f() {\n"
3987                "  if (true)\n"
3988                "#ifdef A\n"
3989                "    f(42);\n"
3990                "  x();\n"
3991                "#else\n"
3992                "    g();\n"
3993                "  x();\n"
3994                "#endif\n"
3995                "}");
3996   verifyFormat("void f(param1, param2,\n"
3997                "       param3,\n"
3998                "#ifdef A\n"
3999                "       param4(param5,\n"
4000                "#ifdef A1\n"
4001                "              param6,\n"
4002                "#ifdef A2\n"
4003                "              param7),\n"
4004                "#else\n"
4005                "              param8),\n"
4006                "       param9,\n"
4007                "#endif\n"
4008                "       param10,\n"
4009                "#endif\n"
4010                "       param11)\n"
4011                "#else\n"
4012                "       param12)\n"
4013                "#endif\n"
4014                "{\n"
4015                "  x();\n"
4016                "}",
4017                getLLVMStyleWithColumns(28));
4018   verifyFormat("#if 1\n"
4019                "int i;");
4020   verifyFormat("#if 1\n"
4021                "#endif\n"
4022                "#if 1\n"
4023                "#else\n"
4024                "#endif\n");
4025   verifyFormat("DEBUG({\n"
4026                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4027                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
4028                "});\n"
4029                "#if a\n"
4030                "#else\n"
4031                "#endif");
4032 
4033   verifyIncompleteFormat("void f(\n"
4034                          "#if A\n"
4035                          ");\n"
4036                          "#else\n"
4037                          "#endif");
4038 }
4039 
4040 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
4041   verifyFormat("#endif\n"
4042                "#if B");
4043 }
4044 
4045 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
4046   FormatStyle SingleLine = getLLVMStyle();
4047   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
4048   verifyFormat("#if 0\n"
4049                "#elif 1\n"
4050                "#endif\n"
4051                "void foo() {\n"
4052                "  if (test) foo2();\n"
4053                "}",
4054                SingleLine);
4055 }
4056 
4057 TEST_F(FormatTest, LayoutBlockInsideParens) {
4058   verifyFormat("functionCall({ int i; });");
4059   verifyFormat("functionCall({\n"
4060                "  int i;\n"
4061                "  int j;\n"
4062                "});");
4063   verifyFormat("functionCall(\n"
4064                "    {\n"
4065                "      int i;\n"
4066                "      int j;\n"
4067                "    },\n"
4068                "    aaaa, bbbb, cccc);");
4069   verifyFormat("functionA(functionB({\n"
4070                "            int i;\n"
4071                "            int j;\n"
4072                "          }),\n"
4073                "          aaaa, bbbb, cccc);");
4074   verifyFormat("functionCall(\n"
4075                "    {\n"
4076                "      int i;\n"
4077                "      int j;\n"
4078                "    },\n"
4079                "    aaaa, bbbb, // comment\n"
4080                "    cccc);");
4081   verifyFormat("functionA(functionB({\n"
4082                "            int i;\n"
4083                "            int j;\n"
4084                "          }),\n"
4085                "          aaaa, bbbb, // comment\n"
4086                "          cccc);");
4087   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
4088   verifyFormat("functionCall(aaaa, bbbb, {\n"
4089                "  int i;\n"
4090                "  int j;\n"
4091                "});");
4092   verifyFormat(
4093       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
4094       "    {\n"
4095       "      int i; // break\n"
4096       "    },\n"
4097       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4098       "                                     ccccccccccccccccc));");
4099   verifyFormat("DEBUG({\n"
4100                "  if (a)\n"
4101                "    f();\n"
4102                "});");
4103 }
4104 
4105 TEST_F(FormatTest, LayoutBlockInsideStatement) {
4106   EXPECT_EQ("SOME_MACRO { int i; }\n"
4107             "int i;",
4108             format("  SOME_MACRO  {int i;}  int i;"));
4109 }
4110 
4111 TEST_F(FormatTest, LayoutNestedBlocks) {
4112   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
4113                "  struct s {\n"
4114                "    int i;\n"
4115                "  };\n"
4116                "  s kBitsToOs[] = {{10}};\n"
4117                "  for (int i = 0; i < 10; ++i)\n"
4118                "    return;\n"
4119                "}");
4120   verifyFormat("call(parameter, {\n"
4121                "  something();\n"
4122                "  // Comment using all columns.\n"
4123                "  somethingelse();\n"
4124                "});",
4125                getLLVMStyleWithColumns(40));
4126   verifyFormat("DEBUG( //\n"
4127                "    { f(); }, a);");
4128   verifyFormat("DEBUG( //\n"
4129                "    {\n"
4130                "      f(); //\n"
4131                "    },\n"
4132                "    a);");
4133 
4134   EXPECT_EQ("call(parameter, {\n"
4135             "  something();\n"
4136             "  // Comment too\n"
4137             "  // looooooooooong.\n"
4138             "  somethingElse();\n"
4139             "});",
4140             format("call(parameter, {\n"
4141                    "  something();\n"
4142                    "  // Comment too looooooooooong.\n"
4143                    "  somethingElse();\n"
4144                    "});",
4145                    getLLVMStyleWithColumns(29)));
4146   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
4147   EXPECT_EQ("DEBUG({ // comment\n"
4148             "  int i;\n"
4149             "});",
4150             format("DEBUG({ // comment\n"
4151                    "int  i;\n"
4152                    "});"));
4153   EXPECT_EQ("DEBUG({\n"
4154             "  int i;\n"
4155             "\n"
4156             "  // comment\n"
4157             "  int j;\n"
4158             "});",
4159             format("DEBUG({\n"
4160                    "  int  i;\n"
4161                    "\n"
4162                    "  // comment\n"
4163                    "  int  j;\n"
4164                    "});"));
4165 
4166   verifyFormat("DEBUG({\n"
4167                "  if (a)\n"
4168                "    return;\n"
4169                "});");
4170   verifyGoogleFormat("DEBUG({\n"
4171                      "  if (a) return;\n"
4172                      "});");
4173   FormatStyle Style = getGoogleStyle();
4174   Style.ColumnLimit = 45;
4175   verifyFormat("Debug(\n"
4176                "    aaaaa,\n"
4177                "    {\n"
4178                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
4179                "    },\n"
4180                "    a);",
4181                Style);
4182 
4183   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
4184 
4185   verifyNoCrash("^{v^{a}}");
4186 }
4187 
4188 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
4189   EXPECT_EQ("#define MACRO()                     \\\n"
4190             "  Debug(aaa, /* force line break */ \\\n"
4191             "        {                           \\\n"
4192             "          int i;                    \\\n"
4193             "          int j;                    \\\n"
4194             "        })",
4195             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
4196                    "          {  int   i;  int  j;   })",
4197                    getGoogleStyle()));
4198 
4199   EXPECT_EQ("#define A                                       \\\n"
4200             "  [] {                                          \\\n"
4201             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
4202             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
4203             "  }",
4204             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
4205                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
4206                    getGoogleStyle()));
4207 }
4208 
4209 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
4210   EXPECT_EQ("{}", format("{}"));
4211   verifyFormat("enum E {};");
4212   verifyFormat("enum E {}");
4213   FormatStyle Style = getLLVMStyle();
4214   Style.SpaceInEmptyBlock = true;
4215   EXPECT_EQ("void f() { }", format("void f() {}", Style));
4216   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
4217   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
4218 }
4219 
4220 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
4221   FormatStyle Style = getLLVMStyle();
4222   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
4223   Style.MacroBlockEnd = "^[A-Z_]+_END$";
4224   verifyFormat("FOO_BEGIN\n"
4225                "  FOO_ENTRY\n"
4226                "FOO_END",
4227                Style);
4228   verifyFormat("FOO_BEGIN\n"
4229                "  NESTED_FOO_BEGIN\n"
4230                "    NESTED_FOO_ENTRY\n"
4231                "  NESTED_FOO_END\n"
4232                "FOO_END",
4233                Style);
4234   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
4235                "  int x;\n"
4236                "  x = 1;\n"
4237                "FOO_END(Baz)",
4238                Style);
4239 }
4240 
4241 //===----------------------------------------------------------------------===//
4242 // Line break tests.
4243 //===----------------------------------------------------------------------===//
4244 
4245 TEST_F(FormatTest, PreventConfusingIndents) {
4246   verifyFormat(
4247       "void f() {\n"
4248       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
4249       "                         parameter, parameter, parameter)),\n"
4250       "                     SecondLongCall(parameter));\n"
4251       "}");
4252   verifyFormat(
4253       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4254       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4255       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4256       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
4257   verifyFormat(
4258       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4259       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
4260       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
4261       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
4262   verifyFormat(
4263       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
4264       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
4265       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
4266       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
4267   verifyFormat("int a = bbbb && ccc &&\n"
4268                "        fffff(\n"
4269                "#define A Just forcing a new line\n"
4270                "            ddd);");
4271 }
4272 
4273 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
4274   verifyFormat(
4275       "bool aaaaaaa =\n"
4276       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
4277       "    bbbbbbbb();");
4278   verifyFormat(
4279       "bool aaaaaaa =\n"
4280       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
4281       "    bbbbbbbb();");
4282 
4283   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
4284                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
4285                "    ccccccccc == ddddddddddd;");
4286   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
4287                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
4288                "    ccccccccc == ddddddddddd;");
4289   verifyFormat(
4290       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
4291       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
4292       "    ccccccccc == ddddddddddd;");
4293 
4294   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
4295                "                 aaaaaa) &&\n"
4296                "         bbbbbb && cccccc;");
4297   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
4298                "                 aaaaaa) >>\n"
4299                "         bbbbbb;");
4300   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
4301                "    SourceMgr.getSpellingColumnNumber(\n"
4302                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
4303                "    1);");
4304 
4305   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4306                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
4307                "    cccccc) {\n}");
4308   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4309                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
4310                "              cccccc) {\n}");
4311   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4312                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
4313                "              cccccc) {\n}");
4314   verifyFormat("b = a &&\n"
4315                "    // Comment\n"
4316                "    b.c && d;");
4317 
4318   // If the LHS of a comparison is not a binary expression itself, the
4319   // additional linebreak confuses many people.
4320   verifyFormat(
4321       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4322       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
4323       "}");
4324   verifyFormat(
4325       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4326       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4327       "}");
4328   verifyFormat(
4329       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
4330       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4331       "}");
4332   verifyFormat(
4333       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4334       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
4335       "}");
4336   // Even explicit parentheses stress the precedence enough to make the
4337   // additional break unnecessary.
4338   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4339                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4340                "}");
4341   // This cases is borderline, but with the indentation it is still readable.
4342   verifyFormat(
4343       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4344       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4345       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
4346       "}",
4347       getLLVMStyleWithColumns(75));
4348 
4349   // If the LHS is a binary expression, we should still use the additional break
4350   // as otherwise the formatting hides the operator precedence.
4351   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4352                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4353                "    5) {\n"
4354                "}");
4355   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4356                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
4357                "    5) {\n"
4358                "}");
4359 
4360   FormatStyle OnePerLine = getLLVMStyle();
4361   OnePerLine.BinPackParameters = false;
4362   verifyFormat(
4363       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4364       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4365       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
4366       OnePerLine);
4367 
4368   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
4369                "                .aaa(aaaaaaaaaaaaa) *\n"
4370                "            aaaaaaa +\n"
4371                "        aaaaaaa;",
4372                getLLVMStyleWithColumns(40));
4373 }
4374 
4375 TEST_F(FormatTest, ExpressionIndentation) {
4376   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4377                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4378                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4379                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4380                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
4381                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
4382                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4383                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
4384                "                 ccccccccccccccccccccccccccccccccccccccccc;");
4385   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4386                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4387                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4388                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4389   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4390                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4391                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4392                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4393   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4394                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4395                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4396                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4397   verifyFormat("if () {\n"
4398                "} else if (aaaaa && bbbbb > // break\n"
4399                "                        ccccc) {\n"
4400                "}");
4401   verifyFormat("if () {\n"
4402                "} else if constexpr (aaaaa && bbbbb > // break\n"
4403                "                                  ccccc) {\n"
4404                "}");
4405   verifyFormat("if () {\n"
4406                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
4407                "                                  ccccc) {\n"
4408                "}");
4409   verifyFormat("if () {\n"
4410                "} else if (aaaaa &&\n"
4411                "           bbbbb > // break\n"
4412                "               ccccc &&\n"
4413                "           ddddd) {\n"
4414                "}");
4415 
4416   // Presence of a trailing comment used to change indentation of b.
4417   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
4418                "       b;\n"
4419                "return aaaaaaaaaaaaaaaaaaa +\n"
4420                "       b; //",
4421                getLLVMStyleWithColumns(30));
4422 }
4423 
4424 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
4425   // Not sure what the best system is here. Like this, the LHS can be found
4426   // immediately above an operator (everything with the same or a higher
4427   // indent). The RHS is aligned right of the operator and so compasses
4428   // everything until something with the same indent as the operator is found.
4429   // FIXME: Is this a good system?
4430   FormatStyle Style = getLLVMStyle();
4431   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
4432   verifyFormat(
4433       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4434       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4435       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4436       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4437       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4438       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4439       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4440       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4441       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
4442       Style);
4443   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4444                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4445                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4446                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4447                Style);
4448   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4449                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4450                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4451                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4452                Style);
4453   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4454                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4455                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4456                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4457                Style);
4458   verifyFormat("if () {\n"
4459                "} else if (aaaaa\n"
4460                "           && bbbbb // break\n"
4461                "                  > ccccc) {\n"
4462                "}",
4463                Style);
4464   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4465                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4466                Style);
4467   verifyFormat("return (a)\n"
4468                "       // comment\n"
4469                "       + b;",
4470                Style);
4471   verifyFormat(
4472       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4473       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4474       "             + cc;",
4475       Style);
4476 
4477   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4478                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4479                Style);
4480 
4481   // Forced by comments.
4482   verifyFormat(
4483       "unsigned ContentSize =\n"
4484       "    sizeof(int16_t)   // DWARF ARange version number\n"
4485       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4486       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4487       "    + sizeof(int8_t); // Segment Size (in bytes)");
4488 
4489   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
4490                "       == boost::fusion::at_c<1>(iiii).second;",
4491                Style);
4492 
4493   Style.ColumnLimit = 60;
4494   verifyFormat("zzzzzzzzzz\n"
4495                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4496                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
4497                Style);
4498 
4499   Style.ColumnLimit = 80;
4500   Style.IndentWidth = 4;
4501   Style.TabWidth = 4;
4502   Style.UseTab = FormatStyle::UT_Always;
4503   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4504   Style.AlignOperands = FormatStyle::OAS_DontAlign;
4505   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
4506             "\t&& (someOtherLongishConditionPart1\n"
4507             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
4508             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
4509                    "(someOtherLongishConditionPart1 || "
4510                    "someOtherEvenLongerNestedConditionPart2);",
4511                    Style));
4512 }
4513 
4514 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
4515   FormatStyle Style = getLLVMStyle();
4516   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
4517   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
4518 
4519   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4520                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4521                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4522                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4523                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4524                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4525                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4526                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4527                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
4528                Style);
4529   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4530                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4531                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4532                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4533                Style);
4534   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4535                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4536                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4537                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4538                Style);
4539   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4540                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4541                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4542                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4543                Style);
4544   verifyFormat("if () {\n"
4545                "} else if (aaaaa\n"
4546                "           && bbbbb // break\n"
4547                "                  > ccccc) {\n"
4548                "}",
4549                Style);
4550   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4551                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4552                Style);
4553   verifyFormat("return (a)\n"
4554                "     // comment\n"
4555                "     + b;",
4556                Style);
4557   verifyFormat(
4558       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4559       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4560       "           + cc;",
4561       Style);
4562   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
4563                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
4564                "                        : 3333333333333333;",
4565                Style);
4566   verifyFormat(
4567       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
4568       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
4569       "                                             : eeeeeeeeeeeeeeeeee)\n"
4570       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
4571       "                        : 3333333333333333;",
4572       Style);
4573   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4574                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4575                Style);
4576 
4577   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
4578                "    == boost::fusion::at_c<1>(iiii).second;",
4579                Style);
4580 
4581   Style.ColumnLimit = 60;
4582   verifyFormat("zzzzzzzzzzzzz\n"
4583                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4584                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
4585                Style);
4586 
4587   // Forced by comments.
4588   Style.ColumnLimit = 80;
4589   verifyFormat(
4590       "unsigned ContentSize\n"
4591       "    = sizeof(int16_t) // DWARF ARange version number\n"
4592       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4593       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4594       "    + sizeof(int8_t); // Segment Size (in bytes)",
4595       Style);
4596 
4597   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4598   verifyFormat(
4599       "unsigned ContentSize =\n"
4600       "    sizeof(int16_t)   // DWARF ARange version number\n"
4601       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4602       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4603       "    + sizeof(int8_t); // Segment Size (in bytes)",
4604       Style);
4605 
4606   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
4607   verifyFormat(
4608       "unsigned ContentSize =\n"
4609       "    sizeof(int16_t)   // DWARF ARange version number\n"
4610       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4611       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4612       "    + sizeof(int8_t); // Segment Size (in bytes)",
4613       Style);
4614 }
4615 
4616 TEST_F(FormatTest, EnforcedOperatorWraps) {
4617   // Here we'd like to wrap after the || operators, but a comment is forcing an
4618   // earlier wrap.
4619   verifyFormat("bool x = aaaaa //\n"
4620                "         || bbbbb\n"
4621                "         //\n"
4622                "         || cccc;");
4623 }
4624 
4625 TEST_F(FormatTest, NoOperandAlignment) {
4626   FormatStyle Style = getLLVMStyle();
4627   Style.AlignOperands = FormatStyle::OAS_DontAlign;
4628   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
4629                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4630                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4631                Style);
4632   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4633   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4634                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4635                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4636                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4637                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4638                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4639                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4640                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4641                "        > ccccccccccccccccccccccccccccccccccccccccc;",
4642                Style);
4643 
4644   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4645                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4646                "    + cc;",
4647                Style);
4648   verifyFormat("int a = aa\n"
4649                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4650                "        * cccccccccccccccccccccccccccccccccccc;\n",
4651                Style);
4652 
4653   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4654   verifyFormat("return (a > b\n"
4655                "    // comment1\n"
4656                "    // comment2\n"
4657                "    || c);",
4658                Style);
4659 }
4660 
4661 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
4662   FormatStyle Style = getLLVMStyle();
4663   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4664   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
4665                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4666                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4667                Style);
4668 }
4669 
4670 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
4671   FormatStyle Style = getLLVMStyle();
4672   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4673   Style.BinPackArguments = false;
4674   Style.ColumnLimit = 40;
4675   verifyFormat("void test() {\n"
4676                "  someFunction(\n"
4677                "      this + argument + is + quite\n"
4678                "      + long + so + it + gets + wrapped\n"
4679                "      + but + remains + bin - packed);\n"
4680                "}",
4681                Style);
4682   verifyFormat("void test() {\n"
4683                "  someFunction(arg1,\n"
4684                "               this + argument + is\n"
4685                "                   + quite + long + so\n"
4686                "                   + it + gets + wrapped\n"
4687                "                   + but + remains + bin\n"
4688                "                   - packed,\n"
4689                "               arg3);\n"
4690                "}",
4691                Style);
4692   verifyFormat("void test() {\n"
4693                "  someFunction(\n"
4694                "      arg1,\n"
4695                "      this + argument + has\n"
4696                "          + anotherFunc(nested,\n"
4697                "                        calls + whose\n"
4698                "                            + arguments\n"
4699                "                            + are + also\n"
4700                "                            + wrapped,\n"
4701                "                        in + addition)\n"
4702                "          + to + being + bin - packed,\n"
4703                "      arg3);\n"
4704                "}",
4705                Style);
4706 
4707   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
4708   verifyFormat("void test() {\n"
4709                "  someFunction(\n"
4710                "      arg1,\n"
4711                "      this + argument + has +\n"
4712                "          anotherFunc(nested,\n"
4713                "                      calls + whose +\n"
4714                "                          arguments +\n"
4715                "                          are + also +\n"
4716                "                          wrapped,\n"
4717                "                      in + addition) +\n"
4718                "          to + being + bin - packed,\n"
4719                "      arg3);\n"
4720                "}",
4721                Style);
4722 }
4723 
4724 TEST_F(FormatTest, ConstructorInitializers) {
4725   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
4726   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
4727                getLLVMStyleWithColumns(45));
4728   verifyFormat("Constructor()\n"
4729                "    : Inttializer(FitsOnTheLine) {}",
4730                getLLVMStyleWithColumns(44));
4731   verifyFormat("Constructor()\n"
4732                "    : Inttializer(FitsOnTheLine) {}",
4733                getLLVMStyleWithColumns(43));
4734 
4735   verifyFormat("template <typename T>\n"
4736                "Constructor() : Initializer(FitsOnTheLine) {}",
4737                getLLVMStyleWithColumns(45));
4738 
4739   verifyFormat(
4740       "SomeClass::Constructor()\n"
4741       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
4742 
4743   verifyFormat(
4744       "SomeClass::Constructor()\n"
4745       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4746       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
4747   verifyFormat(
4748       "SomeClass::Constructor()\n"
4749       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4750       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
4751   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4752                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4753                "    : aaaaaaaaaa(aaaaaa) {}");
4754 
4755   verifyFormat("Constructor()\n"
4756                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4757                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4758                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4759                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
4760 
4761   verifyFormat("Constructor()\n"
4762                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4763                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4764 
4765   verifyFormat("Constructor(int Parameter = 0)\n"
4766                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
4767                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
4768   verifyFormat("Constructor()\n"
4769                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
4770                "}",
4771                getLLVMStyleWithColumns(60));
4772   verifyFormat("Constructor()\n"
4773                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4774                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
4775 
4776   // Here a line could be saved by splitting the second initializer onto two
4777   // lines, but that is not desirable.
4778   verifyFormat("Constructor()\n"
4779                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
4780                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
4781                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4782 
4783   FormatStyle OnePerLine = getLLVMStyle();
4784   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4785   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
4786   verifyFormat("SomeClass::Constructor()\n"
4787                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4788                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4789                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4790                OnePerLine);
4791   verifyFormat("SomeClass::Constructor()\n"
4792                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
4793                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4794                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4795                OnePerLine);
4796   verifyFormat("MyClass::MyClass(int var)\n"
4797                "    : some_var_(var),            // 4 space indent\n"
4798                "      some_other_var_(var + 1) { // lined up\n"
4799                "}",
4800                OnePerLine);
4801   verifyFormat("Constructor()\n"
4802                "    : aaaaa(aaaaaa),\n"
4803                "      aaaaa(aaaaaa),\n"
4804                "      aaaaa(aaaaaa),\n"
4805                "      aaaaa(aaaaaa),\n"
4806                "      aaaaa(aaaaaa) {}",
4807                OnePerLine);
4808   verifyFormat("Constructor()\n"
4809                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
4810                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
4811                OnePerLine);
4812   OnePerLine.BinPackParameters = false;
4813   verifyFormat(
4814       "Constructor()\n"
4815       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4816       "          aaaaaaaaaaa().aaa(),\n"
4817       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4818       OnePerLine);
4819   OnePerLine.ColumnLimit = 60;
4820   verifyFormat("Constructor()\n"
4821                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4822                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
4823                OnePerLine);
4824 
4825   EXPECT_EQ("Constructor()\n"
4826             "    : // Comment forcing unwanted break.\n"
4827             "      aaaa(aaaa) {}",
4828             format("Constructor() :\n"
4829                    "    // Comment forcing unwanted break.\n"
4830                    "    aaaa(aaaa) {}"));
4831 }
4832 
4833 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
4834   FormatStyle Style = getLLVMStyle();
4835   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4836   Style.ColumnLimit = 60;
4837   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4838   Style.AllowAllConstructorInitializersOnNextLine = true;
4839   Style.BinPackParameters = false;
4840 
4841   for (int i = 0; i < 4; ++i) {
4842     // Test all combinations of parameters that should not have an effect.
4843     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
4844     Style.AllowAllArgumentsOnNextLine = i & 2;
4845 
4846     Style.AllowAllConstructorInitializersOnNextLine = true;
4847     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4848     verifyFormat("Constructor()\n"
4849                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4850                  Style);
4851     verifyFormat("Constructor() : a(a), b(b) {}", Style);
4852 
4853     Style.AllowAllConstructorInitializersOnNextLine = false;
4854     verifyFormat("Constructor()\n"
4855                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4856                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4857                  Style);
4858     verifyFormat("Constructor() : a(a), b(b) {}", Style);
4859 
4860     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
4861     Style.AllowAllConstructorInitializersOnNextLine = true;
4862     verifyFormat("Constructor()\n"
4863                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4864                  Style);
4865 
4866     Style.AllowAllConstructorInitializersOnNextLine = false;
4867     verifyFormat("Constructor()\n"
4868                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4869                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4870                  Style);
4871 
4872     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4873     Style.AllowAllConstructorInitializersOnNextLine = true;
4874     verifyFormat("Constructor() :\n"
4875                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4876                  Style);
4877 
4878     Style.AllowAllConstructorInitializersOnNextLine = false;
4879     verifyFormat("Constructor() :\n"
4880                  "    aaaaaaaaaaaaaaaaaa(a),\n"
4881                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4882                  Style);
4883   }
4884 
4885   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
4886   // AllowAllConstructorInitializersOnNextLine in all
4887   // BreakConstructorInitializers modes
4888   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4889   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4890   Style.AllowAllConstructorInitializersOnNextLine = false;
4891   verifyFormat("SomeClassWithALongName::Constructor(\n"
4892                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
4893                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4894                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4895                Style);
4896 
4897   Style.AllowAllConstructorInitializersOnNextLine = true;
4898   verifyFormat("SomeClassWithALongName::Constructor(\n"
4899                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4900                "    int bbbbbbbbbbbbb,\n"
4901                "    int cccccccccccccccc)\n"
4902                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4903                Style);
4904 
4905   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4906   Style.AllowAllConstructorInitializersOnNextLine = false;
4907   verifyFormat("SomeClassWithALongName::Constructor(\n"
4908                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4909                "    int bbbbbbbbbbbbb)\n"
4910                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4911                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4912                Style);
4913 
4914   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
4915 
4916   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4917   verifyFormat("SomeClassWithALongName::Constructor(\n"
4918                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
4919                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4920                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4921                Style);
4922 
4923   Style.AllowAllConstructorInitializersOnNextLine = true;
4924   verifyFormat("SomeClassWithALongName::Constructor(\n"
4925                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4926                "    int bbbbbbbbbbbbb,\n"
4927                "    int cccccccccccccccc)\n"
4928                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4929                Style);
4930 
4931   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4932   Style.AllowAllConstructorInitializersOnNextLine = false;
4933   verifyFormat("SomeClassWithALongName::Constructor(\n"
4934                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4935                "    int bbbbbbbbbbbbb)\n"
4936                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4937                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4938                Style);
4939 
4940   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4941   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4942   verifyFormat("SomeClassWithALongName::Constructor(\n"
4943                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
4944                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
4945                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4946                Style);
4947 
4948   Style.AllowAllConstructorInitializersOnNextLine = true;
4949   verifyFormat("SomeClassWithALongName::Constructor(\n"
4950                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4951                "    int bbbbbbbbbbbbb,\n"
4952                "    int cccccccccccccccc) :\n"
4953                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4954                Style);
4955 
4956   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4957   Style.AllowAllConstructorInitializersOnNextLine = false;
4958   verifyFormat("SomeClassWithALongName::Constructor(\n"
4959                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4960                "    int bbbbbbbbbbbbb) :\n"
4961                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
4962                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4963                Style);
4964 }
4965 
4966 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
4967   FormatStyle Style = getLLVMStyle();
4968   Style.ColumnLimit = 60;
4969   Style.BinPackArguments = false;
4970   for (int i = 0; i < 4; ++i) {
4971     // Test all combinations of parameters that should not have an effect.
4972     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
4973     Style.AllowAllConstructorInitializersOnNextLine = i & 2;
4974 
4975     Style.AllowAllArgumentsOnNextLine = true;
4976     verifyFormat("void foo() {\n"
4977                  "  FunctionCallWithReallyLongName(\n"
4978                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
4979                  "}",
4980                  Style);
4981     Style.AllowAllArgumentsOnNextLine = false;
4982     verifyFormat("void foo() {\n"
4983                  "  FunctionCallWithReallyLongName(\n"
4984                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4985                  "      bbbbbbbbbbbb);\n"
4986                  "}",
4987                  Style);
4988 
4989     Style.AllowAllArgumentsOnNextLine = true;
4990     verifyFormat("void foo() {\n"
4991                  "  auto VariableWithReallyLongName = {\n"
4992                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
4993                  "}",
4994                  Style);
4995     Style.AllowAllArgumentsOnNextLine = false;
4996     verifyFormat("void foo() {\n"
4997                  "  auto VariableWithReallyLongName = {\n"
4998                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4999                  "      bbbbbbbbbbbb};\n"
5000                  "}",
5001                  Style);
5002   }
5003 
5004   // This parameter should not affect declarations.
5005   Style.BinPackParameters = false;
5006   Style.AllowAllArgumentsOnNextLine = false;
5007   Style.AllowAllParametersOfDeclarationOnNextLine = true;
5008   verifyFormat("void FunctionCallWithReallyLongName(\n"
5009                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
5010                Style);
5011   Style.AllowAllParametersOfDeclarationOnNextLine = false;
5012   verifyFormat("void FunctionCallWithReallyLongName(\n"
5013                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
5014                "    int bbbbbbbbbbbb);",
5015                Style);
5016 }
5017 
5018 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
5019   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
5020   // and BAS_Align.
5021   auto Style = getLLVMStyle();
5022   Style.ColumnLimit = 35;
5023   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
5024                     "void functionDecl(int A, int B, int C);";
5025   Style.AllowAllArgumentsOnNextLine = false;
5026   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5027   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5028                       "    paramC);\n"
5029                       "void functionDecl(int A, int B,\n"
5030                       "    int C);"),
5031             format(Input, Style));
5032   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
5033   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5034                       "             paramC);\n"
5035                       "void functionDecl(int A, int B,\n"
5036                       "                  int C);"),
5037             format(Input, Style));
5038   // However, BAS_AlwaysBreak should take precedence over
5039   // AllowAllArgumentsOnNextLine.
5040   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
5041   EXPECT_EQ(StringRef("functionCall(\n"
5042                       "    paramA, paramB, paramC);\n"
5043                       "void functionDecl(\n"
5044                       "    int A, int B, int C);"),
5045             format(Input, Style));
5046 
5047   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
5048   // first argument.
5049   Style.AllowAllArgumentsOnNextLine = true;
5050   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
5051   EXPECT_EQ(StringRef("functionCall(\n"
5052                       "    paramA, paramB, paramC);\n"
5053                       "void functionDecl(\n"
5054                       "    int A, int B, int C);"),
5055             format(Input, Style));
5056   // It wouldn't fit on one line with aligned parameters so this setting
5057   // doesn't change anything for BAS_Align.
5058   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
5059   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5060                       "             paramC);\n"
5061                       "void functionDecl(int A, int B,\n"
5062                       "                  int C);"),
5063             format(Input, Style));
5064   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5065   EXPECT_EQ(StringRef("functionCall(\n"
5066                       "    paramA, paramB, paramC);\n"
5067                       "void functionDecl(\n"
5068                       "    int A, int B, int C);"),
5069             format(Input, Style));
5070 }
5071 
5072 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
5073   FormatStyle Style = getLLVMStyle();
5074   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
5075 
5076   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
5077   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
5078                getStyleWithColumns(Style, 45));
5079   verifyFormat("Constructor() :\n"
5080                "    Initializer(FitsOnTheLine) {}",
5081                getStyleWithColumns(Style, 44));
5082   verifyFormat("Constructor() :\n"
5083                "    Initializer(FitsOnTheLine) {}",
5084                getStyleWithColumns(Style, 43));
5085 
5086   verifyFormat("template <typename T>\n"
5087                "Constructor() : Initializer(FitsOnTheLine) {}",
5088                getStyleWithColumns(Style, 50));
5089   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5090   verifyFormat(
5091       "SomeClass::Constructor() :\n"
5092       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5093       Style);
5094 
5095   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
5096   verifyFormat(
5097       "SomeClass::Constructor() :\n"
5098       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5099       Style);
5100 
5101   verifyFormat(
5102       "SomeClass::Constructor() :\n"
5103       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5104       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5105       Style);
5106   verifyFormat(
5107       "SomeClass::Constructor() :\n"
5108       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5109       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5110       Style);
5111   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5112                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
5113                "    aaaaaaaaaa(aaaaaa) {}",
5114                Style);
5115 
5116   verifyFormat("Constructor() :\n"
5117                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5118                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5119                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5120                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
5121                Style);
5122 
5123   verifyFormat("Constructor() :\n"
5124                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5125                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5126                Style);
5127 
5128   verifyFormat("Constructor(int Parameter = 0) :\n"
5129                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
5130                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
5131                Style);
5132   verifyFormat("Constructor() :\n"
5133                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
5134                "}",
5135                getStyleWithColumns(Style, 60));
5136   verifyFormat("Constructor() :\n"
5137                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5138                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
5139                Style);
5140 
5141   // Here a line could be saved by splitting the second initializer onto two
5142   // lines, but that is not desirable.
5143   verifyFormat("Constructor() :\n"
5144                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
5145                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
5146                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5147                Style);
5148 
5149   FormatStyle OnePerLine = Style;
5150   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5151   OnePerLine.AllowAllConstructorInitializersOnNextLine = false;
5152   verifyFormat("SomeClass::Constructor() :\n"
5153                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5154                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5155                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5156                OnePerLine);
5157   verifyFormat("SomeClass::Constructor() :\n"
5158                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
5159                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5160                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5161                OnePerLine);
5162   verifyFormat("MyClass::MyClass(int var) :\n"
5163                "    some_var_(var),            // 4 space indent\n"
5164                "    some_other_var_(var + 1) { // lined up\n"
5165                "}",
5166                OnePerLine);
5167   verifyFormat("Constructor() :\n"
5168                "    aaaaa(aaaaaa),\n"
5169                "    aaaaa(aaaaaa),\n"
5170                "    aaaaa(aaaaaa),\n"
5171                "    aaaaa(aaaaaa),\n"
5172                "    aaaaa(aaaaaa) {}",
5173                OnePerLine);
5174   verifyFormat("Constructor() :\n"
5175                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
5176                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
5177                OnePerLine);
5178   OnePerLine.BinPackParameters = false;
5179   verifyFormat("Constructor() :\n"
5180                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5181                "        aaaaaaaaaaa().aaa(),\n"
5182                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5183                OnePerLine);
5184   OnePerLine.ColumnLimit = 60;
5185   verifyFormat("Constructor() :\n"
5186                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
5187                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
5188                OnePerLine);
5189 
5190   EXPECT_EQ("Constructor() :\n"
5191             "    // Comment forcing unwanted break.\n"
5192             "    aaaa(aaaa) {}",
5193             format("Constructor() :\n"
5194                    "    // Comment forcing unwanted break.\n"
5195                    "    aaaa(aaaa) {}",
5196                    Style));
5197 
5198   Style.ColumnLimit = 0;
5199   verifyFormat("SomeClass::Constructor() :\n"
5200                "    a(a) {}",
5201                Style);
5202   verifyFormat("SomeClass::Constructor() noexcept :\n"
5203                "    a(a) {}",
5204                Style);
5205   verifyFormat("SomeClass::Constructor() :\n"
5206                "    a(a), b(b), c(c) {}",
5207                Style);
5208   verifyFormat("SomeClass::Constructor() :\n"
5209                "    a(a) {\n"
5210                "  foo();\n"
5211                "  bar();\n"
5212                "}",
5213                Style);
5214 
5215   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
5216   verifyFormat("SomeClass::Constructor() :\n"
5217                "    a(a), b(b), c(c) {\n"
5218                "}",
5219                Style);
5220   verifyFormat("SomeClass::Constructor() :\n"
5221                "    a(a) {\n"
5222                "}",
5223                Style);
5224 
5225   Style.ColumnLimit = 80;
5226   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
5227   Style.ConstructorInitializerIndentWidth = 2;
5228   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
5229   verifyFormat("SomeClass::Constructor() :\n"
5230                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5231                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
5232                Style);
5233 
5234   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
5235   // well
5236   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
5237   verifyFormat(
5238       "class SomeClass\n"
5239       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5240       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5241       Style);
5242   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
5243   verifyFormat(
5244       "class SomeClass\n"
5245       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5246       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5247       Style);
5248   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
5249   verifyFormat(
5250       "class SomeClass :\n"
5251       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5252       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5253       Style);
5254 }
5255 
5256 #ifndef EXPENSIVE_CHECKS
5257 // Expensive checks enables libstdc++ checking which includes validating the
5258 // state of ranges used in std::priority_queue - this blows out the
5259 // runtime/scalability of the function and makes this test unacceptably slow.
5260 TEST_F(FormatTest, MemoizationTests) {
5261   // This breaks if the memoization lookup does not take \c Indent and
5262   // \c LastSpace into account.
5263   verifyFormat(
5264       "extern CFRunLoopTimerRef\n"
5265       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
5266       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
5267       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
5268       "                     CFRunLoopTimerContext *context) {}");
5269 
5270   // Deep nesting somewhat works around our memoization.
5271   verifyFormat(
5272       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5273       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5274       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5275       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5276       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
5277       getLLVMStyleWithColumns(65));
5278   verifyFormat(
5279       "aaaaa(\n"
5280       "    aaaaa,\n"
5281       "    aaaaa(\n"
5282       "        aaaaa,\n"
5283       "        aaaaa(\n"
5284       "            aaaaa,\n"
5285       "            aaaaa(\n"
5286       "                aaaaa,\n"
5287       "                aaaaa(\n"
5288       "                    aaaaa,\n"
5289       "                    aaaaa(\n"
5290       "                        aaaaa,\n"
5291       "                        aaaaa(\n"
5292       "                            aaaaa,\n"
5293       "                            aaaaa(\n"
5294       "                                aaaaa,\n"
5295       "                                aaaaa(\n"
5296       "                                    aaaaa,\n"
5297       "                                    aaaaa(\n"
5298       "                                        aaaaa,\n"
5299       "                                        aaaaa(\n"
5300       "                                            aaaaa,\n"
5301       "                                            aaaaa(\n"
5302       "                                                aaaaa,\n"
5303       "                                                aaaaa))))))))))));",
5304       getLLVMStyleWithColumns(65));
5305   verifyFormat(
5306       "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n"
5307       "                                  a),\n"
5308       "                                a),\n"
5309       "                              a),\n"
5310       "                            a),\n"
5311       "                          a),\n"
5312       "                        a),\n"
5313       "                      a),\n"
5314       "                    a),\n"
5315       "                  a),\n"
5316       "                a),\n"
5317       "              a),\n"
5318       "            a),\n"
5319       "          a),\n"
5320       "        a),\n"
5321       "      a),\n"
5322       "    a),\n"
5323       "  a)",
5324       getLLVMStyleWithColumns(65));
5325 
5326   // This test takes VERY long when memoization is broken.
5327   FormatStyle OnePerLine = getLLVMStyle();
5328   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5329   OnePerLine.BinPackParameters = false;
5330   std::string input = "Constructor()\n"
5331                       "    : aaaa(a,\n";
5332   for (unsigned i = 0, e = 80; i != e; ++i) {
5333     input += "           a,\n";
5334   }
5335   input += "           a) {}";
5336   verifyFormat(input, OnePerLine);
5337 }
5338 #endif
5339 
5340 TEST_F(FormatTest, BreaksAsHighAsPossible) {
5341   verifyFormat(
5342       "void f() {\n"
5343       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
5344       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
5345       "    f();\n"
5346       "}");
5347   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
5348                "    Intervals[i - 1].getRange().getLast()) {\n}");
5349 }
5350 
5351 TEST_F(FormatTest, BreaksFunctionDeclarations) {
5352   // Principially, we break function declarations in a certain order:
5353   // 1) break amongst arguments.
5354   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
5355                "                              Cccccccccccccc cccccccccccccc);");
5356   verifyFormat("template <class TemplateIt>\n"
5357                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
5358                "                            TemplateIt *stop) {}");
5359 
5360   // 2) break after return type.
5361   verifyFormat(
5362       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5363       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
5364       getGoogleStyle());
5365 
5366   // 3) break after (.
5367   verifyFormat(
5368       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
5369       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
5370       getGoogleStyle());
5371 
5372   // 4) break before after nested name specifiers.
5373   verifyFormat(
5374       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5375       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
5376       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
5377       getGoogleStyle());
5378 
5379   // However, there are exceptions, if a sufficient amount of lines can be
5380   // saved.
5381   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
5382   // more adjusting.
5383   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
5384                "                                  Cccccccccccccc cccccccccc,\n"
5385                "                                  Cccccccccccccc cccccccccc,\n"
5386                "                                  Cccccccccccccc cccccccccc,\n"
5387                "                                  Cccccccccccccc cccccccccc);");
5388   verifyFormat(
5389       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5390       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5391       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5392       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
5393       getGoogleStyle());
5394   verifyFormat(
5395       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
5396       "                                          Cccccccccccccc cccccccccc,\n"
5397       "                                          Cccccccccccccc cccccccccc,\n"
5398       "                                          Cccccccccccccc cccccccccc,\n"
5399       "                                          Cccccccccccccc cccccccccc,\n"
5400       "                                          Cccccccccccccc cccccccccc,\n"
5401       "                                          Cccccccccccccc cccccccccc);");
5402   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5403                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5404                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5405                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5406                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
5407 
5408   // Break after multi-line parameters.
5409   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5410                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5411                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5412                "    bbbb bbbb);");
5413   verifyFormat("void SomeLoooooooooooongFunction(\n"
5414                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
5415                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5416                "    int bbbbbbbbbbbbb);");
5417 
5418   // Treat overloaded operators like other functions.
5419   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5420                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
5421   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5422                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
5423   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5424                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
5425   verifyGoogleFormat(
5426       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
5427       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
5428   verifyGoogleFormat(
5429       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
5430       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
5431   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5432                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
5433   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
5434                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
5435   verifyGoogleFormat(
5436       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
5437       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5438       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
5439   verifyGoogleFormat("template <typename T>\n"
5440                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5441                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
5442                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
5443 
5444   FormatStyle Style = getLLVMStyle();
5445   Style.PointerAlignment = FormatStyle::PAS_Left;
5446   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5447                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
5448                Style);
5449   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
5450                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5451                Style);
5452 }
5453 
5454 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
5455   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
5456   // Prefer keeping `::` followed by `operator` together.
5457   EXPECT_EQ("const aaaa::bbbbbbb &\n"
5458             "ccccccccc::operator++() {\n"
5459             "  stuff();\n"
5460             "}",
5461             format("const aaaa::bbbbbbb\n"
5462                    "&ccccccccc::operator++() { stuff(); }",
5463                    getLLVMStyleWithColumns(40)));
5464 }
5465 
5466 TEST_F(FormatTest, TrailingReturnType) {
5467   verifyFormat("auto foo() -> int;\n");
5468   // correct trailing return type spacing
5469   verifyFormat("auto operator->() -> int;\n");
5470   verifyFormat("auto operator++(int) -> int;\n");
5471 
5472   verifyFormat("struct S {\n"
5473                "  auto bar() const -> int;\n"
5474                "};");
5475   verifyFormat("template <size_t Order, typename T>\n"
5476                "auto load_img(const std::string &filename)\n"
5477                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
5478   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
5479                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
5480   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
5481   verifyFormat("template <typename T>\n"
5482                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
5483                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
5484 
5485   // Not trailing return types.
5486   verifyFormat("void f() { auto a = b->c(); }");
5487 }
5488 
5489 TEST_F(FormatTest, DeductionGuides) {
5490   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
5491   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
5492   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
5493   verifyFormat(
5494       "template <class... T>\n"
5495       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
5496   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
5497   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
5498   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
5499   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
5500   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
5501   verifyFormat("template <class T> x() -> x<1>;");
5502   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
5503 
5504   // Ensure not deduction guides.
5505   verifyFormat("c()->f<int>();");
5506   verifyFormat("x()->foo<1>;");
5507   verifyFormat("x = p->foo<3>();");
5508   verifyFormat("x()->x<1>();");
5509   verifyFormat("x()->x<1>;");
5510 }
5511 
5512 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
5513   // Avoid breaking before trailing 'const' or other trailing annotations, if
5514   // they are not function-like.
5515   FormatStyle Style = getGoogleStyle();
5516   Style.ColumnLimit = 47;
5517   verifyFormat("void someLongFunction(\n"
5518                "    int someLoooooooooooooongParameter) const {\n}",
5519                getLLVMStyleWithColumns(47));
5520   verifyFormat("LoooooongReturnType\n"
5521                "someLoooooooongFunction() const {}",
5522                getLLVMStyleWithColumns(47));
5523   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
5524                "    const {}",
5525                Style);
5526   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5527                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
5528   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5529                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
5530   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5531                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
5532   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
5533                "                   aaaaaaaaaaa aaaaa) const override;");
5534   verifyGoogleFormat(
5535       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5536       "    const override;");
5537 
5538   // Even if the first parameter has to be wrapped.
5539   verifyFormat("void someLongFunction(\n"
5540                "    int someLongParameter) const {}",
5541                getLLVMStyleWithColumns(46));
5542   verifyFormat("void someLongFunction(\n"
5543                "    int someLongParameter) const {}",
5544                Style);
5545   verifyFormat("void someLongFunction(\n"
5546                "    int someLongParameter) override {}",
5547                Style);
5548   verifyFormat("void someLongFunction(\n"
5549                "    int someLongParameter) OVERRIDE {}",
5550                Style);
5551   verifyFormat("void someLongFunction(\n"
5552                "    int someLongParameter) final {}",
5553                Style);
5554   verifyFormat("void someLongFunction(\n"
5555                "    int someLongParameter) FINAL {}",
5556                Style);
5557   verifyFormat("void someLongFunction(\n"
5558                "    int parameter) const override {}",
5559                Style);
5560 
5561   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
5562   verifyFormat("void someLongFunction(\n"
5563                "    int someLongParameter) const\n"
5564                "{\n"
5565                "}",
5566                Style);
5567 
5568   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
5569   verifyFormat("void someLongFunction(\n"
5570                "    int someLongParameter) const\n"
5571                "  {\n"
5572                "  }",
5573                Style);
5574 
5575   // Unless these are unknown annotations.
5576   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
5577                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5578                "    LONG_AND_UGLY_ANNOTATION;");
5579 
5580   // Breaking before function-like trailing annotations is fine to keep them
5581   // close to their arguments.
5582   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5583                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5584   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5585                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5586   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5587                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
5588   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
5589                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
5590   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
5591 
5592   verifyFormat(
5593       "void aaaaaaaaaaaaaaaaaa()\n"
5594       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
5595       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
5596   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5597                "    __attribute__((unused));");
5598   verifyGoogleFormat(
5599       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5600       "    GUARDED_BY(aaaaaaaaaaaa);");
5601   verifyGoogleFormat(
5602       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5603       "    GUARDED_BY(aaaaaaaaaaaa);");
5604   verifyGoogleFormat(
5605       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
5606       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5607   verifyGoogleFormat(
5608       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
5609       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
5610 }
5611 
5612 TEST_F(FormatTest, FunctionAnnotations) {
5613   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5614                "int OldFunction(const string &parameter) {}");
5615   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5616                "string OldFunction(const string &parameter) {}");
5617   verifyFormat("template <typename T>\n"
5618                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5619                "string OldFunction(const string &parameter) {}");
5620 
5621   // Not function annotations.
5622   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5623                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
5624   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
5625                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
5626   verifyFormat("MACRO(abc).function() // wrap\n"
5627                "    << abc;");
5628   verifyFormat("MACRO(abc)->function() // wrap\n"
5629                "    << abc;");
5630   verifyFormat("MACRO(abc)::function() // wrap\n"
5631                "    << abc;");
5632 }
5633 
5634 TEST_F(FormatTest, BreaksDesireably) {
5635   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
5636                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
5637                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
5638   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5639                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
5640                "}");
5641 
5642   verifyFormat(
5643       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5644       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5645 
5646   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5647                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5648                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5649 
5650   verifyFormat(
5651       "aaaaaaaa(aaaaaaaaaaaaa,\n"
5652       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5653       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
5654       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5655       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
5656 
5657   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5658                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5659 
5660   verifyFormat(
5661       "void f() {\n"
5662       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
5663       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5664       "}");
5665   verifyFormat(
5666       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5667       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5668   verifyFormat(
5669       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5670       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5671   verifyFormat(
5672       "aaaaaa(aaa,\n"
5673       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5674       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5675       "       aaaa);");
5676   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5677                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5678                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5679 
5680   // Indent consistently independent of call expression and unary operator.
5681   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5682                "    dddddddddddddddddddddddddddddd));");
5683   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5684                "    dddddddddddddddddddddddddddddd));");
5685   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
5686                "    dddddddddddddddddddddddddddddd));");
5687 
5688   // This test case breaks on an incorrect memoization, i.e. an optimization not
5689   // taking into account the StopAt value.
5690   verifyFormat(
5691       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5692       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5693       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5694       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5695 
5696   verifyFormat("{\n  {\n    {\n"
5697                "      Annotation.SpaceRequiredBefore =\n"
5698                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
5699                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
5700                "    }\n  }\n}");
5701 
5702   // Break on an outer level if there was a break on an inner level.
5703   EXPECT_EQ("f(g(h(a, // comment\n"
5704             "      b, c),\n"
5705             "    d, e),\n"
5706             "  x, y);",
5707             format("f(g(h(a, // comment\n"
5708                    "    b, c), d, e), x, y);"));
5709 
5710   // Prefer breaking similar line breaks.
5711   verifyFormat(
5712       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
5713       "                             NSTrackingMouseEnteredAndExited |\n"
5714       "                             NSTrackingActiveAlways;");
5715 }
5716 
5717 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
5718   FormatStyle NoBinPacking = getGoogleStyle();
5719   NoBinPacking.BinPackParameters = false;
5720   NoBinPacking.BinPackArguments = true;
5721   verifyFormat("void f() {\n"
5722                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
5723                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5724                "}",
5725                NoBinPacking);
5726   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
5727                "       int aaaaaaaaaaaaaaaaaaaa,\n"
5728                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5729                NoBinPacking);
5730 
5731   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
5732   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5733                "                        vector<int> bbbbbbbbbbbbbbb);",
5734                NoBinPacking);
5735   // FIXME: This behavior difference is probably not wanted. However, currently
5736   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
5737   // template arguments from BreakBeforeParameter being set because of the
5738   // one-per-line formatting.
5739   verifyFormat(
5740       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
5741       "                                             aaaaaaaaaa> aaaaaaaaaa);",
5742       NoBinPacking);
5743   verifyFormat(
5744       "void fffffffffff(\n"
5745       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
5746       "        aaaaaaaaaa);");
5747 }
5748 
5749 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
5750   FormatStyle NoBinPacking = getGoogleStyle();
5751   NoBinPacking.BinPackParameters = false;
5752   NoBinPacking.BinPackArguments = false;
5753   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
5754                "  aaaaaaaaaaaaaaaaaaaa,\n"
5755                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
5756                NoBinPacking);
5757   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
5758                "        aaaaaaaaaaaaa,\n"
5759                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
5760                NoBinPacking);
5761   verifyFormat(
5762       "aaaaaaaa(aaaaaaaaaaaaa,\n"
5763       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5764       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
5765       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5766       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
5767       NoBinPacking);
5768   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
5769                "    .aaaaaaaaaaaaaaaaaa();",
5770                NoBinPacking);
5771   verifyFormat("void f() {\n"
5772                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5773                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
5774                "}",
5775                NoBinPacking);
5776 
5777   verifyFormat(
5778       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5779       "             aaaaaaaaaaaa,\n"
5780       "             aaaaaaaaaaaa);",
5781       NoBinPacking);
5782   verifyFormat(
5783       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
5784       "                               ddddddddddddddddddddddddddddd),\n"
5785       "             test);",
5786       NoBinPacking);
5787 
5788   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
5789                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
5790                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
5791                "    aaaaaaaaaaaaaaaaaa;",
5792                NoBinPacking);
5793   verifyFormat("a(\"a\"\n"
5794                "  \"a\",\n"
5795                "  a);");
5796 
5797   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
5798   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
5799                "                aaaaaaaaa,\n"
5800                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5801                NoBinPacking);
5802   verifyFormat(
5803       "void f() {\n"
5804       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
5805       "      .aaaaaaa();\n"
5806       "}",
5807       NoBinPacking);
5808   verifyFormat(
5809       "template <class SomeType, class SomeOtherType>\n"
5810       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
5811       NoBinPacking);
5812 }
5813 
5814 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
5815   FormatStyle Style = getLLVMStyleWithColumns(15);
5816   Style.ExperimentalAutoDetectBinPacking = true;
5817   EXPECT_EQ("aaa(aaaa,\n"
5818             "    aaaa,\n"
5819             "    aaaa);\n"
5820             "aaa(aaaa,\n"
5821             "    aaaa,\n"
5822             "    aaaa);",
5823             format("aaa(aaaa,\n" // one-per-line
5824                    "  aaaa,\n"
5825                    "    aaaa  );\n"
5826                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
5827                    Style));
5828   EXPECT_EQ("aaa(aaaa, aaaa,\n"
5829             "    aaaa);\n"
5830             "aaa(aaaa, aaaa,\n"
5831             "    aaaa);",
5832             format("aaa(aaaa,  aaaa,\n" // bin-packed
5833                    "    aaaa  );\n"
5834                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
5835                    Style));
5836 }
5837 
5838 TEST_F(FormatTest, FormatsBuilderPattern) {
5839   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
5840                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
5841                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
5842                "    .StartsWith(\".init\", ORDER_INIT)\n"
5843                "    .StartsWith(\".fini\", ORDER_FINI)\n"
5844                "    .StartsWith(\".hash\", ORDER_HASH)\n"
5845                "    .Default(ORDER_TEXT);\n");
5846 
5847   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
5848                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
5849   verifyFormat("aaaaaaa->aaaaaaa\n"
5850                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5851                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5852                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
5853   verifyFormat(
5854       "aaaaaaa->aaaaaaa\n"
5855       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5856       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
5857   verifyFormat(
5858       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
5859       "    aaaaaaaaaaaaaa);");
5860   verifyFormat(
5861       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
5862       "    aaaaaa->aaaaaaaaaaaa()\n"
5863       "        ->aaaaaaaaaaaaaaaa(\n"
5864       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5865       "        ->aaaaaaaaaaaaaaaaa();");
5866   verifyGoogleFormat(
5867       "void f() {\n"
5868       "  someo->Add((new util::filetools::Handler(dir))\n"
5869       "                 ->OnEvent1(NewPermanentCallback(\n"
5870       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
5871       "                 ->OnEvent2(NewPermanentCallback(\n"
5872       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
5873       "                 ->OnEvent3(NewPermanentCallback(\n"
5874       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
5875       "                 ->OnEvent5(NewPermanentCallback(\n"
5876       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
5877       "                 ->OnEvent6(NewPermanentCallback(\n"
5878       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
5879       "}");
5880 
5881   verifyFormat(
5882       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
5883   verifyFormat("aaaaaaaaaaaaaaa()\n"
5884                "    .aaaaaaaaaaaaaaa()\n"
5885                "    .aaaaaaaaaaaaaaa()\n"
5886                "    .aaaaaaaaaaaaaaa()\n"
5887                "    .aaaaaaaaaaaaaaa();");
5888   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5889                "    .aaaaaaaaaaaaaaa()\n"
5890                "    .aaaaaaaaaaaaaaa()\n"
5891                "    .aaaaaaaaaaaaaaa();");
5892   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5893                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5894                "    .aaaaaaaaaaaaaaa();");
5895   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
5896                "    ->aaaaaaaaaaaaaae(0)\n"
5897                "    ->aaaaaaaaaaaaaaa();");
5898 
5899   // Don't linewrap after very short segments.
5900   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5901                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5902                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5903   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5904                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5905                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5906   verifyFormat("aaa()\n"
5907                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5908                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5909                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5910 
5911   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
5912                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5913                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
5914   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
5915                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5916                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
5917 
5918   // Prefer not to break after empty parentheses.
5919   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
5920                "    First->LastNewlineOffset);");
5921 
5922   // Prefer not to create "hanging" indents.
5923   verifyFormat(
5924       "return !soooooooooooooome_map\n"
5925       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5926       "            .second;");
5927   verifyFormat(
5928       "return aaaaaaaaaaaaaaaa\n"
5929       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
5930       "    .aaaa(aaaaaaaaaaaaaa);");
5931   // No hanging indent here.
5932   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
5933                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5934   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
5935                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5936   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
5937                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5938                getLLVMStyleWithColumns(60));
5939   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
5940                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
5941                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5942                getLLVMStyleWithColumns(59));
5943   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5944                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5945                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5946 
5947   // Dont break if only closing statements before member call
5948   verifyFormat("test() {\n"
5949                "  ([]() -> {\n"
5950                "    int b = 32;\n"
5951                "    return 3;\n"
5952                "  }).foo();\n"
5953                "}");
5954   verifyFormat("test() {\n"
5955                "  (\n"
5956                "      []() -> {\n"
5957                "        int b = 32;\n"
5958                "        return 3;\n"
5959                "      },\n"
5960                "      foo, bar)\n"
5961                "      .foo();\n"
5962                "}");
5963   verifyFormat("test() {\n"
5964                "  ([]() -> {\n"
5965                "    int b = 32;\n"
5966                "    return 3;\n"
5967                "  })\n"
5968                "      .foo()\n"
5969                "      .bar();\n"
5970                "}");
5971   verifyFormat("test() {\n"
5972                "  ([]() -> {\n"
5973                "    int b = 32;\n"
5974                "    return 3;\n"
5975                "  })\n"
5976                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
5977                "           \"bbbb\");\n"
5978                "}",
5979                getLLVMStyleWithColumns(30));
5980 }
5981 
5982 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
5983   verifyFormat(
5984       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5985       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
5986   verifyFormat(
5987       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
5988       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
5989 
5990   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
5991                "    ccccccccccccccccccccccccc) {\n}");
5992   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
5993                "    ccccccccccccccccccccccccc) {\n}");
5994 
5995   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
5996                "    ccccccccccccccccccccccccc) {\n}");
5997   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
5998                "    ccccccccccccccccccccccccc) {\n}");
5999 
6000   verifyFormat(
6001       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
6002       "    ccccccccccccccccccccccccc) {\n}");
6003   verifyFormat(
6004       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
6005       "    ccccccccccccccccccccccccc) {\n}");
6006 
6007   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
6008                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
6009                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
6010                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
6011   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
6012                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
6013                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
6014                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
6015 
6016   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
6017                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
6018                "    aaaaaaaaaaaaaaa != aa) {\n}");
6019   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
6020                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
6021                "    aaaaaaaaaaaaaaa != aa) {\n}");
6022 }
6023 
6024 TEST_F(FormatTest, BreaksAfterAssignments) {
6025   verifyFormat(
6026       "unsigned Cost =\n"
6027       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
6028       "                        SI->getPointerAddressSpaceee());\n");
6029   verifyFormat(
6030       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
6031       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
6032 
6033   verifyFormat(
6034       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
6035       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
6036   verifyFormat("unsigned OriginalStartColumn =\n"
6037                "    SourceMgr.getSpellingColumnNumber(\n"
6038                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
6039                "    1;");
6040 }
6041 
6042 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
6043   FormatStyle Style = getLLVMStyle();
6044   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6045                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
6046                Style);
6047 
6048   Style.PenaltyBreakAssignment = 20;
6049   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6050                "                                 cccccccccccccccccccccccccc;",
6051                Style);
6052 }
6053 
6054 TEST_F(FormatTest, AlignsAfterAssignments) {
6055   verifyFormat(
6056       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6057       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
6058   verifyFormat(
6059       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6060       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
6061   verifyFormat(
6062       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6063       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
6064   verifyFormat(
6065       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6066       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
6067   verifyFormat(
6068       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
6069       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
6070       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
6071 }
6072 
6073 TEST_F(FormatTest, AlignsAfterReturn) {
6074   verifyFormat(
6075       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6076       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
6077   verifyFormat(
6078       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6079       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
6080   verifyFormat(
6081       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
6082       "       aaaaaaaaaaaaaaaaaaaaaa();");
6083   verifyFormat(
6084       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
6085       "        aaaaaaaaaaaaaaaaaaaaaa());");
6086   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6087                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6088   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6089                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
6090                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6091   verifyFormat("return\n"
6092                "    // true if code is one of a or b.\n"
6093                "    code == a || code == b;");
6094 }
6095 
6096 TEST_F(FormatTest, AlignsAfterOpenBracket) {
6097   verifyFormat(
6098       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
6099       "                                                aaaaaaaaa aaaaaaa) {}");
6100   verifyFormat(
6101       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
6102       "                                               aaaaaaaaaaa aaaaaaaaa);");
6103   verifyFormat(
6104       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
6105       "                                             aaaaaaaaaaaaaaaaaaaaa));");
6106   FormatStyle Style = getLLVMStyle();
6107   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6108   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6109                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
6110                Style);
6111   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
6112                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
6113                Style);
6114   verifyFormat("SomeLongVariableName->someFunction(\n"
6115                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
6116                Style);
6117   verifyFormat(
6118       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
6119       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6120       Style);
6121   verifyFormat(
6122       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
6123       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6124       Style);
6125   verifyFormat(
6126       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
6127       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
6128       Style);
6129 
6130   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
6131                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
6132                "        b));",
6133                Style);
6134 
6135   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6136   Style.BinPackArguments = false;
6137   Style.BinPackParameters = false;
6138   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6139                "    aaaaaaaaaaa aaaaaaaa,\n"
6140                "    aaaaaaaaa aaaaaaa,\n"
6141                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6142                Style);
6143   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
6144                "    aaaaaaaaaaa aaaaaaaaa,\n"
6145                "    aaaaaaaaaaa aaaaaaaaa,\n"
6146                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6147                Style);
6148   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
6149                "    aaaaaaaaaaaaaaa,\n"
6150                "    aaaaaaaaaaaaaaaaaaaaa,\n"
6151                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
6152                Style);
6153   verifyFormat(
6154       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
6155       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
6156       Style);
6157   verifyFormat(
6158       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
6159       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
6160       Style);
6161   verifyFormat(
6162       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6163       "    aaaaaaaaaaaaaaaaaaaaa(\n"
6164       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
6165       "    aaaaaaaaaaaaaaaa);",
6166       Style);
6167   verifyFormat(
6168       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6169       "    aaaaaaaaaaaaaaaaaaaaa(\n"
6170       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
6171       "    aaaaaaaaaaaaaaaa);",
6172       Style);
6173 }
6174 
6175 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
6176   FormatStyle Style = getLLVMStyleWithColumns(40);
6177   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6178                "          bbbbbbbbbbbbbbbbbbbbbb);",
6179                Style);
6180   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6181   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6182   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6183                "          bbbbbbbbbbbbbbbbbbbbbb);",
6184                Style);
6185   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6186   Style.AlignOperands = FormatStyle::OAS_Align;
6187   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6188                "          bbbbbbbbbbbbbbbbbbbbbb);",
6189                Style);
6190   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6191   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6192   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6193                "    bbbbbbbbbbbbbbbbbbbbbb);",
6194                Style);
6195 }
6196 
6197 TEST_F(FormatTest, BreaksConditionalExpressions) {
6198   verifyFormat(
6199       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6200       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6201       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6202   verifyFormat(
6203       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
6204       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6205       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6206   verifyFormat(
6207       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6208       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6209   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
6210                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6211                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6212   verifyFormat(
6213       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
6214       "                                                    : aaaaaaaaaaaaa);");
6215   verifyFormat(
6216       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6217       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6218       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6219       "                   aaaaaaaaaaaaa);");
6220   verifyFormat(
6221       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6222       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6223       "                   aaaaaaaaaaaaa);");
6224   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6225                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6226                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6227                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6228                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6229   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6230                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6231                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6232                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6233                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6234                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6235                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6236   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6237                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6238                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6239                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6240                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6241   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6242                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6243                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6244   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
6245                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6246                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6247                "        : aaaaaaaaaaaaaaaa;");
6248   verifyFormat(
6249       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6250       "    ? aaaaaaaaaaaaaaa\n"
6251       "    : aaaaaaaaaaaaaaa;");
6252   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
6253                "          aaaaaaaaa\n"
6254                "      ? b\n"
6255                "      : c);");
6256   verifyFormat("return aaaa == bbbb\n"
6257                "           // comment\n"
6258                "           ? aaaa\n"
6259                "           : bbbb;");
6260   verifyFormat("unsigned Indent =\n"
6261                "    format(TheLine.First,\n"
6262                "           IndentForLevel[TheLine.Level] >= 0\n"
6263                "               ? IndentForLevel[TheLine.Level]\n"
6264                "               : TheLine * 2,\n"
6265                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
6266                getLLVMStyleWithColumns(60));
6267   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
6268                "                  ? aaaaaaaaaaaaaaa\n"
6269                "                  : bbbbbbbbbbbbbbb //\n"
6270                "                        ? ccccccccccccccc\n"
6271                "                        : ddddddddddddddd;");
6272   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
6273                "                  ? aaaaaaaaaaaaaaa\n"
6274                "                  : (bbbbbbbbbbbbbbb //\n"
6275                "                         ? ccccccccccccccc\n"
6276                "                         : ddddddddddddddd);");
6277   verifyFormat(
6278       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6279       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6280       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
6281       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
6282       "                                      : aaaaaaaaaa;");
6283   verifyFormat(
6284       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6285       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
6286       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6287 
6288   FormatStyle NoBinPacking = getLLVMStyle();
6289   NoBinPacking.BinPackArguments = false;
6290   verifyFormat(
6291       "void f() {\n"
6292       "  g(aaa,\n"
6293       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
6294       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6295       "        ? aaaaaaaaaaaaaaa\n"
6296       "        : aaaaaaaaaaaaaaa);\n"
6297       "}",
6298       NoBinPacking);
6299   verifyFormat(
6300       "void f() {\n"
6301       "  g(aaa,\n"
6302       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
6303       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6304       "        ?: aaaaaaaaaaaaaaa);\n"
6305       "}",
6306       NoBinPacking);
6307 
6308   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
6309                "             // comment.\n"
6310                "             ccccccccccccccccccccccccccccccccccccccc\n"
6311                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6312                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
6313 
6314   // Assignments in conditional expressions. Apparently not uncommon :-(.
6315   verifyFormat("return a != b\n"
6316                "           // comment\n"
6317                "           ? a = b\n"
6318                "           : a = b;");
6319   verifyFormat("return a != b\n"
6320                "           // comment\n"
6321                "           ? a = a != b\n"
6322                "                     // comment\n"
6323                "                     ? a = b\n"
6324                "                     : a\n"
6325                "           : a;\n");
6326   verifyFormat("return a != b\n"
6327                "           // comment\n"
6328                "           ? a\n"
6329                "           : a = a != b\n"
6330                "                     // comment\n"
6331                "                     ? a = b\n"
6332                "                     : a;");
6333 
6334   // Chained conditionals
6335   FormatStyle Style = getLLVMStyle();
6336   Style.ColumnLimit = 70;
6337   Style.AlignOperands = FormatStyle::OAS_Align;
6338   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6339                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6340                "                        : 3333333333333333;",
6341                Style);
6342   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6343                "       : bbbbbbbbbb     ? 2222222222222222\n"
6344                "                        : 3333333333333333;",
6345                Style);
6346   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
6347                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6348                "                          : 3333333333333333;",
6349                Style);
6350   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6351                "       : bbbbbbbbbbbbbb ? 222222\n"
6352                "                        : 333333;",
6353                Style);
6354   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6355                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6356                "       : cccccccccccccc ? 3333333333333333\n"
6357                "                        : 4444444444444444;",
6358                Style);
6359   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
6360                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6361                "                        : 3333333333333333;",
6362                Style);
6363   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6364                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6365                "                        : (aaa ? bbb : ccc);",
6366                Style);
6367   verifyFormat(
6368       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6369       "                                             : cccccccccccccccccc)\n"
6370       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6371       "                        : 3333333333333333;",
6372       Style);
6373   verifyFormat(
6374       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6375       "                                             : cccccccccccccccccc)\n"
6376       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6377       "                        : 3333333333333333;",
6378       Style);
6379   verifyFormat(
6380       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6381       "                                             : dddddddddddddddddd)\n"
6382       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6383       "                        : 3333333333333333;",
6384       Style);
6385   verifyFormat(
6386       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6387       "                                             : dddddddddddddddddd)\n"
6388       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6389       "                        : 3333333333333333;",
6390       Style);
6391   verifyFormat(
6392       "return aaaaaaaaa        ? 1111111111111111\n"
6393       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6394       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6395       "                                             : dddddddddddddddddd)\n",
6396       Style);
6397   verifyFormat(
6398       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6399       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6400       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6401       "                                             : cccccccccccccccccc);",
6402       Style);
6403   verifyFormat(
6404       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6405       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6406       "                                             : eeeeeeeeeeeeeeeeee)\n"
6407       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6408       "                        : 3333333333333333;",
6409       Style);
6410   verifyFormat(
6411       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6412       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6413       "                                             : eeeeeeeeeeeeeeeeee)\n"
6414       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6415       "                        : 3333333333333333;",
6416       Style);
6417   verifyFormat(
6418       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6419       "                           : cccccccccccc    ? dddddddddddddddddd\n"
6420       "                                             : eeeeeeeeeeeeeeeeee)\n"
6421       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6422       "                        : 3333333333333333;",
6423       Style);
6424   verifyFormat(
6425       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6426       "                                             : cccccccccccccccccc\n"
6427       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6428       "                        : 3333333333333333;",
6429       Style);
6430   verifyFormat(
6431       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6432       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
6433       "                                             : eeeeeeeeeeeeeeeeee\n"
6434       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6435       "                        : 3333333333333333;",
6436       Style);
6437   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
6438                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
6439                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
6440                "                                   : eeeeeeeeeeeeeeeeee)\n"
6441                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
6442                "                             : 3333333333333333;",
6443                Style);
6444   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
6445                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6446                "             : cccccccccccccccc ? dddddddddddddddddd\n"
6447                "                                : eeeeeeeeeeeeeeeeee\n"
6448                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
6449                "                                 : 3333333333333333;",
6450                Style);
6451 
6452   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6453   Style.BreakBeforeTernaryOperators = false;
6454   // FIXME: Aligning the question marks is weird given DontAlign.
6455   // Consider disabling this alignment in this case. Also check whether this
6456   // will render the adjustment from https://reviews.llvm.org/D82199
6457   // unnecessary.
6458   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
6459                "    bbbb                ? cccccccccccccccccc :\n"
6460                "                          ddddd;\n",
6461                Style);
6462 }
6463 
6464 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
6465   FormatStyle Style = getLLVMStyle();
6466   Style.BreakBeforeTernaryOperators = false;
6467   Style.ColumnLimit = 70;
6468   verifyFormat(
6469       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6470       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6471       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6472       Style);
6473   verifyFormat(
6474       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
6475       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6476       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6477       Style);
6478   verifyFormat(
6479       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6480       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6481       Style);
6482   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
6483                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6484                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6485                Style);
6486   verifyFormat(
6487       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
6488       "                                                      aaaaaaaaaaaaa);",
6489       Style);
6490   verifyFormat(
6491       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6492       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6493       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6494       "                   aaaaaaaaaaaaa);",
6495       Style);
6496   verifyFormat(
6497       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6498       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6499       "                   aaaaaaaaaaaaa);",
6500       Style);
6501   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6502                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6503                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6504                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6505                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6506                Style);
6507   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6508                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6509                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6510                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6511                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6512                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6513                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6514                Style);
6515   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6516                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
6517                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6518                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6519                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6520                Style);
6521   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6522                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6523                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6524                Style);
6525   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
6526                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6527                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6528                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6529                Style);
6530   verifyFormat(
6531       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6532       "    aaaaaaaaaaaaaaa :\n"
6533       "    aaaaaaaaaaaaaaa;",
6534       Style);
6535   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
6536                "          aaaaaaaaa ?\n"
6537                "      b :\n"
6538                "      c);",
6539                Style);
6540   verifyFormat("unsigned Indent =\n"
6541                "    format(TheLine.First,\n"
6542                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
6543                "               IndentForLevel[TheLine.Level] :\n"
6544                "               TheLine * 2,\n"
6545                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
6546                Style);
6547   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6548                "                  aaaaaaaaaaaaaaa :\n"
6549                "                  bbbbbbbbbbbbbbb ? //\n"
6550                "                      ccccccccccccccc :\n"
6551                "                      ddddddddddddddd;",
6552                Style);
6553   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6554                "                  aaaaaaaaaaaaaaa :\n"
6555                "                  (bbbbbbbbbbbbbbb ? //\n"
6556                "                       ccccccccccccccc :\n"
6557                "                       ddddddddddddddd);",
6558                Style);
6559   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6560                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
6561                "            ccccccccccccccccccccccccccc;",
6562                Style);
6563   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6564                "           aaaaa :\n"
6565                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
6566                Style);
6567 
6568   // Chained conditionals
6569   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6570                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6571                "                          3333333333333333;",
6572                Style);
6573   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6574                "       bbbbbbbbbb       ? 2222222222222222 :\n"
6575                "                          3333333333333333;",
6576                Style);
6577   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
6578                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6579                "                          3333333333333333;",
6580                Style);
6581   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6582                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
6583                "                          333333;",
6584                Style);
6585   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6586                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6587                "       cccccccccccccccc ? 3333333333333333 :\n"
6588                "                          4444444444444444;",
6589                Style);
6590   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
6591                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6592                "                          3333333333333333;",
6593                Style);
6594   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6595                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6596                "                          (aaa ? bbb : ccc);",
6597                Style);
6598   verifyFormat(
6599       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6600       "                                               cccccccccccccccccc) :\n"
6601       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6602       "                          3333333333333333;",
6603       Style);
6604   verifyFormat(
6605       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6606       "                                               cccccccccccccccccc) :\n"
6607       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6608       "                          3333333333333333;",
6609       Style);
6610   verifyFormat(
6611       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6612       "                                               dddddddddddddddddd) :\n"
6613       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6614       "                          3333333333333333;",
6615       Style);
6616   verifyFormat(
6617       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6618       "                                               dddddddddddddddddd) :\n"
6619       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6620       "                          3333333333333333;",
6621       Style);
6622   verifyFormat(
6623       "return aaaaaaaaa        ? 1111111111111111 :\n"
6624       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6625       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6626       "                                               dddddddddddddddddd)\n",
6627       Style);
6628   verifyFormat(
6629       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6630       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6631       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6632       "                                               cccccccccccccccccc);",
6633       Style);
6634   verifyFormat(
6635       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6636       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
6637       "                                               eeeeeeeeeeeeeeeeee) :\n"
6638       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6639       "                          3333333333333333;",
6640       Style);
6641   verifyFormat(
6642       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6643       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
6644       "                                               eeeeeeeeeeeeeeeeee) :\n"
6645       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6646       "                          3333333333333333;",
6647       Style);
6648   verifyFormat(
6649       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
6650       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
6651       "                                               eeeeeeeeeeeeeeeeee) :\n"
6652       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6653       "                          3333333333333333;",
6654       Style);
6655   verifyFormat(
6656       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6657       "                                               cccccccccccccccccc :\n"
6658       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6659       "                          3333333333333333;",
6660       Style);
6661   verifyFormat(
6662       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6663       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
6664       "                                               eeeeeeeeeeeeeeeeee :\n"
6665       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6666       "                          3333333333333333;",
6667       Style);
6668   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
6669                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6670                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
6671                "                                 eeeeeeeeeeeeeeeeee) :\n"
6672                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6673                "                               3333333333333333;",
6674                Style);
6675   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
6676                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6677                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
6678                "                                  eeeeeeeeeeeeeeeeee :\n"
6679                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6680                "                               3333333333333333;",
6681                Style);
6682 }
6683 
6684 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
6685   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
6686                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
6687   verifyFormat("bool a = true, b = false;");
6688 
6689   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6690                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
6691                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
6692                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
6693   verifyFormat(
6694       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6695       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
6696       "     d = e && f;");
6697   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
6698                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
6699   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
6700                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
6701   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
6702                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
6703 
6704   FormatStyle Style = getGoogleStyle();
6705   Style.PointerAlignment = FormatStyle::PAS_Left;
6706   Style.DerivePointerAlignment = false;
6707   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6708                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
6709                "    *b = bbbbbbbbbbbbbbbbbbb;",
6710                Style);
6711   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
6712                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
6713                Style);
6714   verifyFormat("vector<int*> a, b;", Style);
6715   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
6716 }
6717 
6718 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
6719   verifyFormat("arr[foo ? bar : baz];");
6720   verifyFormat("f()[foo ? bar : baz];");
6721   verifyFormat("(a + b)[foo ? bar : baz];");
6722   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
6723 }
6724 
6725 TEST_F(FormatTest, AlignsStringLiterals) {
6726   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
6727                "                                      \"short literal\");");
6728   verifyFormat(
6729       "looooooooooooooooooooooooongFunction(\n"
6730       "    \"short literal\"\n"
6731       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
6732   verifyFormat("someFunction(\"Always break between multi-line\"\n"
6733                "             \" string literals\",\n"
6734                "             and, other, parameters);");
6735   EXPECT_EQ("fun + \"1243\" /* comment */\n"
6736             "      \"5678\";",
6737             format("fun + \"1243\" /* comment */\n"
6738                    "    \"5678\";",
6739                    getLLVMStyleWithColumns(28)));
6740   EXPECT_EQ(
6741       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
6742       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
6743       "         \"aaaaaaaaaaaaaaaa\";",
6744       format("aaaaaa ="
6745              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
6746              "aaaaaaaaaaaaaaaaaaaaa\" "
6747              "\"aaaaaaaaaaaaaaaa\";"));
6748   verifyFormat("a = a + \"a\"\n"
6749                "        \"a\"\n"
6750                "        \"a\";");
6751   verifyFormat("f(\"a\", \"b\"\n"
6752                "       \"c\");");
6753 
6754   verifyFormat(
6755       "#define LL_FORMAT \"ll\"\n"
6756       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
6757       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
6758 
6759   verifyFormat("#define A(X)          \\\n"
6760                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
6761                "  \"ccccc\"",
6762                getLLVMStyleWithColumns(23));
6763   verifyFormat("#define A \"def\"\n"
6764                "f(\"abc\" A \"ghi\"\n"
6765                "  \"jkl\");");
6766 
6767   verifyFormat("f(L\"a\"\n"
6768                "  L\"b\");");
6769   verifyFormat("#define A(X)            \\\n"
6770                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
6771                "  L\"ccccc\"",
6772                getLLVMStyleWithColumns(25));
6773 
6774   verifyFormat("f(@\"a\"\n"
6775                "  @\"b\");");
6776   verifyFormat("NSString s = @\"a\"\n"
6777                "             @\"b\"\n"
6778                "             @\"c\";");
6779   verifyFormat("NSString s = @\"a\"\n"
6780                "              \"b\"\n"
6781                "              \"c\";");
6782 }
6783 
6784 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
6785   FormatStyle Style = getLLVMStyle();
6786   // No declarations or definitions should be moved to own line.
6787   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
6788   verifyFormat("class A {\n"
6789                "  int f() { return 1; }\n"
6790                "  int g();\n"
6791                "};\n"
6792                "int f() { return 1; }\n"
6793                "int g();\n",
6794                Style);
6795 
6796   // All declarations and definitions should have the return type moved to its
6797   // own line.
6798   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
6799   Style.TypenameMacros = {"LIST"};
6800   verifyFormat("SomeType\n"
6801                "funcdecl(LIST(uint64_t));",
6802                Style);
6803   verifyFormat("class E {\n"
6804                "  int\n"
6805                "  f() {\n"
6806                "    return 1;\n"
6807                "  }\n"
6808                "  int\n"
6809                "  g();\n"
6810                "};\n"
6811                "int\n"
6812                "f() {\n"
6813                "  return 1;\n"
6814                "}\n"
6815                "int\n"
6816                "g();\n",
6817                Style);
6818 
6819   // Top-level definitions, and no kinds of declarations should have the
6820   // return type moved to its own line.
6821   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
6822   verifyFormat("class B {\n"
6823                "  int f() { return 1; }\n"
6824                "  int g();\n"
6825                "};\n"
6826                "int\n"
6827                "f() {\n"
6828                "  return 1;\n"
6829                "}\n"
6830                "int g();\n",
6831                Style);
6832 
6833   // Top-level definitions and declarations should have the return type moved
6834   // to its own line.
6835   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
6836   verifyFormat("class C {\n"
6837                "  int f() { return 1; }\n"
6838                "  int g();\n"
6839                "};\n"
6840                "int\n"
6841                "f() {\n"
6842                "  return 1;\n"
6843                "}\n"
6844                "int\n"
6845                "g();\n",
6846                Style);
6847 
6848   // All definitions should have the return type moved to its own line, but no
6849   // kinds of declarations.
6850   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
6851   verifyFormat("class D {\n"
6852                "  int\n"
6853                "  f() {\n"
6854                "    return 1;\n"
6855                "  }\n"
6856                "  int g();\n"
6857                "};\n"
6858                "int\n"
6859                "f() {\n"
6860                "  return 1;\n"
6861                "}\n"
6862                "int g();\n",
6863                Style);
6864   verifyFormat("const char *\n"
6865                "f(void) {\n" // Break here.
6866                "  return \"\";\n"
6867                "}\n"
6868                "const char *bar(void);\n", // No break here.
6869                Style);
6870   verifyFormat("template <class T>\n"
6871                "T *\n"
6872                "f(T &c) {\n" // Break here.
6873                "  return NULL;\n"
6874                "}\n"
6875                "template <class T> T *f(T &c);\n", // No break here.
6876                Style);
6877   verifyFormat("class C {\n"
6878                "  int\n"
6879                "  operator+() {\n"
6880                "    return 1;\n"
6881                "  }\n"
6882                "  int\n"
6883                "  operator()() {\n"
6884                "    return 1;\n"
6885                "  }\n"
6886                "};\n",
6887                Style);
6888   verifyFormat("void\n"
6889                "A::operator()() {}\n"
6890                "void\n"
6891                "A::operator>>() {}\n"
6892                "void\n"
6893                "A::operator+() {}\n"
6894                "void\n"
6895                "A::operator*() {}\n"
6896                "void\n"
6897                "A::operator->() {}\n"
6898                "void\n"
6899                "A::operator void *() {}\n"
6900                "void\n"
6901                "A::operator void &() {}\n"
6902                "void\n"
6903                "A::operator void &&() {}\n"
6904                "void\n"
6905                "A::operator char *() {}\n"
6906                "void\n"
6907                "A::operator[]() {}\n"
6908                "void\n"
6909                "A::operator!() {}\n"
6910                "void\n"
6911                "A::operator**() {}\n"
6912                "void\n"
6913                "A::operator<Foo> *() {}\n"
6914                "void\n"
6915                "A::operator<Foo> **() {}\n"
6916                "void\n"
6917                "A::operator<Foo> &() {}\n"
6918                "void\n"
6919                "A::operator void **() {}\n",
6920                Style);
6921   verifyFormat("constexpr auto\n"
6922                "operator()() const -> reference {}\n"
6923                "constexpr auto\n"
6924                "operator>>() const -> reference {}\n"
6925                "constexpr auto\n"
6926                "operator+() const -> reference {}\n"
6927                "constexpr auto\n"
6928                "operator*() const -> reference {}\n"
6929                "constexpr auto\n"
6930                "operator->() const -> reference {}\n"
6931                "constexpr auto\n"
6932                "operator++() const -> reference {}\n"
6933                "constexpr auto\n"
6934                "operator void *() const -> reference {}\n"
6935                "constexpr auto\n"
6936                "operator void **() const -> reference {}\n"
6937                "constexpr auto\n"
6938                "operator void *() const -> reference {}\n"
6939                "constexpr auto\n"
6940                "operator void &() const -> reference {}\n"
6941                "constexpr auto\n"
6942                "operator void &&() const -> reference {}\n"
6943                "constexpr auto\n"
6944                "operator char *() const -> reference {}\n"
6945                "constexpr auto\n"
6946                "operator!() const -> reference {}\n"
6947                "constexpr auto\n"
6948                "operator[]() const -> reference {}\n",
6949                Style);
6950   verifyFormat("void *operator new(std::size_t s);", // No break here.
6951                Style);
6952   verifyFormat("void *\n"
6953                "operator new(std::size_t s) {}",
6954                Style);
6955   verifyFormat("void *\n"
6956                "operator delete[](void *ptr) {}",
6957                Style);
6958   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
6959   verifyFormat("const char *\n"
6960                "f(void)\n" // Break here.
6961                "{\n"
6962                "  return \"\";\n"
6963                "}\n"
6964                "const char *bar(void);\n", // No break here.
6965                Style);
6966   verifyFormat("template <class T>\n"
6967                "T *\n"     // Problem here: no line break
6968                "f(T &c)\n" // Break here.
6969                "{\n"
6970                "  return NULL;\n"
6971                "}\n"
6972                "template <class T> T *f(T &c);\n", // No break here.
6973                Style);
6974   verifyFormat("int\n"
6975                "foo(A<bool> a)\n"
6976                "{\n"
6977                "  return a;\n"
6978                "}\n",
6979                Style);
6980   verifyFormat("int\n"
6981                "foo(A<8> a)\n"
6982                "{\n"
6983                "  return a;\n"
6984                "}\n",
6985                Style);
6986   verifyFormat("int\n"
6987                "foo(A<B<bool>, 8> a)\n"
6988                "{\n"
6989                "  return a;\n"
6990                "}\n",
6991                Style);
6992   verifyFormat("int\n"
6993                "foo(A<B<8>, bool> a)\n"
6994                "{\n"
6995                "  return a;\n"
6996                "}\n",
6997                Style);
6998   verifyFormat("int\n"
6999                "foo(A<B<bool>, bool> a)\n"
7000                "{\n"
7001                "  return a;\n"
7002                "}\n",
7003                Style);
7004   verifyFormat("int\n"
7005                "foo(A<B<8>, 8> a)\n"
7006                "{\n"
7007                "  return a;\n"
7008                "}\n",
7009                Style);
7010 
7011   Style = getGNUStyle();
7012 
7013   // Test for comments at the end of function declarations.
7014   verifyFormat("void\n"
7015                "foo (int a, /*abc*/ int b) // def\n"
7016                "{\n"
7017                "}\n",
7018                Style);
7019 
7020   verifyFormat("void\n"
7021                "foo (int a, /* abc */ int b) /* def */\n"
7022                "{\n"
7023                "}\n",
7024                Style);
7025 
7026   // Definitions that should not break after return type
7027   verifyFormat("void foo (int a, int b); // def\n", Style);
7028   verifyFormat("void foo (int a, int b); /* def */\n", Style);
7029   verifyFormat("void foo (int a, int b);\n", Style);
7030 }
7031 
7032 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
7033   FormatStyle NoBreak = getLLVMStyle();
7034   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
7035   FormatStyle Break = getLLVMStyle();
7036   Break.AlwaysBreakBeforeMultilineStrings = true;
7037   verifyFormat("aaaa = \"bbbb\"\n"
7038                "       \"cccc\";",
7039                NoBreak);
7040   verifyFormat("aaaa =\n"
7041                "    \"bbbb\"\n"
7042                "    \"cccc\";",
7043                Break);
7044   verifyFormat("aaaa(\"bbbb\"\n"
7045                "     \"cccc\");",
7046                NoBreak);
7047   verifyFormat("aaaa(\n"
7048                "    \"bbbb\"\n"
7049                "    \"cccc\");",
7050                Break);
7051   verifyFormat("aaaa(qqq, \"bbbb\"\n"
7052                "          \"cccc\");",
7053                NoBreak);
7054   verifyFormat("aaaa(qqq,\n"
7055                "     \"bbbb\"\n"
7056                "     \"cccc\");",
7057                Break);
7058   verifyFormat("aaaa(qqq,\n"
7059                "     L\"bbbb\"\n"
7060                "     L\"cccc\");",
7061                Break);
7062   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
7063                "                      \"bbbb\"));",
7064                Break);
7065   verifyFormat("string s = someFunction(\n"
7066                "    \"abc\"\n"
7067                "    \"abc\");",
7068                Break);
7069 
7070   // As we break before unary operators, breaking right after them is bad.
7071   verifyFormat("string foo = abc ? \"x\"\n"
7072                "                   \"blah blah blah blah blah blah\"\n"
7073                "                 : \"y\";",
7074                Break);
7075 
7076   // Don't break if there is no column gain.
7077   verifyFormat("f(\"aaaa\"\n"
7078                "  \"bbbb\");",
7079                Break);
7080 
7081   // Treat literals with escaped newlines like multi-line string literals.
7082   EXPECT_EQ("x = \"a\\\n"
7083             "b\\\n"
7084             "c\";",
7085             format("x = \"a\\\n"
7086                    "b\\\n"
7087                    "c\";",
7088                    NoBreak));
7089   EXPECT_EQ("xxxx =\n"
7090             "    \"a\\\n"
7091             "b\\\n"
7092             "c\";",
7093             format("xxxx = \"a\\\n"
7094                    "b\\\n"
7095                    "c\";",
7096                    Break));
7097 
7098   EXPECT_EQ("NSString *const kString =\n"
7099             "    @\"aaaa\"\n"
7100             "    @\"bbbb\";",
7101             format("NSString *const kString = @\"aaaa\"\n"
7102                    "@\"bbbb\";",
7103                    Break));
7104 
7105   Break.ColumnLimit = 0;
7106   verifyFormat("const char *hello = \"hello llvm\";", Break);
7107 }
7108 
7109 TEST_F(FormatTest, AlignsPipes) {
7110   verifyFormat(
7111       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7112       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7113       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7114   verifyFormat(
7115       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
7116       "                     << aaaaaaaaaaaaaaaaaaaa;");
7117   verifyFormat(
7118       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7119       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7120   verifyFormat(
7121       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7122       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7123   verifyFormat(
7124       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
7125       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
7126       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
7127   verifyFormat(
7128       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7129       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7130       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7131   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7132                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7133                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7134                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7135   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
7136                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
7137   verifyFormat(
7138       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7139       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7140   verifyFormat(
7141       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
7142       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
7143 
7144   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
7145                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
7146   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7147                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7148                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
7149                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
7150   verifyFormat("LOG_IF(aaa == //\n"
7151                "       bbb)\n"
7152                "    << a << b;");
7153 
7154   // But sometimes, breaking before the first "<<" is desirable.
7155   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7156                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
7157   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
7158                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7159                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7160   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
7161                "    << BEF << IsTemplate << Description << E->getType();");
7162   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7163                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7164                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7165   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7166                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7167                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7168                "    << aaa;");
7169 
7170   verifyFormat(
7171       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7172       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7173 
7174   // Incomplete string literal.
7175   EXPECT_EQ("llvm::errs() << \"\n"
7176             "             << a;",
7177             format("llvm::errs() << \"\n<<a;"));
7178 
7179   verifyFormat("void f() {\n"
7180                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
7181                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
7182                "}");
7183 
7184   // Handle 'endl'.
7185   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
7186                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
7187   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
7188 
7189   // Handle '\n'.
7190   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
7191                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
7192   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
7193                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
7194   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
7195                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
7196   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
7197 }
7198 
7199 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
7200   verifyFormat("return out << \"somepacket = {\\n\"\n"
7201                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
7202                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
7203                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
7204                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
7205                "           << \"}\";");
7206 
7207   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
7208                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
7209                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
7210   verifyFormat(
7211       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
7212       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
7213       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
7214       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
7215       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
7216   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
7217                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7218   verifyFormat(
7219       "void f() {\n"
7220       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
7221       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7222       "}");
7223 
7224   // Breaking before the first "<<" is generally not desirable.
7225   verifyFormat(
7226       "llvm::errs()\n"
7227       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7228       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7229       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7230       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7231       getLLVMStyleWithColumns(70));
7232   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7233                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7234                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7235                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7236                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7237                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7238                getLLVMStyleWithColumns(70));
7239 
7240   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
7241                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
7242                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
7243   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
7244                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
7245                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
7246   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
7247                "           (aaaa + aaaa);",
7248                getLLVMStyleWithColumns(40));
7249   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
7250                "                  (aaaaaaa + aaaaa));",
7251                getLLVMStyleWithColumns(40));
7252   verifyFormat(
7253       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
7254       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
7255       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
7256 }
7257 
7258 TEST_F(FormatTest, UnderstandsEquals) {
7259   verifyFormat(
7260       "aaaaaaaaaaaaaaaaa =\n"
7261       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7262   verifyFormat(
7263       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7264       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
7265   verifyFormat(
7266       "if (a) {\n"
7267       "  f();\n"
7268       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7269       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
7270       "}");
7271 
7272   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7273                "        100000000 + 10000000) {\n}");
7274 }
7275 
7276 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
7277   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
7278                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
7279 
7280   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
7281                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
7282 
7283   verifyFormat(
7284       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
7285       "                                                          Parameter2);");
7286 
7287   verifyFormat(
7288       "ShortObject->shortFunction(\n"
7289       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
7290       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
7291 
7292   verifyFormat("loooooooooooooongFunction(\n"
7293                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
7294 
7295   verifyFormat(
7296       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
7297       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
7298 
7299   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
7300                "    .WillRepeatedly(Return(SomeValue));");
7301   verifyFormat("void f() {\n"
7302                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
7303                "      .Times(2)\n"
7304                "      .WillRepeatedly(Return(SomeValue));\n"
7305                "}");
7306   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
7307                "    ccccccccccccccccccccccc);");
7308   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7309                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7310                "          .aaaaa(aaaaa),\n"
7311                "      aaaaaaaaaaaaaaaaaaaaa);");
7312   verifyFormat("void f() {\n"
7313                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7314                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
7315                "}");
7316   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7317                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7318                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7319                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7320                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7321   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7322                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7323                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7324                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
7325                "}");
7326 
7327   // Here, it is not necessary to wrap at "." or "->".
7328   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
7329                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
7330   verifyFormat(
7331       "aaaaaaaaaaa->aaaaaaaaa(\n"
7332       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7333       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
7334 
7335   verifyFormat(
7336       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7337       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
7338   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
7339                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
7340   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
7341                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
7342 
7343   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7344                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7345                "    .a();");
7346 
7347   FormatStyle NoBinPacking = getLLVMStyle();
7348   NoBinPacking.BinPackParameters = false;
7349   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7350                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7351                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
7352                "                         aaaaaaaaaaaaaaaaaaa,\n"
7353                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7354                NoBinPacking);
7355 
7356   // If there is a subsequent call, change to hanging indentation.
7357   verifyFormat(
7358       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7359       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
7360       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7361   verifyFormat(
7362       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7363       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
7364   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7365                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7366                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7367   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7368                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7369                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
7370 }
7371 
7372 TEST_F(FormatTest, WrapsTemplateDeclarations) {
7373   verifyFormat("template <typename T>\n"
7374                "virtual void loooooooooooongFunction(int Param1, int Param2);");
7375   verifyFormat("template <typename T>\n"
7376                "// T should be one of {A, B}.\n"
7377                "virtual void loooooooooooongFunction(int Param1, int Param2);");
7378   verifyFormat(
7379       "template <typename T>\n"
7380       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
7381   verifyFormat("template <typename T>\n"
7382                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
7383                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
7384   verifyFormat(
7385       "template <typename T>\n"
7386       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
7387       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
7388   verifyFormat(
7389       "template <typename T>\n"
7390       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
7391       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
7392       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7393   verifyFormat("template <typename T>\n"
7394                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7395                "    int aaaaaaaaaaaaaaaaaaaaaa);");
7396   verifyFormat(
7397       "template <typename T1, typename T2 = char, typename T3 = char,\n"
7398       "          typename T4 = char>\n"
7399       "void f();");
7400   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
7401                "          template <typename> class cccccccccccccccccccccc,\n"
7402                "          typename ddddddddddddd>\n"
7403                "class C {};");
7404   verifyFormat(
7405       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
7406       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7407 
7408   verifyFormat("void f() {\n"
7409                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
7410                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
7411                "}");
7412 
7413   verifyFormat("template <typename T> class C {};");
7414   verifyFormat("template <typename T> void f();");
7415   verifyFormat("template <typename T> void f() {}");
7416   verifyFormat(
7417       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
7418       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7419       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
7420       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
7421       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7422       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
7423       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
7424       getLLVMStyleWithColumns(72));
7425   EXPECT_EQ("static_cast<A< //\n"
7426             "    B> *>(\n"
7427             "\n"
7428             ");",
7429             format("static_cast<A<//\n"
7430                    "    B>*>(\n"
7431                    "\n"
7432                    "    );"));
7433   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7434                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
7435 
7436   FormatStyle AlwaysBreak = getLLVMStyle();
7437   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7438   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
7439   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
7440   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
7441   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7442                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
7443                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
7444   verifyFormat("template <template <typename> class Fooooooo,\n"
7445                "          template <typename> class Baaaaaaar>\n"
7446                "struct C {};",
7447                AlwaysBreak);
7448   verifyFormat("template <typename T> // T can be A, B or C.\n"
7449                "struct C {};",
7450                AlwaysBreak);
7451   verifyFormat("template <enum E> class A {\n"
7452                "public:\n"
7453                "  E *f();\n"
7454                "};");
7455 
7456   FormatStyle NeverBreak = getLLVMStyle();
7457   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
7458   verifyFormat("template <typename T> class C {};", NeverBreak);
7459   verifyFormat("template <typename T> void f();", NeverBreak);
7460   verifyFormat("template <typename T> void f() {}", NeverBreak);
7461   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
7462                "bbbbbbbbbbbbbbbbbbbb) {}",
7463                NeverBreak);
7464   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7465                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
7466                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
7467                NeverBreak);
7468   verifyFormat("template <template <typename> class Fooooooo,\n"
7469                "          template <typename> class Baaaaaaar>\n"
7470                "struct C {};",
7471                NeverBreak);
7472   verifyFormat("template <typename T> // T can be A, B or C.\n"
7473                "struct C {};",
7474                NeverBreak);
7475   verifyFormat("template <enum E> class A {\n"
7476                "public:\n"
7477                "  E *f();\n"
7478                "};",
7479                NeverBreak);
7480   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
7481   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
7482                "bbbbbbbbbbbbbbbbbbbb) {}",
7483                NeverBreak);
7484 }
7485 
7486 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
7487   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
7488   Style.ColumnLimit = 60;
7489   EXPECT_EQ("// Baseline - no comments.\n"
7490             "template <\n"
7491             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
7492             "void f() {}",
7493             format("// Baseline - no comments.\n"
7494                    "template <\n"
7495                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
7496                    "void f() {}",
7497                    Style));
7498 
7499   EXPECT_EQ("template <\n"
7500             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
7501             "void f() {}",
7502             format("template <\n"
7503                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7504                    "void f() {}",
7505                    Style));
7506 
7507   EXPECT_EQ(
7508       "template <\n"
7509       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
7510       "void f() {}",
7511       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
7512              "void f() {}",
7513              Style));
7514 
7515   EXPECT_EQ(
7516       "template <\n"
7517       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
7518       "                                               // multiline\n"
7519       "void f() {}",
7520       format("template <\n"
7521              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7522              "                                              // multiline\n"
7523              "void f() {}",
7524              Style));
7525 
7526   EXPECT_EQ(
7527       "template <typename aaaaaaaaaa<\n"
7528       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
7529       "void f() {}",
7530       format(
7531           "template <\n"
7532           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
7533           "void f() {}",
7534           Style));
7535 }
7536 
7537 TEST_F(FormatTest, WrapsTemplateParameters) {
7538   FormatStyle Style = getLLVMStyle();
7539   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7540   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
7541   verifyFormat(
7542       "template <typename... a> struct q {};\n"
7543       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
7544       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
7545       "    y;",
7546       Style);
7547   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7548   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
7549   verifyFormat(
7550       "template <typename... a> struct r {};\n"
7551       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
7552       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
7553       "    y;",
7554       Style);
7555   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7556   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
7557   verifyFormat("template <typename... a> struct s {};\n"
7558                "extern s<\n"
7559                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7560                "aaaaaaaaaaaaaaaaaaaaaa,\n"
7561                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7562                "aaaaaaaaaaaaaaaaaaaaaa>\n"
7563                "    y;",
7564                Style);
7565   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7566   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
7567   verifyFormat("template <typename... a> struct t {};\n"
7568                "extern t<\n"
7569                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7570                "aaaaaaaaaaaaaaaaaaaaaa,\n"
7571                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7572                "aaaaaaaaaaaaaaaaaaaaaa>\n"
7573                "    y;",
7574                Style);
7575 }
7576 
7577 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
7578   verifyFormat(
7579       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7580       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7581   verifyFormat(
7582       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7583       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7584       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
7585 
7586   // FIXME: Should we have the extra indent after the second break?
7587   verifyFormat(
7588       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7589       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7590       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7591 
7592   verifyFormat(
7593       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
7594       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
7595 
7596   // Breaking at nested name specifiers is generally not desirable.
7597   verifyFormat(
7598       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7599       "    aaaaaaaaaaaaaaaaaaaaaaa);");
7600 
7601   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
7602                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7603                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7604                "                   aaaaaaaaaaaaaaaaaaaaa);",
7605                getLLVMStyleWithColumns(74));
7606 
7607   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7608                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7609                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7610 }
7611 
7612 TEST_F(FormatTest, UnderstandsTemplateParameters) {
7613   verifyFormat("A<int> a;");
7614   verifyFormat("A<A<A<int>>> a;");
7615   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
7616   verifyFormat("bool x = a < 1 || 2 > a;");
7617   verifyFormat("bool x = 5 < f<int>();");
7618   verifyFormat("bool x = f<int>() > 5;");
7619   verifyFormat("bool x = 5 < a<int>::x;");
7620   verifyFormat("bool x = a < 4 ? a > 2 : false;");
7621   verifyFormat("bool x = f() ? a < 2 : a > 2;");
7622 
7623   verifyGoogleFormat("A<A<int>> a;");
7624   verifyGoogleFormat("A<A<A<int>>> a;");
7625   verifyGoogleFormat("A<A<A<A<int>>>> a;");
7626   verifyGoogleFormat("A<A<int> > a;");
7627   verifyGoogleFormat("A<A<A<int> > > a;");
7628   verifyGoogleFormat("A<A<A<A<int> > > > a;");
7629   verifyGoogleFormat("A<::A<int>> a;");
7630   verifyGoogleFormat("A<::A> a;");
7631   verifyGoogleFormat("A< ::A> a;");
7632   verifyGoogleFormat("A< ::A<int> > a;");
7633   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
7634   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
7635   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
7636   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
7637   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
7638             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
7639 
7640   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
7641 
7642   // template closer followed by a token that starts with > or =
7643   verifyFormat("bool b = a<1> > 1;");
7644   verifyFormat("bool b = a<1> >= 1;");
7645   verifyFormat("int i = a<1> >> 1;");
7646   FormatStyle Style = getLLVMStyle();
7647   Style.SpaceBeforeAssignmentOperators = false;
7648   verifyFormat("bool b= a<1> == 1;", Style);
7649   verifyFormat("a<int> = 1;", Style);
7650   verifyFormat("a<int> >>= 1;", Style);
7651 
7652   verifyFormat("test >> a >> b;");
7653   verifyFormat("test << a >> b;");
7654 
7655   verifyFormat("f<int>();");
7656   verifyFormat("template <typename T> void f() {}");
7657   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
7658   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
7659                "sizeof(char)>::type>;");
7660   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
7661   verifyFormat("f(a.operator()<A>());");
7662   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7663                "      .template operator()<A>());",
7664                getLLVMStyleWithColumns(35));
7665 
7666   // Not template parameters.
7667   verifyFormat("return a < b && c > d;");
7668   verifyFormat("void f() {\n"
7669                "  while (a < b && c > d) {\n"
7670                "  }\n"
7671                "}");
7672   verifyFormat("template <typename... Types>\n"
7673                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
7674 
7675   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7676                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
7677                getLLVMStyleWithColumns(60));
7678   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
7679   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
7680   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
7681   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
7682 }
7683 
7684 TEST_F(FormatTest, UnderstandsShiftOperators) {
7685   verifyFormat("if (i < x >> 1)");
7686   verifyFormat("while (i < x >> 1)");
7687   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
7688   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
7689   verifyFormat(
7690       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
7691   verifyFormat("Foo.call<Bar<Function>>()");
7692   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
7693   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
7694                "++i, v = v >> 1)");
7695   verifyFormat("if (w<u<v<x>>, 1>::t)");
7696 }
7697 
7698 TEST_F(FormatTest, BitshiftOperatorWidth) {
7699   EXPECT_EQ("int a = 1 << 2; /* foo\n"
7700             "                   bar */",
7701             format("int    a=1<<2;  /* foo\n"
7702                    "                   bar */"));
7703 
7704   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
7705             "                     bar */",
7706             format("int  b  =256>>1 ;  /* foo\n"
7707                    "                      bar */"));
7708 }
7709 
7710 TEST_F(FormatTest, UnderstandsBinaryOperators) {
7711   verifyFormat("COMPARE(a, ==, b);");
7712   verifyFormat("auto s = sizeof...(Ts) - 1;");
7713 }
7714 
7715 TEST_F(FormatTest, UnderstandsPointersToMembers) {
7716   verifyFormat("int A::*x;");
7717   verifyFormat("int (S::*func)(void *);");
7718   verifyFormat("void f() { int (S::*func)(void *); }");
7719   verifyFormat("typedef bool *(Class::*Member)() const;");
7720   verifyFormat("void f() {\n"
7721                "  (a->*f)();\n"
7722                "  a->*x;\n"
7723                "  (a.*f)();\n"
7724                "  ((*a).*f)();\n"
7725                "  a.*x;\n"
7726                "}");
7727   verifyFormat("void f() {\n"
7728                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
7729                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
7730                "}");
7731   verifyFormat(
7732       "(aaaaaaaaaa->*bbbbbbb)(\n"
7733       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7734   FormatStyle Style = getLLVMStyle();
7735   Style.PointerAlignment = FormatStyle::PAS_Left;
7736   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
7737 }
7738 
7739 TEST_F(FormatTest, UnderstandsUnaryOperators) {
7740   verifyFormat("int a = -2;");
7741   verifyFormat("f(-1, -2, -3);");
7742   verifyFormat("a[-1] = 5;");
7743   verifyFormat("int a = 5 + -2;");
7744   verifyFormat("if (i == -1) {\n}");
7745   verifyFormat("if (i != -1) {\n}");
7746   verifyFormat("if (i > -1) {\n}");
7747   verifyFormat("if (i < -1) {\n}");
7748   verifyFormat("++(a->f());");
7749   verifyFormat("--(a->f());");
7750   verifyFormat("(a->f())++;");
7751   verifyFormat("a[42]++;");
7752   verifyFormat("if (!(a->f())) {\n}");
7753   verifyFormat("if (!+i) {\n}");
7754   verifyFormat("~&a;");
7755 
7756   verifyFormat("a-- > b;");
7757   verifyFormat("b ? -a : c;");
7758   verifyFormat("n * sizeof char16;");
7759   verifyFormat("n * alignof char16;", getGoogleStyle());
7760   verifyFormat("sizeof(char);");
7761   verifyFormat("alignof(char);", getGoogleStyle());
7762 
7763   verifyFormat("return -1;");
7764   verifyFormat("throw -1;");
7765   verifyFormat("switch (a) {\n"
7766                "case -1:\n"
7767                "  break;\n"
7768                "}");
7769   verifyFormat("#define X -1");
7770   verifyFormat("#define X -kConstant");
7771 
7772   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
7773   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
7774 
7775   verifyFormat("int a = /* confusing comment */ -1;");
7776   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
7777   verifyFormat("int a = i /* confusing comment */++;");
7778 
7779   verifyFormat("co_yield -1;");
7780   verifyFormat("co_return -1;");
7781 
7782   // Check that * is not treated as a binary operator when we set
7783   // PointerAlignment as PAS_Left after a keyword and not a declaration.
7784   FormatStyle PASLeftStyle = getLLVMStyle();
7785   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
7786   verifyFormat("co_return *a;", PASLeftStyle);
7787   verifyFormat("co_await *a;", PASLeftStyle);
7788   verifyFormat("co_yield *a", PASLeftStyle);
7789   verifyFormat("return *a;", PASLeftStyle);
7790 }
7791 
7792 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
7793   verifyFormat("if (!aaaaaaaaaa( // break\n"
7794                "        aaaaa)) {\n"
7795                "}");
7796   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
7797                "    aaaaa));");
7798   verifyFormat("*aaa = aaaaaaa( // break\n"
7799                "    bbbbbb);");
7800 }
7801 
7802 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
7803   verifyFormat("bool operator<();");
7804   verifyFormat("bool operator>();");
7805   verifyFormat("bool operator=();");
7806   verifyFormat("bool operator==();");
7807   verifyFormat("bool operator!=();");
7808   verifyFormat("int operator+();");
7809   verifyFormat("int operator++();");
7810   verifyFormat("int operator++(int) volatile noexcept;");
7811   verifyFormat("bool operator,();");
7812   verifyFormat("bool operator();");
7813   verifyFormat("bool operator()();");
7814   verifyFormat("bool operator[]();");
7815   verifyFormat("operator bool();");
7816   verifyFormat("operator int();");
7817   verifyFormat("operator void *();");
7818   verifyFormat("operator SomeType<int>();");
7819   verifyFormat("operator SomeType<int, int>();");
7820   verifyFormat("operator SomeType<SomeType<int>>();");
7821   verifyFormat("void *operator new(std::size_t size);");
7822   verifyFormat("void *operator new[](std::size_t size);");
7823   verifyFormat("void operator delete(void *ptr);");
7824   verifyFormat("void operator delete[](void *ptr);");
7825   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
7826                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
7827   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
7828                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
7829 
7830   verifyFormat(
7831       "ostream &operator<<(ostream &OutputStream,\n"
7832       "                    SomeReallyLongType WithSomeReallyLongValue);");
7833   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
7834                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
7835                "  return left.group < right.group;\n"
7836                "}");
7837   verifyFormat("SomeType &operator=(const SomeType &S);");
7838   verifyFormat("f.template operator()<int>();");
7839 
7840   verifyGoogleFormat("operator void*();");
7841   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
7842   verifyGoogleFormat("operator ::A();");
7843 
7844   verifyFormat("using A::operator+;");
7845   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
7846                "int i;");
7847 }
7848 
7849 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
7850   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
7851   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
7852   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
7853   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
7854   verifyFormat("Deleted &operator=(const Deleted &) &;");
7855   verifyFormat("Deleted &operator=(const Deleted &) &&;");
7856   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
7857   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
7858   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
7859   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
7860   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
7861   verifyFormat("void Fn(T const &) const &;");
7862   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
7863   verifyFormat("template <typename T>\n"
7864                "void F(T) && = delete;",
7865                getGoogleStyle());
7866 
7867   FormatStyle AlignLeft = getLLVMStyle();
7868   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
7869   verifyFormat("void A::b() && {}", AlignLeft);
7870   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
7871   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
7872                AlignLeft);
7873   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
7874   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
7875   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
7876   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
7877   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
7878   verifyFormat("auto Function(T) & -> void;", AlignLeft);
7879   verifyFormat("void Fn(T const&) const&;", AlignLeft);
7880   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
7881 
7882   FormatStyle Spaces = getLLVMStyle();
7883   Spaces.SpacesInCStyleCastParentheses = true;
7884   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
7885   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
7886   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
7887   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
7888 
7889   Spaces.SpacesInCStyleCastParentheses = false;
7890   Spaces.SpacesInParentheses = true;
7891   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
7892   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
7893                Spaces);
7894   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
7895   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
7896 
7897   FormatStyle BreakTemplate = getLLVMStyle();
7898   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7899 
7900   verifyFormat("struct f {\n"
7901                "  template <class T>\n"
7902                "  int &foo(const std::string &str) &noexcept {}\n"
7903                "};",
7904                BreakTemplate);
7905 
7906   verifyFormat("struct f {\n"
7907                "  template <class T>\n"
7908                "  int &foo(const std::string &str) &&noexcept {}\n"
7909                "};",
7910                BreakTemplate);
7911 
7912   verifyFormat("struct f {\n"
7913                "  template <class T>\n"
7914                "  int &foo(const std::string &str) const &noexcept {}\n"
7915                "};",
7916                BreakTemplate);
7917 
7918   verifyFormat("struct f {\n"
7919                "  template <class T>\n"
7920                "  int &foo(const std::string &str) const &noexcept {}\n"
7921                "};",
7922                BreakTemplate);
7923 
7924   verifyFormat("struct f {\n"
7925                "  template <class T>\n"
7926                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
7927                "};",
7928                BreakTemplate);
7929 
7930   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
7931   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
7932       FormatStyle::BTDS_Yes;
7933   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
7934 
7935   verifyFormat("struct f {\n"
7936                "  template <class T>\n"
7937                "  int& foo(const std::string& str) & noexcept {}\n"
7938                "};",
7939                AlignLeftBreakTemplate);
7940 
7941   verifyFormat("struct f {\n"
7942                "  template <class T>\n"
7943                "  int& foo(const std::string& str) && noexcept {}\n"
7944                "};",
7945                AlignLeftBreakTemplate);
7946 
7947   verifyFormat("struct f {\n"
7948                "  template <class T>\n"
7949                "  int& foo(const std::string& str) const& noexcept {}\n"
7950                "};",
7951                AlignLeftBreakTemplate);
7952 
7953   verifyFormat("struct f {\n"
7954                "  template <class T>\n"
7955                "  int& foo(const std::string& str) const&& noexcept {}\n"
7956                "};",
7957                AlignLeftBreakTemplate);
7958 
7959   verifyFormat("struct f {\n"
7960                "  template <class T>\n"
7961                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
7962                "};",
7963                AlignLeftBreakTemplate);
7964 
7965   // The `&` in `Type&` should not be confused with a trailing `&` of
7966   // DEPRECATED(reason) member function.
7967   verifyFormat("struct f {\n"
7968                "  template <class T>\n"
7969                "  DEPRECATED(reason)\n"
7970                "  Type &foo(arguments) {}\n"
7971                "};",
7972                BreakTemplate);
7973 
7974   verifyFormat("struct f {\n"
7975                "  template <class T>\n"
7976                "  DEPRECATED(reason)\n"
7977                "  Type& foo(arguments) {}\n"
7978                "};",
7979                AlignLeftBreakTemplate);
7980 
7981   verifyFormat("void (*foopt)(int) = &func;");
7982 }
7983 
7984 TEST_F(FormatTest, UnderstandsNewAndDelete) {
7985   verifyFormat("void f() {\n"
7986                "  A *a = new A;\n"
7987                "  A *a = new (placement) A;\n"
7988                "  delete a;\n"
7989                "  delete (A *)a;\n"
7990                "}");
7991   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
7992                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
7993   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7994                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
7995                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
7996   verifyFormat("delete[] h->p;");
7997 }
7998 
7999 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
8000   verifyFormat("int *f(int *a) {}");
8001   verifyFormat("int main(int argc, char **argv) {}");
8002   verifyFormat("Test::Test(int b) : a(b * b) {}");
8003   verifyIndependentOfContext("f(a, *a);");
8004   verifyFormat("void g() { f(*a); }");
8005   verifyIndependentOfContext("int a = b * 10;");
8006   verifyIndependentOfContext("int a = 10 * b;");
8007   verifyIndependentOfContext("int a = b * c;");
8008   verifyIndependentOfContext("int a += b * c;");
8009   verifyIndependentOfContext("int a -= b * c;");
8010   verifyIndependentOfContext("int a *= b * c;");
8011   verifyIndependentOfContext("int a /= b * c;");
8012   verifyIndependentOfContext("int a = *b;");
8013   verifyIndependentOfContext("int a = *b * c;");
8014   verifyIndependentOfContext("int a = b * *c;");
8015   verifyIndependentOfContext("int a = b * (10);");
8016   verifyIndependentOfContext("S << b * (10);");
8017   verifyIndependentOfContext("return 10 * b;");
8018   verifyIndependentOfContext("return *b * *c;");
8019   verifyIndependentOfContext("return a & ~b;");
8020   verifyIndependentOfContext("f(b ? *c : *d);");
8021   verifyIndependentOfContext("int a = b ? *c : *d;");
8022   verifyIndependentOfContext("*b = a;");
8023   verifyIndependentOfContext("a * ~b;");
8024   verifyIndependentOfContext("a * !b;");
8025   verifyIndependentOfContext("a * +b;");
8026   verifyIndependentOfContext("a * -b;");
8027   verifyIndependentOfContext("a * ++b;");
8028   verifyIndependentOfContext("a * --b;");
8029   verifyIndependentOfContext("a[4] * b;");
8030   verifyIndependentOfContext("a[a * a] = 1;");
8031   verifyIndependentOfContext("f() * b;");
8032   verifyIndependentOfContext("a * [self dostuff];");
8033   verifyIndependentOfContext("int x = a * (a + b);");
8034   verifyIndependentOfContext("(a *)(a + b);");
8035   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
8036   verifyIndependentOfContext("int *pa = (int *)&a;");
8037   verifyIndependentOfContext("return sizeof(int **);");
8038   verifyIndependentOfContext("return sizeof(int ******);");
8039   verifyIndependentOfContext("return (int **&)a;");
8040   verifyIndependentOfContext("f((*PointerToArray)[10]);");
8041   verifyFormat("void f(Type (*parameter)[10]) {}");
8042   verifyFormat("void f(Type (&parameter)[10]) {}");
8043   verifyGoogleFormat("return sizeof(int**);");
8044   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
8045   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
8046   verifyFormat("auto a = [](int **&, int ***) {};");
8047   verifyFormat("auto PointerBinding = [](const char *S) {};");
8048   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
8049   verifyFormat("[](const decltype(*a) &value) {}");
8050   verifyFormat("[](const typeof(*a) &value) {}");
8051   verifyFormat("[](const _Atomic(a *) &value) {}");
8052   verifyFormat("[](const __underlying_type(a) &value) {}");
8053   verifyFormat("decltype(a * b) F();");
8054   verifyFormat("typeof(a * b) F();");
8055   verifyFormat("#define MACRO() [](A *a) { return 1; }");
8056   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
8057   verifyIndependentOfContext("typedef void (*f)(int *a);");
8058   verifyIndependentOfContext("int i{a * b};");
8059   verifyIndependentOfContext("aaa && aaa->f();");
8060   verifyIndependentOfContext("int x = ~*p;");
8061   verifyFormat("Constructor() : a(a), area(width * height) {}");
8062   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
8063   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
8064   verifyFormat("void f() { f(a, c * d); }");
8065   verifyFormat("void f() { f(new a(), c * d); }");
8066   verifyFormat("void f(const MyOverride &override);");
8067   verifyFormat("void f(const MyFinal &final);");
8068   verifyIndependentOfContext("bool a = f() && override.f();");
8069   verifyIndependentOfContext("bool a = f() && final.f();");
8070 
8071   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
8072 
8073   verifyIndependentOfContext("A<int *> a;");
8074   verifyIndependentOfContext("A<int **> a;");
8075   verifyIndependentOfContext("A<int *, int *> a;");
8076   verifyIndependentOfContext("A<int *[]> a;");
8077   verifyIndependentOfContext(
8078       "const char *const p = reinterpret_cast<const char *const>(q);");
8079   verifyIndependentOfContext("A<int **, int **> a;");
8080   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
8081   verifyFormat("for (char **a = b; *a; ++a) {\n}");
8082   verifyFormat("for (; a && b;) {\n}");
8083   verifyFormat("bool foo = true && [] { return false; }();");
8084 
8085   verifyFormat(
8086       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8087       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8088 
8089   verifyGoogleFormat("int const* a = &b;");
8090   verifyGoogleFormat("**outparam = 1;");
8091   verifyGoogleFormat("*outparam = a * b;");
8092   verifyGoogleFormat("int main(int argc, char** argv) {}");
8093   verifyGoogleFormat("A<int*> a;");
8094   verifyGoogleFormat("A<int**> a;");
8095   verifyGoogleFormat("A<int*, int*> a;");
8096   verifyGoogleFormat("A<int**, int**> a;");
8097   verifyGoogleFormat("f(b ? *c : *d);");
8098   verifyGoogleFormat("int a = b ? *c : *d;");
8099   verifyGoogleFormat("Type* t = **x;");
8100   verifyGoogleFormat("Type* t = *++*x;");
8101   verifyGoogleFormat("*++*x;");
8102   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
8103   verifyGoogleFormat("Type* t = x++ * y;");
8104   verifyGoogleFormat(
8105       "const char* const p = reinterpret_cast<const char* const>(q);");
8106   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
8107   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
8108   verifyGoogleFormat("template <typename T>\n"
8109                      "void f(int i = 0, SomeType** temps = NULL);");
8110 
8111   FormatStyle Left = getLLVMStyle();
8112   Left.PointerAlignment = FormatStyle::PAS_Left;
8113   verifyFormat("x = *a(x) = *a(y);", Left);
8114   verifyFormat("for (;; *a = b) {\n}", Left);
8115   verifyFormat("return *this += 1;", Left);
8116   verifyFormat("throw *x;", Left);
8117   verifyFormat("delete *x;", Left);
8118   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
8119   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
8120   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
8121   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
8122   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
8123   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
8124   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
8125   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
8126   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
8127 
8128   verifyIndependentOfContext("a = *(x + y);");
8129   verifyIndependentOfContext("a = &(x + y);");
8130   verifyIndependentOfContext("*(x + y).call();");
8131   verifyIndependentOfContext("&(x + y)->call();");
8132   verifyFormat("void f() { &(*I).first; }");
8133 
8134   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
8135   verifyFormat(
8136       "int *MyValues = {\n"
8137       "    *A, // Operator detection might be confused by the '{'\n"
8138       "    *BB // Operator detection might be confused by previous comment\n"
8139       "};");
8140 
8141   verifyIndependentOfContext("if (int *a = &b)");
8142   verifyIndependentOfContext("if (int &a = *b)");
8143   verifyIndependentOfContext("if (a & b[i])");
8144   verifyIndependentOfContext("if constexpr (a & b[i])");
8145   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
8146   verifyIndependentOfContext("if (a * (b * c))");
8147   verifyIndependentOfContext("if constexpr (a * (b * c))");
8148   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
8149   verifyIndependentOfContext("if (a::b::c::d & b[i])");
8150   verifyIndependentOfContext("if (*b[i])");
8151   verifyIndependentOfContext("if (int *a = (&b))");
8152   verifyIndependentOfContext("while (int *a = &b)");
8153   verifyIndependentOfContext("while (a * (b * c))");
8154   verifyIndependentOfContext("size = sizeof *a;");
8155   verifyIndependentOfContext("if (a && (b = c))");
8156   verifyFormat("void f() {\n"
8157                "  for (const int &v : Values) {\n"
8158                "  }\n"
8159                "}");
8160   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
8161   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
8162   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
8163 
8164   verifyFormat("#define A (!a * b)");
8165   verifyFormat("#define MACRO     \\\n"
8166                "  int *i = a * b; \\\n"
8167                "  void f(a *b);",
8168                getLLVMStyleWithColumns(19));
8169 
8170   verifyIndependentOfContext("A = new SomeType *[Length];");
8171   verifyIndependentOfContext("A = new SomeType *[Length]();");
8172   verifyIndependentOfContext("T **t = new T *;");
8173   verifyIndependentOfContext("T **t = new T *();");
8174   verifyGoogleFormat("A = new SomeType*[Length]();");
8175   verifyGoogleFormat("A = new SomeType*[Length];");
8176   verifyGoogleFormat("T** t = new T*;");
8177   verifyGoogleFormat("T** t = new T*();");
8178 
8179   verifyFormat("STATIC_ASSERT((a & b) == 0);");
8180   verifyFormat("STATIC_ASSERT(0 == (a & b));");
8181   verifyFormat("template <bool a, bool b> "
8182                "typename t::if<x && y>::type f() {}");
8183   verifyFormat("template <int *y> f() {}");
8184   verifyFormat("vector<int *> v;");
8185   verifyFormat("vector<int *const> v;");
8186   verifyFormat("vector<int *const **const *> v;");
8187   verifyFormat("vector<int *volatile> v;");
8188   verifyFormat("vector<a *_Nonnull> v;");
8189   verifyFormat("vector<a *_Nullable> v;");
8190   verifyFormat("vector<a *_Null_unspecified> v;");
8191   verifyFormat("vector<a *__ptr32> v;");
8192   verifyFormat("vector<a *__ptr64> v;");
8193   verifyFormat("vector<a *__capability> v;");
8194   FormatStyle TypeMacros = getLLVMStyle();
8195   TypeMacros.TypenameMacros = {"LIST"};
8196   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
8197   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
8198   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
8199   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
8200   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
8201 
8202   FormatStyle CustomQualifier = getLLVMStyle();
8203   // Add indentifers that should not be parsed as a qualifier by default.
8204   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
8205   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
8206   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
8207   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
8208   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
8209   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
8210   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
8211   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
8212   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
8213   verifyFormat("vector<a * _NotAQualifier> v;");
8214   verifyFormat("vector<a * __not_a_qualifier> v;");
8215   verifyFormat("vector<a * b> v;");
8216   verifyFormat("foo<b && false>();");
8217   verifyFormat("foo<b & 1>();");
8218   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
8219   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
8220   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
8221   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
8222   verifyFormat(
8223       "template <class T, class = typename std::enable_if<\n"
8224       "                       std::is_integral<T>::value &&\n"
8225       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
8226       "void F();",
8227       getLLVMStyleWithColumns(70));
8228   verifyFormat("template <class T,\n"
8229                "          class = typename std::enable_if<\n"
8230                "              std::is_integral<T>::value &&\n"
8231                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
8232                "          class U>\n"
8233                "void F();",
8234                getLLVMStyleWithColumns(70));
8235   verifyFormat(
8236       "template <class T,\n"
8237       "          class = typename ::std::enable_if<\n"
8238       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
8239       "void F();",
8240       getGoogleStyleWithColumns(68));
8241 
8242   verifyIndependentOfContext("MACRO(int *i);");
8243   verifyIndependentOfContext("MACRO(auto *a);");
8244   verifyIndependentOfContext("MACRO(const A *a);");
8245   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
8246   verifyIndependentOfContext("MACRO(decltype(A) *a);");
8247   verifyIndependentOfContext("MACRO(typeof(A) *a);");
8248   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
8249   verifyIndependentOfContext("MACRO(A *const a);");
8250   verifyIndependentOfContext("MACRO(A *restrict a);");
8251   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
8252   verifyIndependentOfContext("MACRO(A *__restrict a);");
8253   verifyIndependentOfContext("MACRO(A *volatile a);");
8254   verifyIndependentOfContext("MACRO(A *__volatile a);");
8255   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
8256   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
8257   verifyIndependentOfContext("MACRO(A *_Nullable a);");
8258   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
8259   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
8260   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
8261   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
8262   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
8263   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
8264   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
8265   verifyIndependentOfContext("MACRO(A *__capability);");
8266   verifyIndependentOfContext("MACRO(A &__capability);");
8267   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
8268   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
8269   // If we add __my_qualifier to AttributeMacros it should always be parsed as
8270   // a type declaration:
8271   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
8272   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
8273   // Also check that TypenameMacros prevents parsing it as multiplication:
8274   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
8275   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
8276 
8277   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
8278   verifyFormat("void f() { f(float{1}, a * a); }");
8279   // FIXME: Is there a way to make this work?
8280   // verifyIndependentOfContext("MACRO(A *a);");
8281   verifyFormat("MACRO(A &B);");
8282   verifyFormat("MACRO(A *B);");
8283   verifyFormat("void f() { MACRO(A * B); }");
8284   verifyFormat("void f() { MACRO(A & B); }");
8285 
8286   // This lambda was mis-formatted after D88956 (treating it as a binop):
8287   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
8288   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
8289   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
8290   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
8291 
8292   verifyFormat("DatumHandle const *operator->() const { return input_; }");
8293   verifyFormat("return options != nullptr && operator==(*options);");
8294 
8295   EXPECT_EQ("#define OP(x)                                    \\\n"
8296             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
8297             "    return s << a.DebugString();                 \\\n"
8298             "  }",
8299             format("#define OP(x) \\\n"
8300                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
8301                    "    return s << a.DebugString(); \\\n"
8302                    "  }",
8303                    getLLVMStyleWithColumns(50)));
8304 
8305   // FIXME: We cannot handle this case yet; we might be able to figure out that
8306   // foo<x> d > v; doesn't make sense.
8307   verifyFormat("foo<a<b && c> d> v;");
8308 
8309   FormatStyle PointerMiddle = getLLVMStyle();
8310   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
8311   verifyFormat("delete *x;", PointerMiddle);
8312   verifyFormat("int * x;", PointerMiddle);
8313   verifyFormat("int *[] x;", PointerMiddle);
8314   verifyFormat("template <int * y> f() {}", PointerMiddle);
8315   verifyFormat("int * f(int * a) {}", PointerMiddle);
8316   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
8317   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
8318   verifyFormat("A<int *> a;", PointerMiddle);
8319   verifyFormat("A<int **> a;", PointerMiddle);
8320   verifyFormat("A<int *, int *> a;", PointerMiddle);
8321   verifyFormat("A<int *[]> a;", PointerMiddle);
8322   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
8323   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
8324   verifyFormat("T ** t = new T *;", PointerMiddle);
8325 
8326   // Member function reference qualifiers aren't binary operators.
8327   verifyFormat("string // break\n"
8328                "operator()() & {}");
8329   verifyFormat("string // break\n"
8330                "operator()() && {}");
8331   verifyGoogleFormat("template <typename T>\n"
8332                      "auto x() & -> int {}");
8333 }
8334 
8335 TEST_F(FormatTest, UnderstandsAttributes) {
8336   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
8337   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
8338                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
8339   FormatStyle AfterType = getLLVMStyle();
8340   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8341   verifyFormat("__attribute__((nodebug)) void\n"
8342                "foo() {}\n",
8343                AfterType);
8344   verifyFormat("__unused void\n"
8345                "foo() {}",
8346                AfterType);
8347 
8348   FormatStyle CustomAttrs = getLLVMStyle();
8349   CustomAttrs.AttributeMacros.push_back("__unused");
8350   CustomAttrs.AttributeMacros.push_back("__attr1");
8351   CustomAttrs.AttributeMacros.push_back("__attr2");
8352   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
8353   verifyFormat("vector<SomeType *__attribute((foo))> v;");
8354   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
8355   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
8356   // Check that it is parsed as a multiplication without AttributeMacros and
8357   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
8358   verifyFormat("vector<SomeType * __attr1> v;");
8359   verifyFormat("vector<SomeType __attr1 *> v;");
8360   verifyFormat("vector<SomeType __attr1 *const> v;");
8361   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
8362   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
8363   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
8364   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
8365   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
8366   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
8367   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
8368   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
8369 
8370   // Check that these are not parsed as function declarations:
8371   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8372   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
8373   verifyFormat("SomeType s(InitValue);", CustomAttrs);
8374   verifyFormat("SomeType s{InitValue};", CustomAttrs);
8375   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
8376   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
8377   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
8378   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
8379   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
8380   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
8381 }
8382 
8383 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
8384   // Check that qualifiers on pointers don't break parsing of casts.
8385   verifyFormat("x = (foo *const)*v;");
8386   verifyFormat("x = (foo *volatile)*v;");
8387   verifyFormat("x = (foo *restrict)*v;");
8388   verifyFormat("x = (foo *__attribute__((foo)))*v;");
8389   verifyFormat("x = (foo *_Nonnull)*v;");
8390   verifyFormat("x = (foo *_Nullable)*v;");
8391   verifyFormat("x = (foo *_Null_unspecified)*v;");
8392   verifyFormat("x = (foo *_Nonnull)*v;");
8393   verifyFormat("x = (foo *[[clang::attr]])*v;");
8394   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
8395   verifyFormat("x = (foo *__ptr32)*v;");
8396   verifyFormat("x = (foo *__ptr64)*v;");
8397   verifyFormat("x = (foo *__capability)*v;");
8398 
8399   // Check that we handle multiple trailing qualifiers and skip them all to
8400   // determine that the expression is a cast to a pointer type.
8401   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
8402   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
8403   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
8404   StringRef AllQualifiers =
8405       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
8406       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
8407   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
8408   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
8409 
8410   // Also check that address-of is not parsed as a binary bitwise-and:
8411   verifyFormat("x = (foo *const)&v;");
8412   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
8413   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
8414 
8415   // Check custom qualifiers:
8416   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
8417   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
8418   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
8419   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
8420   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
8421                CustomQualifier);
8422   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
8423                CustomQualifier);
8424 
8425   // Check that unknown identifiers result in binary operator parsing:
8426   verifyFormat("x = (foo * __unknown_qualifier) * v;");
8427   verifyFormat("x = (foo * __unknown_qualifier) & v;");
8428 }
8429 
8430 TEST_F(FormatTest, UnderstandsSquareAttributes) {
8431   verifyFormat("SomeType s [[unused]] (InitValue);");
8432   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
8433   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
8434   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
8435   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
8436   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8437                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
8438   verifyFormat("[[nodiscard]] bool f() { return false; }");
8439   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
8440   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
8441   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
8442 
8443   // Make sure we do not mistake attributes for array subscripts.
8444   verifyFormat("int a() {}\n"
8445                "[[unused]] int b() {}\n");
8446   verifyFormat("NSArray *arr;\n"
8447                "arr[[Foo() bar]];");
8448 
8449   // On the other hand, we still need to correctly find array subscripts.
8450   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
8451 
8452   // Make sure that we do not mistake Objective-C method inside array literals
8453   // as attributes, even if those method names are also keywords.
8454   verifyFormat("@[ [foo bar] ];");
8455   verifyFormat("@[ [NSArray class] ];");
8456   verifyFormat("@[ [foo enum] ];");
8457 
8458   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
8459 
8460   // Make sure we do not parse attributes as lambda introducers.
8461   FormatStyle MultiLineFunctions = getLLVMStyle();
8462   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8463   verifyFormat("[[unused]] int b() {\n"
8464                "  return 42;\n"
8465                "}\n",
8466                MultiLineFunctions);
8467 }
8468 
8469 TEST_F(FormatTest, AttributeClass) {
8470   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
8471   verifyFormat("class S {\n"
8472                "  S(S&&) = default;\n"
8473                "};",
8474                Style);
8475   verifyFormat("class [[nodiscard]] S {\n"
8476                "  S(S&&) = default;\n"
8477                "};",
8478                Style);
8479   verifyFormat("class __attribute((maybeunused)) S {\n"
8480                "  S(S&&) = default;\n"
8481                "};",
8482                Style);
8483   verifyFormat("struct S {\n"
8484                "  S(S&&) = default;\n"
8485                "};",
8486                Style);
8487   verifyFormat("struct [[nodiscard]] S {\n"
8488                "  S(S&&) = default;\n"
8489                "};",
8490                Style);
8491 }
8492 
8493 TEST_F(FormatTest, AttributesAfterMacro) {
8494   FormatStyle Style = getLLVMStyle();
8495   verifyFormat("MACRO;\n"
8496                "__attribute__((maybe_unused)) int foo() {\n"
8497                "  //...\n"
8498                "}");
8499 
8500   verifyFormat("MACRO;\n"
8501                "[[nodiscard]] int foo() {\n"
8502                "  //...\n"
8503                "}");
8504 
8505   EXPECT_EQ("MACRO\n\n"
8506             "__attribute__((maybe_unused)) int foo() {\n"
8507             "  //...\n"
8508             "}",
8509             format("MACRO\n\n"
8510                    "__attribute__((maybe_unused)) int foo() {\n"
8511                    "  //...\n"
8512                    "}"));
8513 
8514   EXPECT_EQ("MACRO\n\n"
8515             "[[nodiscard]] int foo() {\n"
8516             "  //...\n"
8517             "}",
8518             format("MACRO\n\n"
8519                    "[[nodiscard]] int foo() {\n"
8520                    "  //...\n"
8521                    "}"));
8522 }
8523 
8524 TEST_F(FormatTest, AttributePenaltyBreaking) {
8525   FormatStyle Style = getLLVMStyle();
8526   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
8527                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
8528                Style);
8529   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
8530                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
8531                Style);
8532   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
8533                "shared_ptr<ALongTypeName> &C d) {\n}",
8534                Style);
8535 }
8536 
8537 TEST_F(FormatTest, UnderstandsEllipsis) {
8538   FormatStyle Style = getLLVMStyle();
8539   verifyFormat("int printf(const char *fmt, ...);");
8540   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
8541   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
8542 
8543   verifyFormat("template <int *...PP> a;", Style);
8544 
8545   Style.PointerAlignment = FormatStyle::PAS_Left;
8546   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
8547 
8548   verifyFormat("template <int*... PP> a;", Style);
8549 
8550   Style.PointerAlignment = FormatStyle::PAS_Middle;
8551   verifyFormat("template <int *... PP> a;", Style);
8552 }
8553 
8554 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
8555   EXPECT_EQ("int *a;\n"
8556             "int *a;\n"
8557             "int *a;",
8558             format("int *a;\n"
8559                    "int* a;\n"
8560                    "int *a;",
8561                    getGoogleStyle()));
8562   EXPECT_EQ("int* a;\n"
8563             "int* a;\n"
8564             "int* a;",
8565             format("int* a;\n"
8566                    "int* a;\n"
8567                    "int *a;",
8568                    getGoogleStyle()));
8569   EXPECT_EQ("int *a;\n"
8570             "int *a;\n"
8571             "int *a;",
8572             format("int *a;\n"
8573                    "int * a;\n"
8574                    "int *  a;",
8575                    getGoogleStyle()));
8576   EXPECT_EQ("auto x = [] {\n"
8577             "  int *a;\n"
8578             "  int *a;\n"
8579             "  int *a;\n"
8580             "};",
8581             format("auto x=[]{int *a;\n"
8582                    "int * a;\n"
8583                    "int *  a;};",
8584                    getGoogleStyle()));
8585 }
8586 
8587 TEST_F(FormatTest, UnderstandsRvalueReferences) {
8588   verifyFormat("int f(int &&a) {}");
8589   verifyFormat("int f(int a, char &&b) {}");
8590   verifyFormat("void f() { int &&a = b; }");
8591   verifyGoogleFormat("int f(int a, char&& b) {}");
8592   verifyGoogleFormat("void f() { int&& a = b; }");
8593 
8594   verifyIndependentOfContext("A<int &&> a;");
8595   verifyIndependentOfContext("A<int &&, int &&> a;");
8596   verifyGoogleFormat("A<int&&> a;");
8597   verifyGoogleFormat("A<int&&, int&&> a;");
8598 
8599   // Not rvalue references:
8600   verifyFormat("template <bool B, bool C> class A {\n"
8601                "  static_assert(B && C, \"Something is wrong\");\n"
8602                "};");
8603   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
8604   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
8605   verifyFormat("#define A(a, b) (a && b)");
8606 }
8607 
8608 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
8609   verifyFormat("void f() {\n"
8610                "  x[aaaaaaaaa -\n"
8611                "    b] = 23;\n"
8612                "}",
8613                getLLVMStyleWithColumns(15));
8614 }
8615 
8616 TEST_F(FormatTest, FormatsCasts) {
8617   verifyFormat("Type *A = static_cast<Type *>(P);");
8618   verifyFormat("Type *A = (Type *)P;");
8619   verifyFormat("Type *A = (vector<Type *, int *>)P;");
8620   verifyFormat("int a = (int)(2.0f);");
8621   verifyFormat("int a = (int)2.0f;");
8622   verifyFormat("x[(int32)y];");
8623   verifyFormat("x = (int32)y;");
8624   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
8625   verifyFormat("int a = (int)*b;");
8626   verifyFormat("int a = (int)2.0f;");
8627   verifyFormat("int a = (int)~0;");
8628   verifyFormat("int a = (int)++a;");
8629   verifyFormat("int a = (int)sizeof(int);");
8630   verifyFormat("int a = (int)+2;");
8631   verifyFormat("my_int a = (my_int)2.0f;");
8632   verifyFormat("my_int a = (my_int)sizeof(int);");
8633   verifyFormat("return (my_int)aaa;");
8634   verifyFormat("#define x ((int)-1)");
8635   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
8636   verifyFormat("#define p(q) ((int *)&q)");
8637   verifyFormat("fn(a)(b) + 1;");
8638 
8639   verifyFormat("void f() { my_int a = (my_int)*b; }");
8640   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
8641   verifyFormat("my_int a = (my_int)~0;");
8642   verifyFormat("my_int a = (my_int)++a;");
8643   verifyFormat("my_int a = (my_int)-2;");
8644   verifyFormat("my_int a = (my_int)1;");
8645   verifyFormat("my_int a = (my_int *)1;");
8646   verifyFormat("my_int a = (const my_int)-1;");
8647   verifyFormat("my_int a = (const my_int *)-1;");
8648   verifyFormat("my_int a = (my_int)(my_int)-1;");
8649   verifyFormat("my_int a = (ns::my_int)-2;");
8650   verifyFormat("case (my_int)ONE:");
8651   verifyFormat("auto x = (X)this;");
8652   // Casts in Obj-C style calls used to not be recognized as such.
8653   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
8654 
8655   // FIXME: single value wrapped with paren will be treated as cast.
8656   verifyFormat("void f(int i = (kValue)*kMask) {}");
8657 
8658   verifyFormat("{ (void)F; }");
8659 
8660   // Don't break after a cast's
8661   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8662                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
8663                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
8664 
8665   // These are not casts.
8666   verifyFormat("void f(int *) {}");
8667   verifyFormat("f(foo)->b;");
8668   verifyFormat("f(foo).b;");
8669   verifyFormat("f(foo)(b);");
8670   verifyFormat("f(foo)[b];");
8671   verifyFormat("[](foo) { return 4; }(bar);");
8672   verifyFormat("(*funptr)(foo)[4];");
8673   verifyFormat("funptrs[4](foo)[4];");
8674   verifyFormat("void f(int *);");
8675   verifyFormat("void f(int *) = 0;");
8676   verifyFormat("void f(SmallVector<int>) {}");
8677   verifyFormat("void f(SmallVector<int>);");
8678   verifyFormat("void f(SmallVector<int>) = 0;");
8679   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
8680   verifyFormat("int a = sizeof(int) * b;");
8681   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
8682   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
8683   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
8684   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
8685 
8686   // These are not casts, but at some point were confused with casts.
8687   verifyFormat("virtual void foo(int *) override;");
8688   verifyFormat("virtual void foo(char &) const;");
8689   verifyFormat("virtual void foo(int *a, char *) const;");
8690   verifyFormat("int a = sizeof(int *) + b;");
8691   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
8692   verifyFormat("bool b = f(g<int>) && c;");
8693   verifyFormat("typedef void (*f)(int i) func;");
8694   verifyFormat("void operator++(int) noexcept;");
8695   verifyFormat("void operator++(int &) noexcept;");
8696   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
8697                "&) noexcept;");
8698   verifyFormat(
8699       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
8700   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
8701   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
8702   verifyFormat("void operator delete(nothrow_t &) noexcept;");
8703   verifyFormat("void operator delete(foo &) noexcept;");
8704   verifyFormat("void operator delete(foo) noexcept;");
8705   verifyFormat("void operator delete(int) noexcept;");
8706   verifyFormat("void operator delete(int &) noexcept;");
8707   verifyFormat("void operator delete(int &) volatile noexcept;");
8708   verifyFormat("void operator delete(int &) const");
8709   verifyFormat("void operator delete(int &) = default");
8710   verifyFormat("void operator delete(int &) = delete");
8711   verifyFormat("void operator delete(int &) [[noreturn]]");
8712   verifyFormat("void operator delete(int &) throw();");
8713   verifyFormat("void operator delete(int &) throw(int);");
8714   verifyFormat("auto operator delete(int &) -> int;");
8715   verifyFormat("auto operator delete(int &) override");
8716   verifyFormat("auto operator delete(int &) final");
8717 
8718   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
8719                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8720   // FIXME: The indentation here is not ideal.
8721   verifyFormat(
8722       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8723       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
8724       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
8725 }
8726 
8727 TEST_F(FormatTest, FormatsFunctionTypes) {
8728   verifyFormat("A<bool()> a;");
8729   verifyFormat("A<SomeType()> a;");
8730   verifyFormat("A<void (*)(int, std::string)> a;");
8731   verifyFormat("A<void *(int)>;");
8732   verifyFormat("void *(*a)(int *, SomeType *);");
8733   verifyFormat("int (*func)(void *);");
8734   verifyFormat("void f() { int (*func)(void *); }");
8735   verifyFormat("template <class CallbackClass>\n"
8736                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
8737 
8738   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
8739   verifyGoogleFormat("void* (*a)(int);");
8740   verifyGoogleFormat(
8741       "template <class CallbackClass>\n"
8742       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
8743 
8744   // Other constructs can look somewhat like function types:
8745   verifyFormat("A<sizeof(*x)> a;");
8746   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
8747   verifyFormat("some_var = function(*some_pointer_var)[0];");
8748   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
8749   verifyFormat("int x = f(&h)();");
8750   verifyFormat("returnsFunction(&param1, &param2)(param);");
8751   verifyFormat("std::function<\n"
8752                "    LooooooooooongTemplatedType<\n"
8753                "        SomeType>*(\n"
8754                "        LooooooooooooooooongType type)>\n"
8755                "    function;",
8756                getGoogleStyleWithColumns(40));
8757 }
8758 
8759 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
8760   verifyFormat("A (*foo_)[6];");
8761   verifyFormat("vector<int> (*foo_)[6];");
8762 }
8763 
8764 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
8765   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8766                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
8767   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
8768                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
8769   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8770                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
8771 
8772   // Different ways of ()-initializiation.
8773   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8774                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
8775   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8776                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
8777   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8778                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
8779   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8780                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
8781 
8782   // Lambdas should not confuse the variable declaration heuristic.
8783   verifyFormat("LooooooooooooooooongType\n"
8784                "    variable(nullptr, [](A *a) {});",
8785                getLLVMStyleWithColumns(40));
8786 }
8787 
8788 TEST_F(FormatTest, BreaksLongDeclarations) {
8789   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
8790                "    AnotherNameForTheLongType;");
8791   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
8792                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8793   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8794                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
8795   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
8796                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
8797   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8798                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8799   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
8800                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8801   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
8802                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8803   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
8804                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8805   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
8806                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8807   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
8808                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8809   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
8810                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8811   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8812                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
8813   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8814                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
8815   FormatStyle Indented = getLLVMStyle();
8816   Indented.IndentWrappedFunctionNames = true;
8817   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8818                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
8819                Indented);
8820   verifyFormat(
8821       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8822       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8823       Indented);
8824   verifyFormat(
8825       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
8826       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8827       Indented);
8828   verifyFormat(
8829       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
8830       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8831       Indented);
8832 
8833   // FIXME: Without the comment, this breaks after "(".
8834   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
8835                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
8836                getGoogleStyle());
8837 
8838   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
8839                "                  int LoooooooooooooooooooongParam2) {}");
8840   verifyFormat(
8841       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
8842       "                                   SourceLocation L, IdentifierIn *II,\n"
8843       "                                   Type *T) {}");
8844   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
8845                "ReallyReaaallyLongFunctionName(\n"
8846                "    const std::string &SomeParameter,\n"
8847                "    const SomeType<string, SomeOtherTemplateParameter>\n"
8848                "        &ReallyReallyLongParameterName,\n"
8849                "    const SomeType<string, SomeOtherTemplateParameter>\n"
8850                "        &AnotherLongParameterName) {}");
8851   verifyFormat("template <typename A>\n"
8852                "SomeLoooooooooooooooooooooongType<\n"
8853                "    typename some_namespace::SomeOtherType<A>::Type>\n"
8854                "Function() {}");
8855 
8856   verifyGoogleFormat(
8857       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
8858       "    aaaaaaaaaaaaaaaaaaaaaaa;");
8859   verifyGoogleFormat(
8860       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
8861       "                                   SourceLocation L) {}");
8862   verifyGoogleFormat(
8863       "some_namespace::LongReturnType\n"
8864       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
8865       "    int first_long_parameter, int second_parameter) {}");
8866 
8867   verifyGoogleFormat("template <typename T>\n"
8868                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
8869                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
8870   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8871                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
8872 
8873   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
8874                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8875                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8876   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8877                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
8878                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
8879   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8880                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
8881                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
8882                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8883 
8884   verifyFormat("template <typename T> // Templates on own line.\n"
8885                "static int            // Some comment.\n"
8886                "MyFunction(int a);",
8887                getLLVMStyle());
8888 }
8889 
8890 TEST_F(FormatTest, FormatsAccessModifiers) {
8891   FormatStyle Style = getLLVMStyle();
8892   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
8893             FormatStyle::ELBAMS_LogicalBlock);
8894   verifyFormat("struct foo {\n"
8895                "private:\n"
8896                "  void f() {}\n"
8897                "\n"
8898                "private:\n"
8899                "  int i;\n"
8900                "\n"
8901                "protected:\n"
8902                "  int j;\n"
8903                "};\n",
8904                Style);
8905   verifyFormat("struct foo {\n"
8906                "private:\n"
8907                "  void f() {}\n"
8908                "\n"
8909                "private:\n"
8910                "  int i;\n"
8911                "\n"
8912                "protected:\n"
8913                "  int j;\n"
8914                "};\n",
8915                "struct foo {\n"
8916                "private:\n"
8917                "  void f() {}\n"
8918                "private:\n"
8919                "  int i;\n"
8920                "protected:\n"
8921                "  int j;\n"
8922                "};\n",
8923                Style);
8924   verifyFormat("struct foo { /* comment */\n"
8925                "private:\n"
8926                "  int i;\n"
8927                "  // comment\n"
8928                "private:\n"
8929                "  int j;\n"
8930                "};\n",
8931                Style);
8932   verifyFormat("struct foo {\n"
8933                "#ifdef FOO\n"
8934                "#endif\n"
8935                "private:\n"
8936                "  int i;\n"
8937                "#ifdef FOO\n"
8938                "private:\n"
8939                "#endif\n"
8940                "  int j;\n"
8941                "};\n",
8942                Style);
8943   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
8944   verifyFormat("struct foo {\n"
8945                "private:\n"
8946                "  void f() {}\n"
8947                "private:\n"
8948                "  int i;\n"
8949                "protected:\n"
8950                "  int j;\n"
8951                "};\n",
8952                Style);
8953   verifyFormat("struct foo {\n"
8954                "private:\n"
8955                "  void f() {}\n"
8956                "private:\n"
8957                "  int i;\n"
8958                "protected:\n"
8959                "  int j;\n"
8960                "};\n",
8961                "struct foo {\n"
8962                "\n"
8963                "private:\n"
8964                "  void f() {}\n"
8965                "\n"
8966                "private:\n"
8967                "  int i;\n"
8968                "\n"
8969                "protected:\n"
8970                "  int j;\n"
8971                "};\n",
8972                Style);
8973   verifyFormat("struct foo { /* comment */\n"
8974                "private:\n"
8975                "  int i;\n"
8976                "  // comment\n"
8977                "private:\n"
8978                "  int j;\n"
8979                "};\n",
8980                "struct foo { /* comment */\n"
8981                "\n"
8982                "private:\n"
8983                "  int i;\n"
8984                "  // comment\n"
8985                "\n"
8986                "private:\n"
8987                "  int j;\n"
8988                "};\n",
8989                Style);
8990   verifyFormat("struct foo {\n"
8991                "#ifdef FOO\n"
8992                "#endif\n"
8993                "private:\n"
8994                "  int i;\n"
8995                "#ifdef FOO\n"
8996                "private:\n"
8997                "#endif\n"
8998                "  int j;\n"
8999                "};\n",
9000                "struct foo {\n"
9001                "#ifdef FOO\n"
9002                "#endif\n"
9003                "\n"
9004                "private:\n"
9005                "  int i;\n"
9006                "#ifdef FOO\n"
9007                "\n"
9008                "private:\n"
9009                "#endif\n"
9010                "  int j;\n"
9011                "};\n",
9012                Style);
9013   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9014   verifyFormat("struct foo {\n"
9015                "private:\n"
9016                "  void f() {}\n"
9017                "\n"
9018                "private:\n"
9019                "  int i;\n"
9020                "\n"
9021                "protected:\n"
9022                "  int j;\n"
9023                "};\n",
9024                Style);
9025   verifyFormat("struct foo {\n"
9026                "private:\n"
9027                "  void f() {}\n"
9028                "\n"
9029                "private:\n"
9030                "  int i;\n"
9031                "\n"
9032                "protected:\n"
9033                "  int j;\n"
9034                "};\n",
9035                "struct foo {\n"
9036                "private:\n"
9037                "  void f() {}\n"
9038                "private:\n"
9039                "  int i;\n"
9040                "protected:\n"
9041                "  int j;\n"
9042                "};\n",
9043                Style);
9044   verifyFormat("struct foo { /* comment */\n"
9045                "private:\n"
9046                "  int i;\n"
9047                "  // comment\n"
9048                "\n"
9049                "private:\n"
9050                "  int j;\n"
9051                "};\n",
9052                "struct foo { /* comment */\n"
9053                "private:\n"
9054                "  int i;\n"
9055                "  // comment\n"
9056                "\n"
9057                "private:\n"
9058                "  int j;\n"
9059                "};\n",
9060                Style);
9061   verifyFormat("struct foo {\n"
9062                "#ifdef FOO\n"
9063                "#endif\n"
9064                "\n"
9065                "private:\n"
9066                "  int i;\n"
9067                "#ifdef FOO\n"
9068                "\n"
9069                "private:\n"
9070                "#endif\n"
9071                "  int j;\n"
9072                "};\n",
9073                "struct foo {\n"
9074                "#ifdef FOO\n"
9075                "#endif\n"
9076                "private:\n"
9077                "  int i;\n"
9078                "#ifdef FOO\n"
9079                "private:\n"
9080                "#endif\n"
9081                "  int j;\n"
9082                "};\n",
9083                Style);
9084   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9085   EXPECT_EQ("struct foo {\n"
9086             "\n"
9087             "private:\n"
9088             "  void f() {}\n"
9089             "\n"
9090             "private:\n"
9091             "  int i;\n"
9092             "\n"
9093             "protected:\n"
9094             "  int j;\n"
9095             "};\n",
9096             format("struct foo {\n"
9097                    "\n"
9098                    "private:\n"
9099                    "  void f() {}\n"
9100                    "\n"
9101                    "private:\n"
9102                    "  int i;\n"
9103                    "\n"
9104                    "protected:\n"
9105                    "  int j;\n"
9106                    "};\n",
9107                    Style));
9108   verifyFormat("struct foo {\n"
9109                "private:\n"
9110                "  void f() {}\n"
9111                "private:\n"
9112                "  int i;\n"
9113                "protected:\n"
9114                "  int j;\n"
9115                "};\n",
9116                Style);
9117   EXPECT_EQ("struct foo { /* comment */\n"
9118             "\n"
9119             "private:\n"
9120             "  int i;\n"
9121             "  // comment\n"
9122             "\n"
9123             "private:\n"
9124             "  int j;\n"
9125             "};\n",
9126             format("struct foo { /* comment */\n"
9127                    "\n"
9128                    "private:\n"
9129                    "  int i;\n"
9130                    "  // comment\n"
9131                    "\n"
9132                    "private:\n"
9133                    "  int j;\n"
9134                    "};\n",
9135                    Style));
9136   verifyFormat("struct foo { /* comment */\n"
9137                "private:\n"
9138                "  int i;\n"
9139                "  // comment\n"
9140                "private:\n"
9141                "  int j;\n"
9142                "};\n",
9143                Style);
9144   EXPECT_EQ("struct foo {\n"
9145             "#ifdef FOO\n"
9146             "#endif\n"
9147             "\n"
9148             "private:\n"
9149             "  int i;\n"
9150             "#ifdef FOO\n"
9151             "\n"
9152             "private:\n"
9153             "#endif\n"
9154             "  int j;\n"
9155             "};\n",
9156             format("struct foo {\n"
9157                    "#ifdef FOO\n"
9158                    "#endif\n"
9159                    "\n"
9160                    "private:\n"
9161                    "  int i;\n"
9162                    "#ifdef FOO\n"
9163                    "\n"
9164                    "private:\n"
9165                    "#endif\n"
9166                    "  int j;\n"
9167                    "};\n",
9168                    Style));
9169   verifyFormat("struct foo {\n"
9170                "#ifdef FOO\n"
9171                "#endif\n"
9172                "private:\n"
9173                "  int i;\n"
9174                "#ifdef FOO\n"
9175                "private:\n"
9176                "#endif\n"
9177                "  int j;\n"
9178                "};\n",
9179                Style);
9180 
9181   FormatStyle NoEmptyLines = getLLVMStyle();
9182   NoEmptyLines.MaxEmptyLinesToKeep = 0;
9183   verifyFormat("struct foo {\n"
9184                "private:\n"
9185                "  void f() {}\n"
9186                "\n"
9187                "private:\n"
9188                "  int i;\n"
9189                "\n"
9190                "public:\n"
9191                "protected:\n"
9192                "  int j;\n"
9193                "};\n",
9194                NoEmptyLines);
9195 
9196   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9197   verifyFormat("struct foo {\n"
9198                "private:\n"
9199                "  void f() {}\n"
9200                "private:\n"
9201                "  int i;\n"
9202                "public:\n"
9203                "protected:\n"
9204                "  int j;\n"
9205                "};\n",
9206                NoEmptyLines);
9207 
9208   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9209   verifyFormat("struct foo {\n"
9210                "private:\n"
9211                "  void f() {}\n"
9212                "\n"
9213                "private:\n"
9214                "  int i;\n"
9215                "\n"
9216                "public:\n"
9217                "\n"
9218                "protected:\n"
9219                "  int j;\n"
9220                "};\n",
9221                NoEmptyLines);
9222 }
9223 
9224 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
9225 
9226   FormatStyle Style = getLLVMStyle();
9227   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
9228   verifyFormat("struct foo {\n"
9229                "private:\n"
9230                "  void f() {}\n"
9231                "\n"
9232                "private:\n"
9233                "  int i;\n"
9234                "\n"
9235                "protected:\n"
9236                "  int j;\n"
9237                "};\n",
9238                Style);
9239 
9240   // Check if lines are removed.
9241   verifyFormat("struct foo {\n"
9242                "private:\n"
9243                "  void f() {}\n"
9244                "\n"
9245                "private:\n"
9246                "  int i;\n"
9247                "\n"
9248                "protected:\n"
9249                "  int j;\n"
9250                "};\n",
9251                "struct foo {\n"
9252                "private:\n"
9253                "\n"
9254                "  void f() {}\n"
9255                "\n"
9256                "private:\n"
9257                "\n"
9258                "  int i;\n"
9259                "\n"
9260                "protected:\n"
9261                "\n"
9262                "  int j;\n"
9263                "};\n",
9264                Style);
9265 
9266   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9267   verifyFormat("struct foo {\n"
9268                "private:\n"
9269                "\n"
9270                "  void f() {}\n"
9271                "\n"
9272                "private:\n"
9273                "\n"
9274                "  int i;\n"
9275                "\n"
9276                "protected:\n"
9277                "\n"
9278                "  int j;\n"
9279                "};\n",
9280                Style);
9281 
9282   // Check if lines are added.
9283   verifyFormat("struct foo {\n"
9284                "private:\n"
9285                "\n"
9286                "  void f() {}\n"
9287                "\n"
9288                "private:\n"
9289                "\n"
9290                "  int i;\n"
9291                "\n"
9292                "protected:\n"
9293                "\n"
9294                "  int j;\n"
9295                "};\n",
9296                "struct foo {\n"
9297                "private:\n"
9298                "  void f() {}\n"
9299                "\n"
9300                "private:\n"
9301                "  int i;\n"
9302                "\n"
9303                "protected:\n"
9304                "  int j;\n"
9305                "};\n",
9306                Style);
9307 
9308   // Leave tests rely on the code layout, test::messUp can not be used.
9309   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9310   Style.MaxEmptyLinesToKeep = 0u;
9311   verifyFormat("struct foo {\n"
9312                "private:\n"
9313                "  void f() {}\n"
9314                "\n"
9315                "private:\n"
9316                "  int i;\n"
9317                "\n"
9318                "protected:\n"
9319                "  int j;\n"
9320                "};\n",
9321                Style);
9322 
9323   // Check if MaxEmptyLinesToKeep is respected.
9324   EXPECT_EQ("struct foo {\n"
9325             "private:\n"
9326             "  void f() {}\n"
9327             "\n"
9328             "private:\n"
9329             "  int i;\n"
9330             "\n"
9331             "protected:\n"
9332             "  int j;\n"
9333             "};\n",
9334             format("struct foo {\n"
9335                    "private:\n"
9336                    "\n\n\n"
9337                    "  void f() {}\n"
9338                    "\n"
9339                    "private:\n"
9340                    "\n\n\n"
9341                    "  int i;\n"
9342                    "\n"
9343                    "protected:\n"
9344                    "\n\n\n"
9345                    "  int j;\n"
9346                    "};\n",
9347                    Style));
9348 
9349   Style.MaxEmptyLinesToKeep = 1u;
9350   EXPECT_EQ("struct foo {\n"
9351             "private:\n"
9352             "\n"
9353             "  void f() {}\n"
9354             "\n"
9355             "private:\n"
9356             "\n"
9357             "  int i;\n"
9358             "\n"
9359             "protected:\n"
9360             "\n"
9361             "  int j;\n"
9362             "};\n",
9363             format("struct foo {\n"
9364                    "private:\n"
9365                    "\n"
9366                    "  void f() {}\n"
9367                    "\n"
9368                    "private:\n"
9369                    "\n"
9370                    "  int i;\n"
9371                    "\n"
9372                    "protected:\n"
9373                    "\n"
9374                    "  int j;\n"
9375                    "};\n",
9376                    Style));
9377   // Check if no lines are kept.
9378   EXPECT_EQ("struct foo {\n"
9379             "private:\n"
9380             "  void f() {}\n"
9381             "\n"
9382             "private:\n"
9383             "  int i;\n"
9384             "\n"
9385             "protected:\n"
9386             "  int j;\n"
9387             "};\n",
9388             format("struct foo {\n"
9389                    "private:\n"
9390                    "  void f() {}\n"
9391                    "\n"
9392                    "private:\n"
9393                    "  int i;\n"
9394                    "\n"
9395                    "protected:\n"
9396                    "  int j;\n"
9397                    "};\n",
9398                    Style));
9399   // Check if MaxEmptyLinesToKeep is respected.
9400   EXPECT_EQ("struct foo {\n"
9401             "private:\n"
9402             "\n"
9403             "  void f() {}\n"
9404             "\n"
9405             "private:\n"
9406             "\n"
9407             "  int i;\n"
9408             "\n"
9409             "protected:\n"
9410             "\n"
9411             "  int j;\n"
9412             "};\n",
9413             format("struct foo {\n"
9414                    "private:\n"
9415                    "\n\n\n"
9416                    "  void f() {}\n"
9417                    "\n"
9418                    "private:\n"
9419                    "\n\n\n"
9420                    "  int i;\n"
9421                    "\n"
9422                    "protected:\n"
9423                    "\n\n\n"
9424                    "  int j;\n"
9425                    "};\n",
9426                    Style));
9427 
9428   Style.MaxEmptyLinesToKeep = 10u;
9429   EXPECT_EQ("struct foo {\n"
9430             "private:\n"
9431             "\n\n\n"
9432             "  void f() {}\n"
9433             "\n"
9434             "private:\n"
9435             "\n\n\n"
9436             "  int i;\n"
9437             "\n"
9438             "protected:\n"
9439             "\n\n\n"
9440             "  int j;\n"
9441             "};\n",
9442             format("struct foo {\n"
9443                    "private:\n"
9444                    "\n\n\n"
9445                    "  void f() {}\n"
9446                    "\n"
9447                    "private:\n"
9448                    "\n\n\n"
9449                    "  int i;\n"
9450                    "\n"
9451                    "protected:\n"
9452                    "\n\n\n"
9453                    "  int j;\n"
9454                    "};\n",
9455                    Style));
9456 
9457   // Test with comments.
9458   Style = getLLVMStyle();
9459   verifyFormat("struct foo {\n"
9460                "private:\n"
9461                "  // comment\n"
9462                "  void f() {}\n"
9463                "\n"
9464                "private: /* comment */\n"
9465                "  int i;\n"
9466                "};\n",
9467                Style);
9468   verifyFormat("struct foo {\n"
9469                "private:\n"
9470                "  // comment\n"
9471                "  void f() {}\n"
9472                "\n"
9473                "private: /* comment */\n"
9474                "  int i;\n"
9475                "};\n",
9476                "struct foo {\n"
9477                "private:\n"
9478                "\n"
9479                "  // comment\n"
9480                "  void f() {}\n"
9481                "\n"
9482                "private: /* comment */\n"
9483                "\n"
9484                "  int i;\n"
9485                "};\n",
9486                Style);
9487 
9488   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9489   verifyFormat("struct foo {\n"
9490                "private:\n"
9491                "\n"
9492                "  // comment\n"
9493                "  void f() {}\n"
9494                "\n"
9495                "private: /* comment */\n"
9496                "\n"
9497                "  int i;\n"
9498                "};\n",
9499                "struct foo {\n"
9500                "private:\n"
9501                "  // comment\n"
9502                "  void f() {}\n"
9503                "\n"
9504                "private: /* comment */\n"
9505                "  int i;\n"
9506                "};\n",
9507                Style);
9508   verifyFormat("struct foo {\n"
9509                "private:\n"
9510                "\n"
9511                "  // comment\n"
9512                "  void f() {}\n"
9513                "\n"
9514                "private: /* comment */\n"
9515                "\n"
9516                "  int i;\n"
9517                "};\n",
9518                Style);
9519 
9520   // Test with preprocessor defines.
9521   Style = getLLVMStyle();
9522   verifyFormat("struct foo {\n"
9523                "private:\n"
9524                "#ifdef FOO\n"
9525                "#endif\n"
9526                "  void f() {}\n"
9527                "};\n",
9528                Style);
9529   verifyFormat("struct foo {\n"
9530                "private:\n"
9531                "#ifdef FOO\n"
9532                "#endif\n"
9533                "  void f() {}\n"
9534                "};\n",
9535                "struct foo {\n"
9536                "private:\n"
9537                "\n"
9538                "#ifdef FOO\n"
9539                "#endif\n"
9540                "  void f() {}\n"
9541                "};\n",
9542                Style);
9543 
9544   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9545   verifyFormat("struct foo {\n"
9546                "private:\n"
9547                "\n"
9548                "#ifdef FOO\n"
9549                "#endif\n"
9550                "  void f() {}\n"
9551                "};\n",
9552                "struct foo {\n"
9553                "private:\n"
9554                "#ifdef FOO\n"
9555                "#endif\n"
9556                "  void f() {}\n"
9557                "};\n",
9558                Style);
9559   verifyFormat("struct foo {\n"
9560                "private:\n"
9561                "\n"
9562                "#ifdef FOO\n"
9563                "#endif\n"
9564                "  void f() {}\n"
9565                "};\n",
9566                Style);
9567 }
9568 
9569 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
9570   // Combined tests of EmptyLineAfterAccessModifier and
9571   // EmptyLineBeforeAccessModifier.
9572   FormatStyle Style = getLLVMStyle();
9573   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9574   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9575   verifyFormat("struct foo {\n"
9576                "private:\n"
9577                "\n"
9578                "protected:\n"
9579                "};\n",
9580                Style);
9581 
9582   Style.MaxEmptyLinesToKeep = 10u;
9583   // Both remove all new lines.
9584   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9585   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
9586   verifyFormat("struct foo {\n"
9587                "private:\n"
9588                "protected:\n"
9589                "};\n",
9590                "struct foo {\n"
9591                "private:\n"
9592                "\n\n\n"
9593                "protected:\n"
9594                "};\n",
9595                Style);
9596 
9597   // Leave tests rely on the code layout, test::messUp can not be used.
9598   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9599   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9600   Style.MaxEmptyLinesToKeep = 10u;
9601   EXPECT_EQ("struct foo {\n"
9602             "private:\n"
9603             "\n\n\n"
9604             "protected:\n"
9605             "};\n",
9606             format("struct foo {\n"
9607                    "private:\n"
9608                    "\n\n\n"
9609                    "protected:\n"
9610                    "};\n",
9611                    Style));
9612   Style.MaxEmptyLinesToKeep = 3u;
9613   EXPECT_EQ("struct foo {\n"
9614             "private:\n"
9615             "\n\n\n"
9616             "protected:\n"
9617             "};\n",
9618             format("struct foo {\n"
9619                    "private:\n"
9620                    "\n\n\n"
9621                    "protected:\n"
9622                    "};\n",
9623                    Style));
9624   Style.MaxEmptyLinesToKeep = 1u;
9625   EXPECT_EQ("struct foo {\n"
9626             "private:\n"
9627             "\n\n\n"
9628             "protected:\n"
9629             "};\n",
9630             format("struct foo {\n"
9631                    "private:\n"
9632                    "\n\n\n"
9633                    "protected:\n"
9634                    "};\n",
9635                    Style)); // Based on new lines in original document and not
9636                             // on the setting.
9637 
9638   Style.MaxEmptyLinesToKeep = 10u;
9639   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9640   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9641   // Newlines are kept if they are greater than zero,
9642   // test::messUp removes all new lines which changes the logic
9643   EXPECT_EQ("struct foo {\n"
9644             "private:\n"
9645             "\n\n\n"
9646             "protected:\n"
9647             "};\n",
9648             format("struct foo {\n"
9649                    "private:\n"
9650                    "\n\n\n"
9651                    "protected:\n"
9652                    "};\n",
9653                    Style));
9654 
9655   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9656   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9657   // test::messUp removes all new lines which changes the logic
9658   EXPECT_EQ("struct foo {\n"
9659             "private:\n"
9660             "\n\n\n"
9661             "protected:\n"
9662             "};\n",
9663             format("struct foo {\n"
9664                    "private:\n"
9665                    "\n\n\n"
9666                    "protected:\n"
9667                    "};\n",
9668                    Style));
9669 
9670   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9671   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
9672   EXPECT_EQ("struct foo {\n"
9673             "private:\n"
9674             "\n\n\n"
9675             "protected:\n"
9676             "};\n",
9677             format("struct foo {\n"
9678                    "private:\n"
9679                    "\n\n\n"
9680                    "protected:\n"
9681                    "};\n",
9682                    Style)); // test::messUp removes all new lines which changes
9683                             // the logic.
9684 
9685   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9686   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9687   verifyFormat("struct foo {\n"
9688                "private:\n"
9689                "protected:\n"
9690                "};\n",
9691                "struct foo {\n"
9692                "private:\n"
9693                "\n\n\n"
9694                "protected:\n"
9695                "};\n",
9696                Style);
9697 
9698   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9699   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
9700   EXPECT_EQ("struct foo {\n"
9701             "private:\n"
9702             "\n\n\n"
9703             "protected:\n"
9704             "};\n",
9705             format("struct foo {\n"
9706                    "private:\n"
9707                    "\n\n\n"
9708                    "protected:\n"
9709                    "};\n",
9710                    Style)); // test::messUp removes all new lines which changes
9711                             // the logic.
9712 
9713   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9714   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9715   verifyFormat("struct foo {\n"
9716                "private:\n"
9717                "protected:\n"
9718                "};\n",
9719                "struct foo {\n"
9720                "private:\n"
9721                "\n\n\n"
9722                "protected:\n"
9723                "};\n",
9724                Style);
9725 
9726   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
9727   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9728   verifyFormat("struct foo {\n"
9729                "private:\n"
9730                "protected:\n"
9731                "};\n",
9732                "struct foo {\n"
9733                "private:\n"
9734                "\n\n\n"
9735                "protected:\n"
9736                "};\n",
9737                Style);
9738 
9739   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
9740   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9741   verifyFormat("struct foo {\n"
9742                "private:\n"
9743                "protected:\n"
9744                "};\n",
9745                "struct foo {\n"
9746                "private:\n"
9747                "\n\n\n"
9748                "protected:\n"
9749                "};\n",
9750                Style);
9751 
9752   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
9753   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
9754   verifyFormat("struct foo {\n"
9755                "private:\n"
9756                "protected:\n"
9757                "};\n",
9758                "struct foo {\n"
9759                "private:\n"
9760                "\n\n\n"
9761                "protected:\n"
9762                "};\n",
9763                Style);
9764 }
9765 
9766 TEST_F(FormatTest, FormatsArrays) {
9767   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
9768                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
9769   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
9770                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
9771   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
9772                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
9773   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9774                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
9775   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9776                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
9777   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9778                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
9779                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
9780   verifyFormat(
9781       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
9782       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
9783       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
9784   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
9785                "    .aaaaaaaaaaaaaaaaaaaaaa();");
9786 
9787   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
9788                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
9789   verifyFormat(
9790       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
9791       "                                  .aaaaaaa[0]\n"
9792       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
9793   verifyFormat("a[::b::c];");
9794 
9795   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
9796 
9797   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
9798   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
9799 }
9800 
9801 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
9802   verifyFormat("(a)->b();");
9803   verifyFormat("--a;");
9804 }
9805 
9806 TEST_F(FormatTest, HandlesIncludeDirectives) {
9807   verifyFormat("#include <string>\n"
9808                "#include <a/b/c.h>\n"
9809                "#include \"a/b/string\"\n"
9810                "#include \"string.h\"\n"
9811                "#include \"string.h\"\n"
9812                "#include <a-a>\n"
9813                "#include < path with space >\n"
9814                "#include_next <test.h>"
9815                "#include \"abc.h\" // this is included for ABC\n"
9816                "#include \"some long include\" // with a comment\n"
9817                "#include \"some very long include path\"\n"
9818                "#include <some/very/long/include/path>\n",
9819                getLLVMStyleWithColumns(35));
9820   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
9821   EXPECT_EQ("#include <a>", format("#include<a>"));
9822 
9823   verifyFormat("#import <string>");
9824   verifyFormat("#import <a/b/c.h>");
9825   verifyFormat("#import \"a/b/string\"");
9826   verifyFormat("#import \"string.h\"");
9827   verifyFormat("#import \"string.h\"");
9828   verifyFormat("#if __has_include(<strstream>)\n"
9829                "#include <strstream>\n"
9830                "#endif");
9831 
9832   verifyFormat("#define MY_IMPORT <a/b>");
9833 
9834   verifyFormat("#if __has_include(<a/b>)");
9835   verifyFormat("#if __has_include_next(<a/b>)");
9836   verifyFormat("#define F __has_include(<a/b>)");
9837   verifyFormat("#define F __has_include_next(<a/b>)");
9838 
9839   // Protocol buffer definition or missing "#".
9840   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
9841                getLLVMStyleWithColumns(30));
9842 
9843   FormatStyle Style = getLLVMStyle();
9844   Style.AlwaysBreakBeforeMultilineStrings = true;
9845   Style.ColumnLimit = 0;
9846   verifyFormat("#import \"abc.h\"", Style);
9847 
9848   // But 'import' might also be a regular C++ namespace.
9849   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9850                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9851 }
9852 
9853 //===----------------------------------------------------------------------===//
9854 // Error recovery tests.
9855 //===----------------------------------------------------------------------===//
9856 
9857 TEST_F(FormatTest, IncompleteParameterLists) {
9858   FormatStyle NoBinPacking = getLLVMStyle();
9859   NoBinPacking.BinPackParameters = false;
9860   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
9861                "                        double *min_x,\n"
9862                "                        double *max_x,\n"
9863                "                        double *min_y,\n"
9864                "                        double *max_y,\n"
9865                "                        double *min_z,\n"
9866                "                        double *max_z, ) {}",
9867                NoBinPacking);
9868 }
9869 
9870 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
9871   verifyFormat("void f() { return; }\n42");
9872   verifyFormat("void f() {\n"
9873                "  if (0)\n"
9874                "    return;\n"
9875                "}\n"
9876                "42");
9877   verifyFormat("void f() { return }\n42");
9878   verifyFormat("void f() {\n"
9879                "  if (0)\n"
9880                "    return\n"
9881                "}\n"
9882                "42");
9883 }
9884 
9885 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
9886   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
9887   EXPECT_EQ("void f() {\n"
9888             "  if (a)\n"
9889             "    return\n"
9890             "}",
9891             format("void  f  (  )  {  if  ( a )  return  }"));
9892   EXPECT_EQ("namespace N {\n"
9893             "void f()\n"
9894             "}",
9895             format("namespace  N  {  void f()  }"));
9896   EXPECT_EQ("namespace N {\n"
9897             "void f() {}\n"
9898             "void g()\n"
9899             "} // namespace N",
9900             format("namespace N  { void f( ) { } void g( ) }"));
9901 }
9902 
9903 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
9904   verifyFormat("int aaaaaaaa =\n"
9905                "    // Overlylongcomment\n"
9906                "    b;",
9907                getLLVMStyleWithColumns(20));
9908   verifyFormat("function(\n"
9909                "    ShortArgument,\n"
9910                "    LoooooooooooongArgument);\n",
9911                getLLVMStyleWithColumns(20));
9912 }
9913 
9914 TEST_F(FormatTest, IncorrectAccessSpecifier) {
9915   verifyFormat("public:");
9916   verifyFormat("class A {\n"
9917                "public\n"
9918                "  void f() {}\n"
9919                "};");
9920   verifyFormat("public\n"
9921                "int qwerty;");
9922   verifyFormat("public\n"
9923                "B {}");
9924   verifyFormat("public\n"
9925                "{}");
9926   verifyFormat("public\n"
9927                "B { int x; }");
9928 }
9929 
9930 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
9931   verifyFormat("{");
9932   verifyFormat("#})");
9933   verifyNoCrash("(/**/[:!] ?[).");
9934 }
9935 
9936 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
9937   // Found by oss-fuzz:
9938   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
9939   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9940   Style.ColumnLimit = 60;
9941   verifyNoCrash(
9942       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
9943       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
9944       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
9945       Style);
9946 }
9947 
9948 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
9949   verifyFormat("do {\n}");
9950   verifyFormat("do {\n}\n"
9951                "f();");
9952   verifyFormat("do {\n}\n"
9953                "wheeee(fun);");
9954   verifyFormat("do {\n"
9955                "  f();\n"
9956                "}");
9957 }
9958 
9959 TEST_F(FormatTest, IncorrectCodeMissingParens) {
9960   verifyFormat("if {\n  foo;\n  foo();\n}");
9961   verifyFormat("switch {\n  foo;\n  foo();\n}");
9962   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
9963   verifyFormat("while {\n  foo;\n  foo();\n}");
9964   verifyFormat("do {\n  foo;\n  foo();\n} while;");
9965 }
9966 
9967 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
9968   verifyIncompleteFormat("namespace {\n"
9969                          "class Foo { Foo (\n"
9970                          "};\n"
9971                          "} // namespace");
9972 }
9973 
9974 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
9975   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
9976   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
9977   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
9978   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
9979 
9980   EXPECT_EQ("{\n"
9981             "  {\n"
9982             "    breakme(\n"
9983             "        qwe);\n"
9984             "  }\n",
9985             format("{\n"
9986                    "    {\n"
9987                    " breakme(qwe);\n"
9988                    "}\n",
9989                    getLLVMStyleWithColumns(10)));
9990 }
9991 
9992 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
9993   verifyFormat("int x = {\n"
9994                "    avariable,\n"
9995                "    b(alongervariable)};",
9996                getLLVMStyleWithColumns(25));
9997 }
9998 
9999 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
10000   verifyFormat("return (a)(b){1, 2, 3};");
10001 }
10002 
10003 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
10004   verifyFormat("vector<int> x{1, 2, 3, 4};");
10005   verifyFormat("vector<int> x{\n"
10006                "    1,\n"
10007                "    2,\n"
10008                "    3,\n"
10009                "    4,\n"
10010                "};");
10011   verifyFormat("vector<T> x{{}, {}, {}, {}};");
10012   verifyFormat("f({1, 2});");
10013   verifyFormat("auto v = Foo{-1};");
10014   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
10015   verifyFormat("Class::Class : member{1, 2, 3} {}");
10016   verifyFormat("new vector<int>{1, 2, 3};");
10017   verifyFormat("new int[3]{1, 2, 3};");
10018   verifyFormat("new int{1};");
10019   verifyFormat("return {arg1, arg2};");
10020   verifyFormat("return {arg1, SomeType{parameter}};");
10021   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
10022   verifyFormat("new T{arg1, arg2};");
10023   verifyFormat("f(MyMap[{composite, key}]);");
10024   verifyFormat("class Class {\n"
10025                "  T member = {arg1, arg2};\n"
10026                "};");
10027   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
10028   verifyFormat("const struct A a = {.a = 1, .b = 2};");
10029   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
10030   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
10031   verifyFormat("int a = std::is_integral<int>{} + 0;");
10032 
10033   verifyFormat("int foo(int i) { return fo1{}(i); }");
10034   verifyFormat("int foo(int i) { return fo1{}(i); }");
10035   verifyFormat("auto i = decltype(x){};");
10036   verifyFormat("auto i = typeof(x){};");
10037   verifyFormat("auto i = _Atomic(x){};");
10038   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
10039   verifyFormat("Node n{1, Node{1000}, //\n"
10040                "       2};");
10041   verifyFormat("Aaaa aaaaaaa{\n"
10042                "    {\n"
10043                "        aaaa,\n"
10044                "    },\n"
10045                "};");
10046   verifyFormat("class C : public D {\n"
10047                "  SomeClass SC{2};\n"
10048                "};");
10049   verifyFormat("class C : public A {\n"
10050                "  class D : public B {\n"
10051                "    void f() { int i{2}; }\n"
10052                "  };\n"
10053                "};");
10054   verifyFormat("#define A {a, a},");
10055 
10056   // Avoid breaking between equal sign and opening brace
10057   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
10058   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
10059   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
10060                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
10061                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
10062                "     {\"ccccccccccccccccccccc\", 2}};",
10063                AvoidBreakingFirstArgument);
10064 
10065   // Binpacking only if there is no trailing comma
10066   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
10067                "                      cccccccccc, dddddddddd};",
10068                getLLVMStyleWithColumns(50));
10069   verifyFormat("const Aaaaaa aaaaa = {\n"
10070                "    aaaaaaaaaaa,\n"
10071                "    bbbbbbbbbbb,\n"
10072                "    ccccccccccc,\n"
10073                "    ddddddddddd,\n"
10074                "};",
10075                getLLVMStyleWithColumns(50));
10076 
10077   // Cases where distinguising braced lists and blocks is hard.
10078   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
10079   verifyFormat("void f() {\n"
10080                "  return; // comment\n"
10081                "}\n"
10082                "SomeType t;");
10083   verifyFormat("void f() {\n"
10084                "  if (a) {\n"
10085                "    f();\n"
10086                "  }\n"
10087                "}\n"
10088                "SomeType t;");
10089 
10090   // In combination with BinPackArguments = false.
10091   FormatStyle NoBinPacking = getLLVMStyle();
10092   NoBinPacking.BinPackArguments = false;
10093   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
10094                "                      bbbbb,\n"
10095                "                      ccccc,\n"
10096                "                      ddddd,\n"
10097                "                      eeeee,\n"
10098                "                      ffffff,\n"
10099                "                      ggggg,\n"
10100                "                      hhhhhh,\n"
10101                "                      iiiiii,\n"
10102                "                      jjjjjj,\n"
10103                "                      kkkkkk};",
10104                NoBinPacking);
10105   verifyFormat("const Aaaaaa aaaaa = {\n"
10106                "    aaaaa,\n"
10107                "    bbbbb,\n"
10108                "    ccccc,\n"
10109                "    ddddd,\n"
10110                "    eeeee,\n"
10111                "    ffffff,\n"
10112                "    ggggg,\n"
10113                "    hhhhhh,\n"
10114                "    iiiiii,\n"
10115                "    jjjjjj,\n"
10116                "    kkkkkk,\n"
10117                "};",
10118                NoBinPacking);
10119   verifyFormat(
10120       "const Aaaaaa aaaaa = {\n"
10121       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
10122       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
10123       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
10124       "};",
10125       NoBinPacking);
10126 
10127   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
10128   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
10129             "    CDDDP83848_BMCR_REGISTER,\n"
10130             "    CDDDP83848_BMSR_REGISTER,\n"
10131             "    CDDDP83848_RBR_REGISTER};",
10132             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
10133                    "                                CDDDP83848_BMSR_REGISTER,\n"
10134                    "                                CDDDP83848_RBR_REGISTER};",
10135                    NoBinPacking));
10136 
10137   // FIXME: The alignment of these trailing comments might be bad. Then again,
10138   // this might be utterly useless in real code.
10139   verifyFormat("Constructor::Constructor()\n"
10140                "    : some_value{         //\n"
10141                "                 aaaaaaa, //\n"
10142                "                 bbbbbbb} {}");
10143 
10144   // In braced lists, the first comment is always assumed to belong to the
10145   // first element. Thus, it can be moved to the next or previous line as
10146   // appropriate.
10147   EXPECT_EQ("function({// First element:\n"
10148             "          1,\n"
10149             "          // Second element:\n"
10150             "          2});",
10151             format("function({\n"
10152                    "    // First element:\n"
10153                    "    1,\n"
10154                    "    // Second element:\n"
10155                    "    2});"));
10156   EXPECT_EQ("std::vector<int> MyNumbers{\n"
10157             "    // First element:\n"
10158             "    1,\n"
10159             "    // Second element:\n"
10160             "    2};",
10161             format("std::vector<int> MyNumbers{// First element:\n"
10162                    "                           1,\n"
10163                    "                           // Second element:\n"
10164                    "                           2};",
10165                    getLLVMStyleWithColumns(30)));
10166   // A trailing comma should still lead to an enforced line break and no
10167   // binpacking.
10168   EXPECT_EQ("vector<int> SomeVector = {\n"
10169             "    // aaa\n"
10170             "    1,\n"
10171             "    2,\n"
10172             "};",
10173             format("vector<int> SomeVector = { // aaa\n"
10174                    "    1, 2, };"));
10175 
10176   // C++11 brace initializer list l-braces should not be treated any differently
10177   // when breaking before lambda bodies is enabled
10178   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
10179   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
10180   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
10181   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
10182   verifyFormat(
10183       "std::runtime_error{\n"
10184       "    \"Long string which will force a break onto the next line...\"};",
10185       BreakBeforeLambdaBody);
10186 
10187   FormatStyle ExtraSpaces = getLLVMStyle();
10188   ExtraSpaces.Cpp11BracedListStyle = false;
10189   ExtraSpaces.ColumnLimit = 75;
10190   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
10191   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
10192   verifyFormat("f({ 1, 2 });", ExtraSpaces);
10193   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
10194   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
10195   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
10196   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
10197   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
10198   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
10199   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
10200   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
10201   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
10202   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
10203   verifyFormat("class Class {\n"
10204                "  T member = { arg1, arg2 };\n"
10205                "};",
10206                ExtraSpaces);
10207   verifyFormat(
10208       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10209       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
10210       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
10211       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
10212       ExtraSpaces);
10213   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
10214   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
10215                ExtraSpaces);
10216   verifyFormat(
10217       "someFunction(OtherParam,\n"
10218       "             BracedList{ // comment 1 (Forcing interesting break)\n"
10219       "                         param1, param2,\n"
10220       "                         // comment 2\n"
10221       "                         param3, param4 });",
10222       ExtraSpaces);
10223   verifyFormat(
10224       "std::this_thread::sleep_for(\n"
10225       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
10226       ExtraSpaces);
10227   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
10228                "    aaaaaaa,\n"
10229                "    aaaaaaaaaa,\n"
10230                "    aaaaa,\n"
10231                "    aaaaaaaaaaaaaaa,\n"
10232                "    aaa,\n"
10233                "    aaaaaaaaaa,\n"
10234                "    a,\n"
10235                "    aaaaaaaaaaaaaaaaaaaaa,\n"
10236                "    aaaaaaaaaaaa,\n"
10237                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
10238                "    aaaaaaa,\n"
10239                "    a};");
10240   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
10241   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
10242   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
10243 
10244   // Avoid breaking between initializer/equal sign and opening brace
10245   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
10246   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
10247                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
10248                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
10249                "  { \"ccccccccccccccccccccc\", 2 }\n"
10250                "};",
10251                ExtraSpaces);
10252   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
10253                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
10254                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
10255                "  { \"ccccccccccccccccccccc\", 2 }\n"
10256                "};",
10257                ExtraSpaces);
10258 
10259   FormatStyle SpaceBeforeBrace = getLLVMStyle();
10260   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
10261   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
10262   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
10263 
10264   FormatStyle SpaceBetweenBraces = getLLVMStyle();
10265   SpaceBetweenBraces.SpacesInAngles = true;
10266   SpaceBetweenBraces.SpacesInParentheses = true;
10267   SpaceBetweenBraces.SpacesInSquareBrackets = true;
10268   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
10269   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
10270   verifyFormat("vector< int > x{ // comment 1\n"
10271                "                 1, 2, 3, 4 };",
10272                SpaceBetweenBraces);
10273   SpaceBetweenBraces.ColumnLimit = 20;
10274   EXPECT_EQ("vector< int > x{\n"
10275             "    1, 2, 3, 4 };",
10276             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
10277   SpaceBetweenBraces.ColumnLimit = 24;
10278   EXPECT_EQ("vector< int > x{ 1, 2,\n"
10279             "                 3, 4 };",
10280             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
10281   EXPECT_EQ("vector< int > x{\n"
10282             "    1,\n"
10283             "    2,\n"
10284             "    3,\n"
10285             "    4,\n"
10286             "};",
10287             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
10288   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
10289   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
10290   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
10291 }
10292 
10293 TEST_F(FormatTest, FormatSpacesInAngles) {
10294   FormatStyle SpaceInAngles = getLLVMStyle();
10295   SpaceInAngles.SpacesInAngles = true;
10296   verifyFormat("vector< ::std::string > x1;", SpaceInAngles);
10297   verifyFormat("Foo< int, Bar > x2;", SpaceInAngles);
10298   verifyFormat("Foo< ::int, ::Bar > x3;", SpaceInAngles);
10299 
10300   SpaceInAngles.SpacesInAngles = false;
10301   verifyFormat("vector<::std::string> x4;", SpaceInAngles);
10302   verifyFormat("vector<int> x5;", SpaceInAngles);
10303   verifyFormat("Foo<int, Bar> x6;", SpaceInAngles);
10304   verifyFormat("Foo<::int, ::Bar> x7;", SpaceInAngles);
10305 }
10306 
10307 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
10308   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10309                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10310                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10311                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10312                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10313                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
10314   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
10315                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10316                "                 1, 22, 333, 4444, 55555, //\n"
10317                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10318                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
10319   verifyFormat(
10320       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
10321       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
10322       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
10323       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
10324       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
10325       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
10326       "                 7777777};");
10327   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
10328                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
10329                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
10330   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
10331                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
10332                "    // Separating comment.\n"
10333                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
10334   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
10335                "    // Leading comment\n"
10336                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
10337                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
10338   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
10339                "                 1, 1, 1, 1};",
10340                getLLVMStyleWithColumns(39));
10341   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
10342                "                 1, 1, 1, 1};",
10343                getLLVMStyleWithColumns(38));
10344   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
10345                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
10346                getLLVMStyleWithColumns(43));
10347   verifyFormat(
10348       "static unsigned SomeValues[10][3] = {\n"
10349       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
10350       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
10351   verifyFormat("static auto fields = new vector<string>{\n"
10352                "    \"aaaaaaaaaaaaa\",\n"
10353                "    \"aaaaaaaaaaaaa\",\n"
10354                "    \"aaaaaaaaaaaa\",\n"
10355                "    \"aaaaaaaaaaaaaa\",\n"
10356                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
10357                "    \"aaaaaaaaaaaa\",\n"
10358                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
10359                "};");
10360   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
10361   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
10362                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
10363                "                 3, cccccccccccccccccccccc};",
10364                getLLVMStyleWithColumns(60));
10365 
10366   // Trailing commas.
10367   verifyFormat("vector<int> x = {\n"
10368                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
10369                "};",
10370                getLLVMStyleWithColumns(39));
10371   verifyFormat("vector<int> x = {\n"
10372                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
10373                "};",
10374                getLLVMStyleWithColumns(39));
10375   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
10376                "                 1, 1, 1, 1,\n"
10377                "                 /**/ /**/};",
10378                getLLVMStyleWithColumns(39));
10379 
10380   // Trailing comment in the first line.
10381   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
10382                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
10383                "    111111111,  222222222,  3333333333,  444444444,  //\n"
10384                "    11111111,   22222222,   333333333,   44444444};");
10385   // Trailing comment in the last line.
10386   verifyFormat("int aaaaa[] = {\n"
10387                "    1, 2, 3, // comment\n"
10388                "    4, 5, 6  // comment\n"
10389                "};");
10390 
10391   // With nested lists, we should either format one item per line or all nested
10392   // lists one on line.
10393   // FIXME: For some nested lists, we can do better.
10394   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
10395                "        {aaaaaaaaaaaaaaaaaaa},\n"
10396                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
10397                "        {aaaaaaaaaaaaaaaaa}};",
10398                getLLVMStyleWithColumns(60));
10399   verifyFormat(
10400       "SomeStruct my_struct_array = {\n"
10401       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
10402       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
10403       "    {aaa, aaa},\n"
10404       "    {aaa, aaa},\n"
10405       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
10406       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
10407       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
10408 
10409   // No column layout should be used here.
10410   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
10411                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
10412 
10413   verifyNoCrash("a<,");
10414 
10415   // No braced initializer here.
10416   verifyFormat("void f() {\n"
10417                "  struct Dummy {};\n"
10418                "  f(v);\n"
10419                "}");
10420 
10421   // Long lists should be formatted in columns even if they are nested.
10422   verifyFormat(
10423       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10424       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10425       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10426       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10427       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10428       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
10429 
10430   // Allow "single-column" layout even if that violates the column limit. There
10431   // isn't going to be a better way.
10432   verifyFormat("std::vector<int> a = {\n"
10433                "    aaaaaaaa,\n"
10434                "    aaaaaaaa,\n"
10435                "    aaaaaaaa,\n"
10436                "    aaaaaaaa,\n"
10437                "    aaaaaaaaaa,\n"
10438                "    aaaaaaaa,\n"
10439                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
10440                getLLVMStyleWithColumns(30));
10441   verifyFormat("vector<int> aaaa = {\n"
10442                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10443                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10444                "    aaaaaa.aaaaaaa,\n"
10445                "    aaaaaa.aaaaaaa,\n"
10446                "    aaaaaa.aaaaaaa,\n"
10447                "    aaaaaa.aaaaaaa,\n"
10448                "};");
10449 
10450   // Don't create hanging lists.
10451   verifyFormat("someFunction(Param, {List1, List2,\n"
10452                "                     List3});",
10453                getLLVMStyleWithColumns(35));
10454   verifyFormat("someFunction(Param, Param,\n"
10455                "             {List1, List2,\n"
10456                "              List3});",
10457                getLLVMStyleWithColumns(35));
10458   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
10459                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
10460 }
10461 
10462 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
10463   FormatStyle DoNotMerge = getLLVMStyle();
10464   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10465 
10466   verifyFormat("void f() { return 42; }");
10467   verifyFormat("void f() {\n"
10468                "  return 42;\n"
10469                "}",
10470                DoNotMerge);
10471   verifyFormat("void f() {\n"
10472                "  // Comment\n"
10473                "}");
10474   verifyFormat("{\n"
10475                "#error {\n"
10476                "  int a;\n"
10477                "}");
10478   verifyFormat("{\n"
10479                "  int a;\n"
10480                "#error {\n"
10481                "}");
10482   verifyFormat("void f() {} // comment");
10483   verifyFormat("void f() { int a; } // comment");
10484   verifyFormat("void f() {\n"
10485                "} // comment",
10486                DoNotMerge);
10487   verifyFormat("void f() {\n"
10488                "  int a;\n"
10489                "} // comment",
10490                DoNotMerge);
10491   verifyFormat("void f() {\n"
10492                "} // comment",
10493                getLLVMStyleWithColumns(15));
10494 
10495   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
10496   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
10497 
10498   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
10499   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
10500   verifyFormat("class C {\n"
10501                "  C()\n"
10502                "      : iiiiiiii(nullptr),\n"
10503                "        kkkkkkk(nullptr),\n"
10504                "        mmmmmmm(nullptr),\n"
10505                "        nnnnnnn(nullptr) {}\n"
10506                "};",
10507                getGoogleStyle());
10508 
10509   FormatStyle NoColumnLimit = getLLVMStyle();
10510   NoColumnLimit.ColumnLimit = 0;
10511   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
10512   EXPECT_EQ("class C {\n"
10513             "  A() : b(0) {}\n"
10514             "};",
10515             format("class C{A():b(0){}};", NoColumnLimit));
10516   EXPECT_EQ("A()\n"
10517             "    : b(0) {\n"
10518             "}",
10519             format("A()\n:b(0)\n{\n}", NoColumnLimit));
10520 
10521   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
10522   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
10523       FormatStyle::SFS_None;
10524   EXPECT_EQ("A()\n"
10525             "    : b(0) {\n"
10526             "}",
10527             format("A():b(0){}", DoNotMergeNoColumnLimit));
10528   EXPECT_EQ("A()\n"
10529             "    : b(0) {\n"
10530             "}",
10531             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
10532 
10533   verifyFormat("#define A          \\\n"
10534                "  void f() {       \\\n"
10535                "    int i;         \\\n"
10536                "  }",
10537                getLLVMStyleWithColumns(20));
10538   verifyFormat("#define A           \\\n"
10539                "  void f() { int i; }",
10540                getLLVMStyleWithColumns(21));
10541   verifyFormat("#define A            \\\n"
10542                "  void f() {         \\\n"
10543                "    int i;           \\\n"
10544                "  }                  \\\n"
10545                "  int j;",
10546                getLLVMStyleWithColumns(22));
10547   verifyFormat("#define A             \\\n"
10548                "  void f() { int i; } \\\n"
10549                "  int j;",
10550                getLLVMStyleWithColumns(23));
10551 }
10552 
10553 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
10554   FormatStyle MergeEmptyOnly = getLLVMStyle();
10555   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
10556   verifyFormat("class C {\n"
10557                "  int f() {}\n"
10558                "};",
10559                MergeEmptyOnly);
10560   verifyFormat("class C {\n"
10561                "  int f() {\n"
10562                "    return 42;\n"
10563                "  }\n"
10564                "};",
10565                MergeEmptyOnly);
10566   verifyFormat("int f() {}", MergeEmptyOnly);
10567   verifyFormat("int f() {\n"
10568                "  return 42;\n"
10569                "}",
10570                MergeEmptyOnly);
10571 
10572   // Also verify behavior when BraceWrapping.AfterFunction = true
10573   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
10574   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
10575   verifyFormat("int f() {}", MergeEmptyOnly);
10576   verifyFormat("class C {\n"
10577                "  int f() {}\n"
10578                "};",
10579                MergeEmptyOnly);
10580 }
10581 
10582 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
10583   FormatStyle MergeInlineOnly = getLLVMStyle();
10584   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
10585   verifyFormat("class C {\n"
10586                "  int f() { return 42; }\n"
10587                "};",
10588                MergeInlineOnly);
10589   verifyFormat("int f() {\n"
10590                "  return 42;\n"
10591                "}",
10592                MergeInlineOnly);
10593 
10594   // SFS_Inline implies SFS_Empty
10595   verifyFormat("class C {\n"
10596                "  int f() {}\n"
10597                "};",
10598                MergeInlineOnly);
10599   verifyFormat("int f() {}", MergeInlineOnly);
10600 
10601   // Also verify behavior when BraceWrapping.AfterFunction = true
10602   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
10603   MergeInlineOnly.BraceWrapping.AfterFunction = true;
10604   verifyFormat("class C {\n"
10605                "  int f() { return 42; }\n"
10606                "};",
10607                MergeInlineOnly);
10608   verifyFormat("int f()\n"
10609                "{\n"
10610                "  return 42;\n"
10611                "}",
10612                MergeInlineOnly);
10613 
10614   // SFS_Inline implies SFS_Empty
10615   verifyFormat("int f() {}", MergeInlineOnly);
10616   verifyFormat("class C {\n"
10617                "  int f() {}\n"
10618                "};",
10619                MergeInlineOnly);
10620 }
10621 
10622 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
10623   FormatStyle MergeInlineOnly = getLLVMStyle();
10624   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
10625       FormatStyle::SFS_InlineOnly;
10626   verifyFormat("class C {\n"
10627                "  int f() { return 42; }\n"
10628                "};",
10629                MergeInlineOnly);
10630   verifyFormat("int f() {\n"
10631                "  return 42;\n"
10632                "}",
10633                MergeInlineOnly);
10634 
10635   // SFS_InlineOnly does not imply SFS_Empty
10636   verifyFormat("class C {\n"
10637                "  int f() {}\n"
10638                "};",
10639                MergeInlineOnly);
10640   verifyFormat("int f() {\n"
10641                "}",
10642                MergeInlineOnly);
10643 
10644   // Also verify behavior when BraceWrapping.AfterFunction = true
10645   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
10646   MergeInlineOnly.BraceWrapping.AfterFunction = true;
10647   verifyFormat("class C {\n"
10648                "  int f() { return 42; }\n"
10649                "};",
10650                MergeInlineOnly);
10651   verifyFormat("int f()\n"
10652                "{\n"
10653                "  return 42;\n"
10654                "}",
10655                MergeInlineOnly);
10656 
10657   // SFS_InlineOnly does not imply SFS_Empty
10658   verifyFormat("int f()\n"
10659                "{\n"
10660                "}",
10661                MergeInlineOnly);
10662   verifyFormat("class C {\n"
10663                "  int f() {}\n"
10664                "};",
10665                MergeInlineOnly);
10666 }
10667 
10668 TEST_F(FormatTest, SplitEmptyFunction) {
10669   FormatStyle Style = getLLVMStyle();
10670   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10671   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10672   Style.BraceWrapping.AfterFunction = true;
10673   Style.BraceWrapping.SplitEmptyFunction = false;
10674   Style.ColumnLimit = 40;
10675 
10676   verifyFormat("int f()\n"
10677                "{}",
10678                Style);
10679   verifyFormat("int f()\n"
10680                "{\n"
10681                "  return 42;\n"
10682                "}",
10683                Style);
10684   verifyFormat("int f()\n"
10685                "{\n"
10686                "  // some comment\n"
10687                "}",
10688                Style);
10689 
10690   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
10691   verifyFormat("int f() {}", Style);
10692   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10693                "{}",
10694                Style);
10695   verifyFormat("int f()\n"
10696                "{\n"
10697                "  return 0;\n"
10698                "}",
10699                Style);
10700 
10701   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
10702   verifyFormat("class Foo {\n"
10703                "  int f() {}\n"
10704                "};\n",
10705                Style);
10706   verifyFormat("class Foo {\n"
10707                "  int f() { return 0; }\n"
10708                "};\n",
10709                Style);
10710   verifyFormat("class Foo {\n"
10711                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10712                "  {}\n"
10713                "};\n",
10714                Style);
10715   verifyFormat("class Foo {\n"
10716                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10717                "  {\n"
10718                "    return 0;\n"
10719                "  }\n"
10720                "};\n",
10721                Style);
10722 
10723   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
10724   verifyFormat("int f() {}", Style);
10725   verifyFormat("int f() { return 0; }", Style);
10726   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10727                "{}",
10728                Style);
10729   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10730                "{\n"
10731                "  return 0;\n"
10732                "}",
10733                Style);
10734 }
10735 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
10736   FormatStyle Style = getLLVMStyle();
10737   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
10738   verifyFormat("#ifdef A\n"
10739                "int f() {}\n"
10740                "#else\n"
10741                "int g() {}\n"
10742                "#endif",
10743                Style);
10744 }
10745 
10746 TEST_F(FormatTest, SplitEmptyClass) {
10747   FormatStyle Style = getLLVMStyle();
10748   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10749   Style.BraceWrapping.AfterClass = true;
10750   Style.BraceWrapping.SplitEmptyRecord = false;
10751 
10752   verifyFormat("class Foo\n"
10753                "{};",
10754                Style);
10755   verifyFormat("/* something */ class Foo\n"
10756                "{};",
10757                Style);
10758   verifyFormat("template <typename X> class Foo\n"
10759                "{};",
10760                Style);
10761   verifyFormat("class Foo\n"
10762                "{\n"
10763                "  Foo();\n"
10764                "};",
10765                Style);
10766   verifyFormat("typedef class Foo\n"
10767                "{\n"
10768                "} Foo_t;",
10769                Style);
10770 
10771   Style.BraceWrapping.SplitEmptyRecord = true;
10772   Style.BraceWrapping.AfterStruct = true;
10773   verifyFormat("class rep\n"
10774                "{\n"
10775                "};",
10776                Style);
10777   verifyFormat("struct rep\n"
10778                "{\n"
10779                "};",
10780                Style);
10781   verifyFormat("template <typename T> class rep\n"
10782                "{\n"
10783                "};",
10784                Style);
10785   verifyFormat("template <typename T> struct rep\n"
10786                "{\n"
10787                "};",
10788                Style);
10789   verifyFormat("class rep\n"
10790                "{\n"
10791                "  int x;\n"
10792                "};",
10793                Style);
10794   verifyFormat("struct rep\n"
10795                "{\n"
10796                "  int x;\n"
10797                "};",
10798                Style);
10799   verifyFormat("template <typename T> class rep\n"
10800                "{\n"
10801                "  int x;\n"
10802                "};",
10803                Style);
10804   verifyFormat("template <typename T> struct rep\n"
10805                "{\n"
10806                "  int x;\n"
10807                "};",
10808                Style);
10809   verifyFormat("template <typename T> class rep // Foo\n"
10810                "{\n"
10811                "  int x;\n"
10812                "};",
10813                Style);
10814   verifyFormat("template <typename T> struct rep // Bar\n"
10815                "{\n"
10816                "  int x;\n"
10817                "};",
10818                Style);
10819 
10820   verifyFormat("template <typename T> class rep<T>\n"
10821                "{\n"
10822                "  int x;\n"
10823                "};",
10824                Style);
10825 
10826   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
10827                "{\n"
10828                "  int x;\n"
10829                "};",
10830                Style);
10831   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
10832                "{\n"
10833                "};",
10834                Style);
10835 
10836   verifyFormat("#include \"stdint.h\"\n"
10837                "namespace rep {}",
10838                Style);
10839   verifyFormat("#include <stdint.h>\n"
10840                "namespace rep {}",
10841                Style);
10842   verifyFormat("#include <stdint.h>\n"
10843                "namespace rep {}",
10844                "#include <stdint.h>\n"
10845                "namespace rep {\n"
10846                "\n"
10847                "\n"
10848                "}",
10849                Style);
10850 }
10851 
10852 TEST_F(FormatTest, SplitEmptyStruct) {
10853   FormatStyle Style = getLLVMStyle();
10854   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10855   Style.BraceWrapping.AfterStruct = true;
10856   Style.BraceWrapping.SplitEmptyRecord = false;
10857 
10858   verifyFormat("struct Foo\n"
10859                "{};",
10860                Style);
10861   verifyFormat("/* something */ struct Foo\n"
10862                "{};",
10863                Style);
10864   verifyFormat("template <typename X> struct Foo\n"
10865                "{};",
10866                Style);
10867   verifyFormat("struct Foo\n"
10868                "{\n"
10869                "  Foo();\n"
10870                "};",
10871                Style);
10872   verifyFormat("typedef struct Foo\n"
10873                "{\n"
10874                "} Foo_t;",
10875                Style);
10876   // typedef struct Bar {} Bar_t;
10877 }
10878 
10879 TEST_F(FormatTest, SplitEmptyUnion) {
10880   FormatStyle Style = getLLVMStyle();
10881   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10882   Style.BraceWrapping.AfterUnion = true;
10883   Style.BraceWrapping.SplitEmptyRecord = false;
10884 
10885   verifyFormat("union Foo\n"
10886                "{};",
10887                Style);
10888   verifyFormat("/* something */ union Foo\n"
10889                "{};",
10890                Style);
10891   verifyFormat("union Foo\n"
10892                "{\n"
10893                "  A,\n"
10894                "};",
10895                Style);
10896   verifyFormat("typedef union Foo\n"
10897                "{\n"
10898                "} Foo_t;",
10899                Style);
10900 }
10901 
10902 TEST_F(FormatTest, SplitEmptyNamespace) {
10903   FormatStyle Style = getLLVMStyle();
10904   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10905   Style.BraceWrapping.AfterNamespace = true;
10906   Style.BraceWrapping.SplitEmptyNamespace = false;
10907 
10908   verifyFormat("namespace Foo\n"
10909                "{};",
10910                Style);
10911   verifyFormat("/* something */ namespace Foo\n"
10912                "{};",
10913                Style);
10914   verifyFormat("inline namespace Foo\n"
10915                "{};",
10916                Style);
10917   verifyFormat("/* something */ inline namespace Foo\n"
10918                "{};",
10919                Style);
10920   verifyFormat("export namespace Foo\n"
10921                "{};",
10922                Style);
10923   verifyFormat("namespace Foo\n"
10924                "{\n"
10925                "void Bar();\n"
10926                "};",
10927                Style);
10928 }
10929 
10930 TEST_F(FormatTest, NeverMergeShortRecords) {
10931   FormatStyle Style = getLLVMStyle();
10932 
10933   verifyFormat("class Foo {\n"
10934                "  Foo();\n"
10935                "};",
10936                Style);
10937   verifyFormat("typedef class Foo {\n"
10938                "  Foo();\n"
10939                "} Foo_t;",
10940                Style);
10941   verifyFormat("struct Foo {\n"
10942                "  Foo();\n"
10943                "};",
10944                Style);
10945   verifyFormat("typedef struct Foo {\n"
10946                "  Foo();\n"
10947                "} Foo_t;",
10948                Style);
10949   verifyFormat("union Foo {\n"
10950                "  A,\n"
10951                "};",
10952                Style);
10953   verifyFormat("typedef union Foo {\n"
10954                "  A,\n"
10955                "} Foo_t;",
10956                Style);
10957   verifyFormat("namespace Foo {\n"
10958                "void Bar();\n"
10959                "};",
10960                Style);
10961 
10962   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10963   Style.BraceWrapping.AfterClass = true;
10964   Style.BraceWrapping.AfterStruct = true;
10965   Style.BraceWrapping.AfterUnion = true;
10966   Style.BraceWrapping.AfterNamespace = true;
10967   verifyFormat("class Foo\n"
10968                "{\n"
10969                "  Foo();\n"
10970                "};",
10971                Style);
10972   verifyFormat("typedef class Foo\n"
10973                "{\n"
10974                "  Foo();\n"
10975                "} Foo_t;",
10976                Style);
10977   verifyFormat("struct Foo\n"
10978                "{\n"
10979                "  Foo();\n"
10980                "};",
10981                Style);
10982   verifyFormat("typedef struct Foo\n"
10983                "{\n"
10984                "  Foo();\n"
10985                "} Foo_t;",
10986                Style);
10987   verifyFormat("union Foo\n"
10988                "{\n"
10989                "  A,\n"
10990                "};",
10991                Style);
10992   verifyFormat("typedef union Foo\n"
10993                "{\n"
10994                "  A,\n"
10995                "} Foo_t;",
10996                Style);
10997   verifyFormat("namespace Foo\n"
10998                "{\n"
10999                "void Bar();\n"
11000                "};",
11001                Style);
11002 }
11003 
11004 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
11005   // Elaborate type variable declarations.
11006   verifyFormat("struct foo a = {bar};\nint n;");
11007   verifyFormat("class foo a = {bar};\nint n;");
11008   verifyFormat("union foo a = {bar};\nint n;");
11009 
11010   // Elaborate types inside function definitions.
11011   verifyFormat("struct foo f() {}\nint n;");
11012   verifyFormat("class foo f() {}\nint n;");
11013   verifyFormat("union foo f() {}\nint n;");
11014 
11015   // Templates.
11016   verifyFormat("template <class X> void f() {}\nint n;");
11017   verifyFormat("template <struct X> void f() {}\nint n;");
11018   verifyFormat("template <union X> void f() {}\nint n;");
11019 
11020   // Actual definitions...
11021   verifyFormat("struct {\n} n;");
11022   verifyFormat(
11023       "template <template <class T, class Y>, class Z> class X {\n} n;");
11024   verifyFormat("union Z {\n  int n;\n} x;");
11025   verifyFormat("class MACRO Z {\n} n;");
11026   verifyFormat("class MACRO(X) Z {\n} n;");
11027   verifyFormat("class __attribute__(X) Z {\n} n;");
11028   verifyFormat("class __declspec(X) Z {\n} n;");
11029   verifyFormat("class A##B##C {\n} n;");
11030   verifyFormat("class alignas(16) Z {\n} n;");
11031   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
11032   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
11033 
11034   // Redefinition from nested context:
11035   verifyFormat("class A::B::C {\n} n;");
11036 
11037   // Template definitions.
11038   verifyFormat(
11039       "template <typename F>\n"
11040       "Matcher(const Matcher<F> &Other,\n"
11041       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
11042       "                             !is_same<F, T>::value>::type * = 0)\n"
11043       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
11044 
11045   // FIXME: This is still incorrectly handled at the formatter side.
11046   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
11047   verifyFormat("int i = SomeFunction(a<b, a> b);");
11048 
11049   // FIXME:
11050   // This now gets parsed incorrectly as class definition.
11051   // verifyFormat("class A<int> f() {\n}\nint n;");
11052 
11053   // Elaborate types where incorrectly parsing the structural element would
11054   // break the indent.
11055   verifyFormat("if (true)\n"
11056                "  class X x;\n"
11057                "else\n"
11058                "  f();\n");
11059 
11060   // This is simply incomplete. Formatting is not important, but must not crash.
11061   verifyFormat("class A:");
11062 }
11063 
11064 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
11065   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
11066             format("#error Leave     all         white!!!!! space* alone!\n"));
11067   EXPECT_EQ(
11068       "#warning Leave     all         white!!!!! space* alone!\n",
11069       format("#warning Leave     all         white!!!!! space* alone!\n"));
11070   EXPECT_EQ("#error 1", format("  #  error   1"));
11071   EXPECT_EQ("#warning 1", format("  #  warning 1"));
11072 }
11073 
11074 TEST_F(FormatTest, FormatHashIfExpressions) {
11075   verifyFormat("#if AAAA && BBBB");
11076   verifyFormat("#if (AAAA && BBBB)");
11077   verifyFormat("#elif (AAAA && BBBB)");
11078   // FIXME: Come up with a better indentation for #elif.
11079   verifyFormat(
11080       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
11081       "    defined(BBBBBBBB)\n"
11082       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
11083       "    defined(BBBBBBBB)\n"
11084       "#endif",
11085       getLLVMStyleWithColumns(65));
11086 }
11087 
11088 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
11089   FormatStyle AllowsMergedIf = getGoogleStyle();
11090   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
11091       FormatStyle::SIS_WithoutElse;
11092   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
11093   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
11094   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
11095   EXPECT_EQ("if (true) return 42;",
11096             format("if (true)\nreturn 42;", AllowsMergedIf));
11097   FormatStyle ShortMergedIf = AllowsMergedIf;
11098   ShortMergedIf.ColumnLimit = 25;
11099   verifyFormat("#define A \\\n"
11100                "  if (true) return 42;",
11101                ShortMergedIf);
11102   verifyFormat("#define A \\\n"
11103                "  f();    \\\n"
11104                "  if (true)\n"
11105                "#define B",
11106                ShortMergedIf);
11107   verifyFormat("#define A \\\n"
11108                "  f();    \\\n"
11109                "  if (true)\n"
11110                "g();",
11111                ShortMergedIf);
11112   verifyFormat("{\n"
11113                "#ifdef A\n"
11114                "  // Comment\n"
11115                "  if (true) continue;\n"
11116                "#endif\n"
11117                "  // Comment\n"
11118                "  if (true) continue;\n"
11119                "}",
11120                ShortMergedIf);
11121   ShortMergedIf.ColumnLimit = 33;
11122   verifyFormat("#define A \\\n"
11123                "  if constexpr (true) return 42;",
11124                ShortMergedIf);
11125   verifyFormat("#define A \\\n"
11126                "  if CONSTEXPR (true) return 42;",
11127                ShortMergedIf);
11128   ShortMergedIf.ColumnLimit = 29;
11129   verifyFormat("#define A                   \\\n"
11130                "  if (aaaaaaaaaa) return 1; \\\n"
11131                "  return 2;",
11132                ShortMergedIf);
11133   ShortMergedIf.ColumnLimit = 28;
11134   verifyFormat("#define A         \\\n"
11135                "  if (aaaaaaaaaa) \\\n"
11136                "    return 1;     \\\n"
11137                "  return 2;",
11138                ShortMergedIf);
11139   verifyFormat("#define A                \\\n"
11140                "  if constexpr (aaaaaaa) \\\n"
11141                "    return 1;            \\\n"
11142                "  return 2;",
11143                ShortMergedIf);
11144   verifyFormat("#define A                \\\n"
11145                "  if CONSTEXPR (aaaaaaa) \\\n"
11146                "    return 1;            \\\n"
11147                "  return 2;",
11148                ShortMergedIf);
11149 }
11150 
11151 TEST_F(FormatTest, FormatStarDependingOnContext) {
11152   verifyFormat("void f(int *a);");
11153   verifyFormat("void f() { f(fint * b); }");
11154   verifyFormat("class A {\n  void f(int *a);\n};");
11155   verifyFormat("class A {\n  int *a;\n};");
11156   verifyFormat("namespace a {\n"
11157                "namespace b {\n"
11158                "class A {\n"
11159                "  void f() {}\n"
11160                "  int *a;\n"
11161                "};\n"
11162                "} // namespace b\n"
11163                "} // namespace a");
11164 }
11165 
11166 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
11167   verifyFormat("while");
11168   verifyFormat("operator");
11169 }
11170 
11171 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
11172   // This code would be painfully slow to format if we didn't skip it.
11173   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
11174                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11175                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11176                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11177                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11178                    "A(1, 1)\n"
11179                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
11180                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11181                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11182                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11183                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11184                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11185                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11186                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11187                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11188                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
11189   // Deeply nested part is untouched, rest is formatted.
11190   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
11191             format(std::string("int    i;\n") + Code + "int    j;\n",
11192                    getLLVMStyle(), SC_ExpectIncomplete));
11193 }
11194 
11195 //===----------------------------------------------------------------------===//
11196 // Objective-C tests.
11197 //===----------------------------------------------------------------------===//
11198 
11199 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
11200   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
11201   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
11202             format("-(NSUInteger)indexOfObject:(id)anObject;"));
11203   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
11204   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
11205   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
11206             format("-(NSInteger)Method3:(id)anObject;"));
11207   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
11208             format("-(NSInteger)Method4:(id)anObject;"));
11209   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
11210             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
11211   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
11212             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
11213   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
11214             "forAllCells:(BOOL)flag;",
11215             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
11216                    "forAllCells:(BOOL)flag;"));
11217 
11218   // Very long objectiveC method declaration.
11219   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
11220                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
11221   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
11222                "                    inRange:(NSRange)range\n"
11223                "                   outRange:(NSRange)out_range\n"
11224                "                  outRange1:(NSRange)out_range1\n"
11225                "                  outRange2:(NSRange)out_range2\n"
11226                "                  outRange3:(NSRange)out_range3\n"
11227                "                  outRange4:(NSRange)out_range4\n"
11228                "                  outRange5:(NSRange)out_range5\n"
11229                "                  outRange6:(NSRange)out_range6\n"
11230                "                  outRange7:(NSRange)out_range7\n"
11231                "                  outRange8:(NSRange)out_range8\n"
11232                "                  outRange9:(NSRange)out_range9;");
11233 
11234   // When the function name has to be wrapped.
11235   FormatStyle Style = getLLVMStyle();
11236   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
11237   // and always indents instead.
11238   Style.IndentWrappedFunctionNames = false;
11239   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
11240                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
11241                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
11242                "}",
11243                Style);
11244   Style.IndentWrappedFunctionNames = true;
11245   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
11246                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
11247                "               anotherName:(NSString)dddddddddddddd {\n"
11248                "}",
11249                Style);
11250 
11251   verifyFormat("- (int)sum:(vector<int>)numbers;");
11252   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
11253   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
11254   // protocol lists (but not for template classes):
11255   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
11256 
11257   verifyFormat("- (int (*)())foo:(int (*)())f;");
11258   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
11259 
11260   // If there's no return type (very rare in practice!), LLVM and Google style
11261   // agree.
11262   verifyFormat("- foo;");
11263   verifyFormat("- foo:(int)f;");
11264   verifyGoogleFormat("- foo:(int)foo;");
11265 }
11266 
11267 TEST_F(FormatTest, BreaksStringLiterals) {
11268   EXPECT_EQ("\"some text \"\n"
11269             "\"other\";",
11270             format("\"some text other\";", getLLVMStyleWithColumns(12)));
11271   EXPECT_EQ("\"some text \"\n"
11272             "\"other\";",
11273             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
11274   EXPECT_EQ(
11275       "#define A  \\\n"
11276       "  \"some \"  \\\n"
11277       "  \"text \"  \\\n"
11278       "  \"other\";",
11279       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
11280   EXPECT_EQ(
11281       "#define A  \\\n"
11282       "  \"so \"    \\\n"
11283       "  \"text \"  \\\n"
11284       "  \"other\";",
11285       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
11286 
11287   EXPECT_EQ("\"some text\"",
11288             format("\"some text\"", getLLVMStyleWithColumns(1)));
11289   EXPECT_EQ("\"some text\"",
11290             format("\"some text\"", getLLVMStyleWithColumns(11)));
11291   EXPECT_EQ("\"some \"\n"
11292             "\"text\"",
11293             format("\"some text\"", getLLVMStyleWithColumns(10)));
11294   EXPECT_EQ("\"some \"\n"
11295             "\"text\"",
11296             format("\"some text\"", getLLVMStyleWithColumns(7)));
11297   EXPECT_EQ("\"some\"\n"
11298             "\" tex\"\n"
11299             "\"t\"",
11300             format("\"some text\"", getLLVMStyleWithColumns(6)));
11301   EXPECT_EQ("\"some\"\n"
11302             "\" tex\"\n"
11303             "\" and\"",
11304             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
11305   EXPECT_EQ("\"some\"\n"
11306             "\"/tex\"\n"
11307             "\"/and\"",
11308             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
11309 
11310   EXPECT_EQ("variable =\n"
11311             "    \"long string \"\n"
11312             "    \"literal\";",
11313             format("variable = \"long string literal\";",
11314                    getLLVMStyleWithColumns(20)));
11315 
11316   EXPECT_EQ("variable = f(\n"
11317             "    \"long string \"\n"
11318             "    \"literal\",\n"
11319             "    short,\n"
11320             "    loooooooooooooooooooong);",
11321             format("variable = f(\"long string literal\", short, "
11322                    "loooooooooooooooooooong);",
11323                    getLLVMStyleWithColumns(20)));
11324 
11325   EXPECT_EQ(
11326       "f(g(\"long string \"\n"
11327       "    \"literal\"),\n"
11328       "  b);",
11329       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
11330   EXPECT_EQ("f(g(\"long string \"\n"
11331             "    \"literal\",\n"
11332             "    a),\n"
11333             "  b);",
11334             format("f(g(\"long string literal\", a), b);",
11335                    getLLVMStyleWithColumns(20)));
11336   EXPECT_EQ(
11337       "f(\"one two\".split(\n"
11338       "    variable));",
11339       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
11340   EXPECT_EQ("f(\"one two three four five six \"\n"
11341             "  \"seven\".split(\n"
11342             "      really_looooong_variable));",
11343             format("f(\"one two three four five six seven\"."
11344                    "split(really_looooong_variable));",
11345                    getLLVMStyleWithColumns(33)));
11346 
11347   EXPECT_EQ("f(\"some \"\n"
11348             "  \"text\",\n"
11349             "  other);",
11350             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
11351 
11352   // Only break as a last resort.
11353   verifyFormat(
11354       "aaaaaaaaaaaaaaaaaaaa(\n"
11355       "    aaaaaaaaaaaaaaaaaaaa,\n"
11356       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
11357 
11358   EXPECT_EQ("\"splitmea\"\n"
11359             "\"trandomp\"\n"
11360             "\"oint\"",
11361             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
11362 
11363   EXPECT_EQ("\"split/\"\n"
11364             "\"pathat/\"\n"
11365             "\"slashes\"",
11366             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
11367 
11368   EXPECT_EQ("\"split/\"\n"
11369             "\"pathat/\"\n"
11370             "\"slashes\"",
11371             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
11372   EXPECT_EQ("\"split at \"\n"
11373             "\"spaces/at/\"\n"
11374             "\"slashes.at.any$\"\n"
11375             "\"non-alphanumeric%\"\n"
11376             "\"1111111111characte\"\n"
11377             "\"rs\"",
11378             format("\"split at "
11379                    "spaces/at/"
11380                    "slashes.at."
11381                    "any$non-"
11382                    "alphanumeric%"
11383                    "1111111111characte"
11384                    "rs\"",
11385                    getLLVMStyleWithColumns(20)));
11386 
11387   // Verify that splitting the strings understands
11388   // Style::AlwaysBreakBeforeMultilineStrings.
11389   EXPECT_EQ("aaaaaaaaaaaa(\n"
11390             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
11391             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
11392             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
11393                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
11394                    "aaaaaaaaaaaaaaaaaaaaaa\");",
11395                    getGoogleStyle()));
11396   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
11397             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
11398             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
11399                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
11400                    "aaaaaaaaaaaaaaaaaaaaaa\";",
11401                    getGoogleStyle()));
11402   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
11403             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
11404             format("llvm::outs() << "
11405                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
11406                    "aaaaaaaaaaaaaaaaaaa\";"));
11407   EXPECT_EQ("ffff(\n"
11408             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
11409             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
11410             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
11411                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
11412                    getGoogleStyle()));
11413 
11414   FormatStyle Style = getLLVMStyleWithColumns(12);
11415   Style.BreakStringLiterals = false;
11416   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
11417 
11418   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
11419   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
11420   EXPECT_EQ("#define A \\\n"
11421             "  \"some \" \\\n"
11422             "  \"text \" \\\n"
11423             "  \"other\";",
11424             format("#define A \"some text other\";", AlignLeft));
11425 }
11426 
11427 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
11428   EXPECT_EQ("C a = \"some more \"\n"
11429             "      \"text\";",
11430             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
11431 }
11432 
11433 TEST_F(FormatTest, FullyRemoveEmptyLines) {
11434   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
11435   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11436   EXPECT_EQ("int i = a(b());",
11437             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
11438 }
11439 
11440 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
11441   EXPECT_EQ(
11442       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
11443       "(\n"
11444       "    \"x\t\");",
11445       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
11446              "aaaaaaa("
11447              "\"x\t\");"));
11448 }
11449 
11450 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
11451   EXPECT_EQ(
11452       "u8\"utf8 string \"\n"
11453       "u8\"literal\";",
11454       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
11455   EXPECT_EQ(
11456       "u\"utf16 string \"\n"
11457       "u\"literal\";",
11458       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
11459   EXPECT_EQ(
11460       "U\"utf32 string \"\n"
11461       "U\"literal\";",
11462       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
11463   EXPECT_EQ("L\"wide string \"\n"
11464             "L\"literal\";",
11465             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
11466   EXPECT_EQ("@\"NSString \"\n"
11467             "@\"literal\";",
11468             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
11469   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
11470 
11471   // This input makes clang-format try to split the incomplete unicode escape
11472   // sequence, which used to lead to a crasher.
11473   verifyNoCrash(
11474       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
11475       getLLVMStyleWithColumns(60));
11476 }
11477 
11478 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
11479   FormatStyle Style = getGoogleStyleWithColumns(15);
11480   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
11481   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
11482   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
11483   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
11484   EXPECT_EQ("u8R\"x(raw literal)x\";",
11485             format("u8R\"x(raw literal)x\";", Style));
11486 }
11487 
11488 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
11489   FormatStyle Style = getLLVMStyleWithColumns(20);
11490   EXPECT_EQ(
11491       "_T(\"aaaaaaaaaaaaaa\")\n"
11492       "_T(\"aaaaaaaaaaaaaa\")\n"
11493       "_T(\"aaaaaaaaaaaa\")",
11494       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
11495   EXPECT_EQ("f(x,\n"
11496             "  _T(\"aaaaaaaaaaaa\")\n"
11497             "  _T(\"aaa\"),\n"
11498             "  z);",
11499             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
11500 
11501   // FIXME: Handle embedded spaces in one iteration.
11502   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
11503   //            "_T(\"aaaaaaaaaaaaa\")\n"
11504   //            "_T(\"aaaaaaaaaaaaa\")\n"
11505   //            "_T(\"a\")",
11506   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
11507   //                   getLLVMStyleWithColumns(20)));
11508   EXPECT_EQ(
11509       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
11510       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
11511   EXPECT_EQ("f(\n"
11512             "#if !TEST\n"
11513             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
11514             "#endif\n"
11515             ");",
11516             format("f(\n"
11517                    "#if !TEST\n"
11518                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
11519                    "#endif\n"
11520                    ");"));
11521   EXPECT_EQ("f(\n"
11522             "\n"
11523             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
11524             format("f(\n"
11525                    "\n"
11526                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
11527 }
11528 
11529 TEST_F(FormatTest, BreaksStringLiteralOperands) {
11530   // In a function call with two operands, the second can be broken with no line
11531   // break before it.
11532   EXPECT_EQ(
11533       "func(a, \"long long \"\n"
11534       "        \"long long\");",
11535       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
11536   // In a function call with three operands, the second must be broken with a
11537   // line break before it.
11538   EXPECT_EQ("func(a,\n"
11539             "     \"long long long \"\n"
11540             "     \"long\",\n"
11541             "     c);",
11542             format("func(a, \"long long long long\", c);",
11543                    getLLVMStyleWithColumns(24)));
11544   // In a function call with three operands, the third must be broken with a
11545   // line break before it.
11546   EXPECT_EQ("func(a, b,\n"
11547             "     \"long long long \"\n"
11548             "     \"long\");",
11549             format("func(a, b, \"long long long long\");",
11550                    getLLVMStyleWithColumns(24)));
11551   // In a function call with three operands, both the second and the third must
11552   // be broken with a line break before them.
11553   EXPECT_EQ("func(a,\n"
11554             "     \"long long long \"\n"
11555             "     \"long\",\n"
11556             "     \"long long long \"\n"
11557             "     \"long\");",
11558             format("func(a, \"long long long long\", \"long long long long\");",
11559                    getLLVMStyleWithColumns(24)));
11560   // In a chain of << with two operands, the second can be broken with no line
11561   // break before it.
11562   EXPECT_EQ("a << \"line line \"\n"
11563             "     \"line\";",
11564             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
11565   // In a chain of << with three operands, the second can be broken with no line
11566   // break before it.
11567   EXPECT_EQ(
11568       "abcde << \"line \"\n"
11569       "         \"line line\"\n"
11570       "      << c;",
11571       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
11572   // In a chain of << with three operands, the third must be broken with a line
11573   // break before it.
11574   EXPECT_EQ(
11575       "a << b\n"
11576       "  << \"line line \"\n"
11577       "     \"line\";",
11578       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
11579   // In a chain of << with three operands, the second can be broken with no line
11580   // break before it and the third must be broken with a line break before it.
11581   EXPECT_EQ("abcd << \"line line \"\n"
11582             "        \"line\"\n"
11583             "     << \"line line \"\n"
11584             "        \"line\";",
11585             format("abcd << \"line line line\" << \"line line line\";",
11586                    getLLVMStyleWithColumns(20)));
11587   // In a chain of binary operators with two operands, the second can be broken
11588   // with no line break before it.
11589   EXPECT_EQ(
11590       "abcd + \"line line \"\n"
11591       "       \"line line\";",
11592       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
11593   // In a chain of binary operators with three operands, the second must be
11594   // broken with a line break before it.
11595   EXPECT_EQ("abcd +\n"
11596             "    \"line line \"\n"
11597             "    \"line line\" +\n"
11598             "    e;",
11599             format("abcd + \"line line line line\" + e;",
11600                    getLLVMStyleWithColumns(20)));
11601   // In a function call with two operands, with AlignAfterOpenBracket enabled,
11602   // the first must be broken with a line break before it.
11603   FormatStyle Style = getLLVMStyleWithColumns(25);
11604   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
11605   EXPECT_EQ("someFunction(\n"
11606             "    \"long long long \"\n"
11607             "    \"long\",\n"
11608             "    a);",
11609             format("someFunction(\"long long long long\", a);", Style));
11610 }
11611 
11612 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
11613   EXPECT_EQ(
11614       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11615       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11616       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
11617       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11618              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11619              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
11620 }
11621 
11622 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
11623   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
11624             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
11625   EXPECT_EQ("fffffffffff(g(R\"x(\n"
11626             "multiline raw string literal xxxxxxxxxxxxxx\n"
11627             ")x\",\n"
11628             "              a),\n"
11629             "            b);",
11630             format("fffffffffff(g(R\"x(\n"
11631                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11632                    ")x\", a), b);",
11633                    getGoogleStyleWithColumns(20)));
11634   EXPECT_EQ("fffffffffff(\n"
11635             "    g(R\"x(qqq\n"
11636             "multiline raw string literal xxxxxxxxxxxxxx\n"
11637             ")x\",\n"
11638             "      a),\n"
11639             "    b);",
11640             format("fffffffffff(g(R\"x(qqq\n"
11641                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11642                    ")x\", a), b);",
11643                    getGoogleStyleWithColumns(20)));
11644 
11645   EXPECT_EQ("fffffffffff(R\"x(\n"
11646             "multiline raw string literal xxxxxxxxxxxxxx\n"
11647             ")x\");",
11648             format("fffffffffff(R\"x(\n"
11649                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11650                    ")x\");",
11651                    getGoogleStyleWithColumns(20)));
11652   EXPECT_EQ("fffffffffff(R\"x(\n"
11653             "multiline raw string literal xxxxxxxxxxxxxx\n"
11654             ")x\" + bbbbbb);",
11655             format("fffffffffff(R\"x(\n"
11656                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11657                    ")x\" +   bbbbbb);",
11658                    getGoogleStyleWithColumns(20)));
11659   EXPECT_EQ("fffffffffff(\n"
11660             "    R\"x(\n"
11661             "multiline raw string literal xxxxxxxxxxxxxx\n"
11662             ")x\" +\n"
11663             "    bbbbbb);",
11664             format("fffffffffff(\n"
11665                    " R\"x(\n"
11666                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11667                    ")x\" + bbbbbb);",
11668                    getGoogleStyleWithColumns(20)));
11669   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
11670             format("fffffffffff(\n"
11671                    " R\"(single line raw string)\" + bbbbbb);"));
11672 }
11673 
11674 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
11675   verifyFormat("string a = \"unterminated;");
11676   EXPECT_EQ("function(\"unterminated,\n"
11677             "         OtherParameter);",
11678             format("function(  \"unterminated,\n"
11679                    "    OtherParameter);"));
11680 }
11681 
11682 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
11683   FormatStyle Style = getLLVMStyle();
11684   Style.Standard = FormatStyle::LS_Cpp03;
11685   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
11686             format("#define x(_a) printf(\"foo\"_a);", Style));
11687 }
11688 
11689 TEST_F(FormatTest, CppLexVersion) {
11690   FormatStyle Style = getLLVMStyle();
11691   // Formatting of x * y differs if x is a type.
11692   verifyFormat("void foo() { MACRO(a * b); }", Style);
11693   verifyFormat("void foo() { MACRO(int *b); }", Style);
11694 
11695   // LLVM style uses latest lexer.
11696   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
11697   Style.Standard = FormatStyle::LS_Cpp17;
11698   // But in c++17, char8_t isn't a keyword.
11699   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
11700 }
11701 
11702 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
11703 
11704 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
11705   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
11706             "             \"ddeeefff\");",
11707             format("someFunction(\"aaabbbcccdddeeefff\");",
11708                    getLLVMStyleWithColumns(25)));
11709   EXPECT_EQ("someFunction1234567890(\n"
11710             "    \"aaabbbcccdddeeefff\");",
11711             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
11712                    getLLVMStyleWithColumns(26)));
11713   EXPECT_EQ("someFunction1234567890(\n"
11714             "    \"aaabbbcccdddeeeff\"\n"
11715             "    \"f\");",
11716             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
11717                    getLLVMStyleWithColumns(25)));
11718   EXPECT_EQ("someFunction1234567890(\n"
11719             "    \"aaabbbcccdddeeeff\"\n"
11720             "    \"f\");",
11721             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
11722                    getLLVMStyleWithColumns(24)));
11723   EXPECT_EQ("someFunction(\n"
11724             "    \"aaabbbcc ddde \"\n"
11725             "    \"efff\");",
11726             format("someFunction(\"aaabbbcc ddde efff\");",
11727                    getLLVMStyleWithColumns(25)));
11728   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
11729             "             \"ddeeefff\");",
11730             format("someFunction(\"aaabbbccc ddeeefff\");",
11731                    getLLVMStyleWithColumns(25)));
11732   EXPECT_EQ("someFunction1234567890(\n"
11733             "    \"aaabb \"\n"
11734             "    \"cccdddeeefff\");",
11735             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
11736                    getLLVMStyleWithColumns(25)));
11737   EXPECT_EQ("#define A          \\\n"
11738             "  string s =       \\\n"
11739             "      \"123456789\"  \\\n"
11740             "      \"0\";         \\\n"
11741             "  int i;",
11742             format("#define A string s = \"1234567890\"; int i;",
11743                    getLLVMStyleWithColumns(20)));
11744   EXPECT_EQ("someFunction(\n"
11745             "    \"aaabbbcc \"\n"
11746             "    \"dddeeefff\");",
11747             format("someFunction(\"aaabbbcc dddeeefff\");",
11748                    getLLVMStyleWithColumns(25)));
11749 }
11750 
11751 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
11752   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
11753   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
11754   EXPECT_EQ("\"test\"\n"
11755             "\"\\n\"",
11756             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
11757   EXPECT_EQ("\"tes\\\\\"\n"
11758             "\"n\"",
11759             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
11760   EXPECT_EQ("\"\\\\\\\\\"\n"
11761             "\"\\n\"",
11762             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
11763   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
11764   EXPECT_EQ("\"\\uff01\"\n"
11765             "\"test\"",
11766             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
11767   EXPECT_EQ("\"\\Uff01ff02\"",
11768             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
11769   EXPECT_EQ("\"\\x000000000001\"\n"
11770             "\"next\"",
11771             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
11772   EXPECT_EQ("\"\\x000000000001next\"",
11773             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
11774   EXPECT_EQ("\"\\x000000000001\"",
11775             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
11776   EXPECT_EQ("\"test\"\n"
11777             "\"\\000000\"\n"
11778             "\"000001\"",
11779             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
11780   EXPECT_EQ("\"test\\000\"\n"
11781             "\"00000000\"\n"
11782             "\"1\"",
11783             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
11784 }
11785 
11786 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
11787   verifyFormat("void f() {\n"
11788                "  return g() {}\n"
11789                "  void h() {}");
11790   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
11791                "g();\n"
11792                "}");
11793 }
11794 
11795 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
11796   verifyFormat(
11797       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
11798 }
11799 
11800 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
11801   verifyFormat("class X {\n"
11802                "  void f() {\n"
11803                "  }\n"
11804                "};",
11805                getLLVMStyleWithColumns(12));
11806 }
11807 
11808 TEST_F(FormatTest, ConfigurableIndentWidth) {
11809   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
11810   EightIndent.IndentWidth = 8;
11811   EightIndent.ContinuationIndentWidth = 8;
11812   verifyFormat("void f() {\n"
11813                "        someFunction();\n"
11814                "        if (true) {\n"
11815                "                f();\n"
11816                "        }\n"
11817                "}",
11818                EightIndent);
11819   verifyFormat("class X {\n"
11820                "        void f() {\n"
11821                "        }\n"
11822                "};",
11823                EightIndent);
11824   verifyFormat("int x[] = {\n"
11825                "        call(),\n"
11826                "        call()};",
11827                EightIndent);
11828 }
11829 
11830 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
11831   verifyFormat("double\n"
11832                "f();",
11833                getLLVMStyleWithColumns(8));
11834 }
11835 
11836 TEST_F(FormatTest, ConfigurableUseOfTab) {
11837   FormatStyle Tab = getLLVMStyleWithColumns(42);
11838   Tab.IndentWidth = 8;
11839   Tab.UseTab = FormatStyle::UT_Always;
11840   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
11841 
11842   EXPECT_EQ("if (aaaaaaaa && // q\n"
11843             "    bb)\t\t// w\n"
11844             "\t;",
11845             format("if (aaaaaaaa &&// q\n"
11846                    "bb)// w\n"
11847                    ";",
11848                    Tab));
11849   EXPECT_EQ("if (aaa && bbb) // w\n"
11850             "\t;",
11851             format("if(aaa&&bbb)// w\n"
11852                    ";",
11853                    Tab));
11854 
11855   verifyFormat("class X {\n"
11856                "\tvoid f() {\n"
11857                "\t\tsomeFunction(parameter1,\n"
11858                "\t\t\t     parameter2);\n"
11859                "\t}\n"
11860                "};",
11861                Tab);
11862   verifyFormat("#define A                        \\\n"
11863                "\tvoid f() {               \\\n"
11864                "\t\tsomeFunction(    \\\n"
11865                "\t\t    parameter1,  \\\n"
11866                "\t\t    parameter2); \\\n"
11867                "\t}",
11868                Tab);
11869   verifyFormat("int a;\t      // x\n"
11870                "int bbbbbbbb; // x\n",
11871                Tab);
11872 
11873   Tab.TabWidth = 4;
11874   Tab.IndentWidth = 8;
11875   verifyFormat("class TabWidth4Indent8 {\n"
11876                "\t\tvoid f() {\n"
11877                "\t\t\t\tsomeFunction(parameter1,\n"
11878                "\t\t\t\t\t\t\t parameter2);\n"
11879                "\t\t}\n"
11880                "};",
11881                Tab);
11882 
11883   Tab.TabWidth = 4;
11884   Tab.IndentWidth = 4;
11885   verifyFormat("class TabWidth4Indent4 {\n"
11886                "\tvoid f() {\n"
11887                "\t\tsomeFunction(parameter1,\n"
11888                "\t\t\t\t\t parameter2);\n"
11889                "\t}\n"
11890                "};",
11891                Tab);
11892 
11893   Tab.TabWidth = 8;
11894   Tab.IndentWidth = 4;
11895   verifyFormat("class TabWidth8Indent4 {\n"
11896                "    void f() {\n"
11897                "\tsomeFunction(parameter1,\n"
11898                "\t\t     parameter2);\n"
11899                "    }\n"
11900                "};",
11901                Tab);
11902 
11903   Tab.TabWidth = 8;
11904   Tab.IndentWidth = 8;
11905   EXPECT_EQ("/*\n"
11906             "\t      a\t\tcomment\n"
11907             "\t      in multiple lines\n"
11908             "       */",
11909             format("   /*\t \t \n"
11910                    " \t \t a\t\tcomment\t \t\n"
11911                    " \t \t in multiple lines\t\n"
11912                    " \t  */",
11913                    Tab));
11914 
11915   Tab.UseTab = FormatStyle::UT_ForIndentation;
11916   verifyFormat("{\n"
11917                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11918                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11919                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11920                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11921                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11922                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11923                "};",
11924                Tab);
11925   verifyFormat("enum AA {\n"
11926                "\ta1, // Force multiple lines\n"
11927                "\ta2,\n"
11928                "\ta3\n"
11929                "};",
11930                Tab);
11931   EXPECT_EQ("if (aaaaaaaa && // q\n"
11932             "    bb)         // w\n"
11933             "\t;",
11934             format("if (aaaaaaaa &&// q\n"
11935                    "bb)// w\n"
11936                    ";",
11937                    Tab));
11938   verifyFormat("class X {\n"
11939                "\tvoid f() {\n"
11940                "\t\tsomeFunction(parameter1,\n"
11941                "\t\t             parameter2);\n"
11942                "\t}\n"
11943                "};",
11944                Tab);
11945   verifyFormat("{\n"
11946                "\tQ(\n"
11947                "\t    {\n"
11948                "\t\t    int a;\n"
11949                "\t\t    someFunction(aaaaaaaa,\n"
11950                "\t\t                 bbbbbbb);\n"
11951                "\t    },\n"
11952                "\t    p);\n"
11953                "}",
11954                Tab);
11955   EXPECT_EQ("{\n"
11956             "\t/* aaaa\n"
11957             "\t   bbbb */\n"
11958             "}",
11959             format("{\n"
11960                    "/* aaaa\n"
11961                    "   bbbb */\n"
11962                    "}",
11963                    Tab));
11964   EXPECT_EQ("{\n"
11965             "\t/*\n"
11966             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11967             "\t  bbbbbbbbbbbbb\n"
11968             "\t*/\n"
11969             "}",
11970             format("{\n"
11971                    "/*\n"
11972                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11973                    "*/\n"
11974                    "}",
11975                    Tab));
11976   EXPECT_EQ("{\n"
11977             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11978             "\t// bbbbbbbbbbbbb\n"
11979             "}",
11980             format("{\n"
11981                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11982                    "}",
11983                    Tab));
11984   EXPECT_EQ("{\n"
11985             "\t/*\n"
11986             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11987             "\t  bbbbbbbbbbbbb\n"
11988             "\t*/\n"
11989             "}",
11990             format("{\n"
11991                    "\t/*\n"
11992                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11993                    "\t*/\n"
11994                    "}",
11995                    Tab));
11996   EXPECT_EQ("{\n"
11997             "\t/*\n"
11998             "\n"
11999             "\t*/\n"
12000             "}",
12001             format("{\n"
12002                    "\t/*\n"
12003                    "\n"
12004                    "\t*/\n"
12005                    "}",
12006                    Tab));
12007   EXPECT_EQ("{\n"
12008             "\t/*\n"
12009             " asdf\n"
12010             "\t*/\n"
12011             "}",
12012             format("{\n"
12013                    "\t/*\n"
12014                    " asdf\n"
12015                    "\t*/\n"
12016                    "}",
12017                    Tab));
12018 
12019   Tab.UseTab = FormatStyle::UT_Never;
12020   EXPECT_EQ("/*\n"
12021             "              a\t\tcomment\n"
12022             "              in multiple lines\n"
12023             "       */",
12024             format("   /*\t \t \n"
12025                    " \t \t a\t\tcomment\t \t\n"
12026                    " \t \t in multiple lines\t\n"
12027                    " \t  */",
12028                    Tab));
12029   EXPECT_EQ("/* some\n"
12030             "   comment */",
12031             format(" \t \t /* some\n"
12032                    " \t \t    comment */",
12033                    Tab));
12034   EXPECT_EQ("int a; /* some\n"
12035             "   comment */",
12036             format(" \t \t int a; /* some\n"
12037                    " \t \t    comment */",
12038                    Tab));
12039 
12040   EXPECT_EQ("int a; /* some\n"
12041             "comment */",
12042             format(" \t \t int\ta; /* some\n"
12043                    " \t \t    comment */",
12044                    Tab));
12045   EXPECT_EQ("f(\"\t\t\"); /* some\n"
12046             "    comment */",
12047             format(" \t \t f(\"\t\t\"); /* some\n"
12048                    " \t \t    comment */",
12049                    Tab));
12050   EXPECT_EQ("{\n"
12051             "        /*\n"
12052             "         * Comment\n"
12053             "         */\n"
12054             "        int i;\n"
12055             "}",
12056             format("{\n"
12057                    "\t/*\n"
12058                    "\t * Comment\n"
12059                    "\t */\n"
12060                    "\t int i;\n"
12061                    "}",
12062                    Tab));
12063 
12064   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
12065   Tab.TabWidth = 8;
12066   Tab.IndentWidth = 8;
12067   EXPECT_EQ("if (aaaaaaaa && // q\n"
12068             "    bb)         // w\n"
12069             "\t;",
12070             format("if (aaaaaaaa &&// q\n"
12071                    "bb)// w\n"
12072                    ";",
12073                    Tab));
12074   EXPECT_EQ("if (aaa && bbb) // w\n"
12075             "\t;",
12076             format("if(aaa&&bbb)// w\n"
12077                    ";",
12078                    Tab));
12079   verifyFormat("class X {\n"
12080                "\tvoid f() {\n"
12081                "\t\tsomeFunction(parameter1,\n"
12082                "\t\t\t     parameter2);\n"
12083                "\t}\n"
12084                "};",
12085                Tab);
12086   verifyFormat("#define A                        \\\n"
12087                "\tvoid f() {               \\\n"
12088                "\t\tsomeFunction(    \\\n"
12089                "\t\t    parameter1,  \\\n"
12090                "\t\t    parameter2); \\\n"
12091                "\t}",
12092                Tab);
12093   Tab.TabWidth = 4;
12094   Tab.IndentWidth = 8;
12095   verifyFormat("class TabWidth4Indent8 {\n"
12096                "\t\tvoid f() {\n"
12097                "\t\t\t\tsomeFunction(parameter1,\n"
12098                "\t\t\t\t\t\t\t parameter2);\n"
12099                "\t\t}\n"
12100                "};",
12101                Tab);
12102   Tab.TabWidth = 4;
12103   Tab.IndentWidth = 4;
12104   verifyFormat("class TabWidth4Indent4 {\n"
12105                "\tvoid f() {\n"
12106                "\t\tsomeFunction(parameter1,\n"
12107                "\t\t\t\t\t parameter2);\n"
12108                "\t}\n"
12109                "};",
12110                Tab);
12111   Tab.TabWidth = 8;
12112   Tab.IndentWidth = 4;
12113   verifyFormat("class TabWidth8Indent4 {\n"
12114                "    void f() {\n"
12115                "\tsomeFunction(parameter1,\n"
12116                "\t\t     parameter2);\n"
12117                "    }\n"
12118                "};",
12119                Tab);
12120   Tab.TabWidth = 8;
12121   Tab.IndentWidth = 8;
12122   EXPECT_EQ("/*\n"
12123             "\t      a\t\tcomment\n"
12124             "\t      in multiple lines\n"
12125             "       */",
12126             format("   /*\t \t \n"
12127                    " \t \t a\t\tcomment\t \t\n"
12128                    " \t \t in multiple lines\t\n"
12129                    " \t  */",
12130                    Tab));
12131   verifyFormat("{\n"
12132                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12133                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12134                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12135                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12136                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12137                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12138                "};",
12139                Tab);
12140   verifyFormat("enum AA {\n"
12141                "\ta1, // Force multiple lines\n"
12142                "\ta2,\n"
12143                "\ta3\n"
12144                "};",
12145                Tab);
12146   EXPECT_EQ("if (aaaaaaaa && // q\n"
12147             "    bb)         // w\n"
12148             "\t;",
12149             format("if (aaaaaaaa &&// q\n"
12150                    "bb)// w\n"
12151                    ";",
12152                    Tab));
12153   verifyFormat("class X {\n"
12154                "\tvoid f() {\n"
12155                "\t\tsomeFunction(parameter1,\n"
12156                "\t\t\t     parameter2);\n"
12157                "\t}\n"
12158                "};",
12159                Tab);
12160   verifyFormat("{\n"
12161                "\tQ(\n"
12162                "\t    {\n"
12163                "\t\t    int a;\n"
12164                "\t\t    someFunction(aaaaaaaa,\n"
12165                "\t\t\t\t bbbbbbb);\n"
12166                "\t    },\n"
12167                "\t    p);\n"
12168                "}",
12169                Tab);
12170   EXPECT_EQ("{\n"
12171             "\t/* aaaa\n"
12172             "\t   bbbb */\n"
12173             "}",
12174             format("{\n"
12175                    "/* aaaa\n"
12176                    "   bbbb */\n"
12177                    "}",
12178                    Tab));
12179   EXPECT_EQ("{\n"
12180             "\t/*\n"
12181             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12182             "\t  bbbbbbbbbbbbb\n"
12183             "\t*/\n"
12184             "}",
12185             format("{\n"
12186                    "/*\n"
12187                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12188                    "*/\n"
12189                    "}",
12190                    Tab));
12191   EXPECT_EQ("{\n"
12192             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12193             "\t// bbbbbbbbbbbbb\n"
12194             "}",
12195             format("{\n"
12196                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12197                    "}",
12198                    Tab));
12199   EXPECT_EQ("{\n"
12200             "\t/*\n"
12201             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12202             "\t  bbbbbbbbbbbbb\n"
12203             "\t*/\n"
12204             "}",
12205             format("{\n"
12206                    "\t/*\n"
12207                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12208                    "\t*/\n"
12209                    "}",
12210                    Tab));
12211   EXPECT_EQ("{\n"
12212             "\t/*\n"
12213             "\n"
12214             "\t*/\n"
12215             "}",
12216             format("{\n"
12217                    "\t/*\n"
12218                    "\n"
12219                    "\t*/\n"
12220                    "}",
12221                    Tab));
12222   EXPECT_EQ("{\n"
12223             "\t/*\n"
12224             " asdf\n"
12225             "\t*/\n"
12226             "}",
12227             format("{\n"
12228                    "\t/*\n"
12229                    " asdf\n"
12230                    "\t*/\n"
12231                    "}",
12232                    Tab));
12233   EXPECT_EQ("/* some\n"
12234             "   comment */",
12235             format(" \t \t /* some\n"
12236                    " \t \t    comment */",
12237                    Tab));
12238   EXPECT_EQ("int a; /* some\n"
12239             "   comment */",
12240             format(" \t \t int a; /* some\n"
12241                    " \t \t    comment */",
12242                    Tab));
12243   EXPECT_EQ("int a; /* some\n"
12244             "comment */",
12245             format(" \t \t int\ta; /* some\n"
12246                    " \t \t    comment */",
12247                    Tab));
12248   EXPECT_EQ("f(\"\t\t\"); /* some\n"
12249             "    comment */",
12250             format(" \t \t f(\"\t\t\"); /* some\n"
12251                    " \t \t    comment */",
12252                    Tab));
12253   EXPECT_EQ("{\n"
12254             "\t/*\n"
12255             "\t * Comment\n"
12256             "\t */\n"
12257             "\tint i;\n"
12258             "}",
12259             format("{\n"
12260                    "\t/*\n"
12261                    "\t * Comment\n"
12262                    "\t */\n"
12263                    "\t int i;\n"
12264                    "}",
12265                    Tab));
12266   Tab.TabWidth = 2;
12267   Tab.IndentWidth = 2;
12268   EXPECT_EQ("{\n"
12269             "\t/* aaaa\n"
12270             "\t\t bbbb */\n"
12271             "}",
12272             format("{\n"
12273                    "/* aaaa\n"
12274                    "\t bbbb */\n"
12275                    "}",
12276                    Tab));
12277   EXPECT_EQ("{\n"
12278             "\t/*\n"
12279             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12280             "\t\tbbbbbbbbbbbbb\n"
12281             "\t*/\n"
12282             "}",
12283             format("{\n"
12284                    "/*\n"
12285                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12286                    "*/\n"
12287                    "}",
12288                    Tab));
12289   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
12290   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
12291   Tab.TabWidth = 4;
12292   Tab.IndentWidth = 4;
12293   verifyFormat("class Assign {\n"
12294                "\tvoid f() {\n"
12295                "\t\tint         x      = 123;\n"
12296                "\t\tint         random = 4;\n"
12297                "\t\tstd::string alphabet =\n"
12298                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
12299                "\t}\n"
12300                "};",
12301                Tab);
12302 
12303   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
12304   Tab.TabWidth = 8;
12305   Tab.IndentWidth = 8;
12306   EXPECT_EQ("if (aaaaaaaa && // q\n"
12307             "    bb)         // w\n"
12308             "\t;",
12309             format("if (aaaaaaaa &&// q\n"
12310                    "bb)// w\n"
12311                    ";",
12312                    Tab));
12313   EXPECT_EQ("if (aaa && bbb) // w\n"
12314             "\t;",
12315             format("if(aaa&&bbb)// w\n"
12316                    ";",
12317                    Tab));
12318   verifyFormat("class X {\n"
12319                "\tvoid f() {\n"
12320                "\t\tsomeFunction(parameter1,\n"
12321                "\t\t             parameter2);\n"
12322                "\t}\n"
12323                "};",
12324                Tab);
12325   verifyFormat("#define A                        \\\n"
12326                "\tvoid f() {               \\\n"
12327                "\t\tsomeFunction(    \\\n"
12328                "\t\t    parameter1,  \\\n"
12329                "\t\t    parameter2); \\\n"
12330                "\t}",
12331                Tab);
12332   Tab.TabWidth = 4;
12333   Tab.IndentWidth = 8;
12334   verifyFormat("class TabWidth4Indent8 {\n"
12335                "\t\tvoid f() {\n"
12336                "\t\t\t\tsomeFunction(parameter1,\n"
12337                "\t\t\t\t             parameter2);\n"
12338                "\t\t}\n"
12339                "};",
12340                Tab);
12341   Tab.TabWidth = 4;
12342   Tab.IndentWidth = 4;
12343   verifyFormat("class TabWidth4Indent4 {\n"
12344                "\tvoid f() {\n"
12345                "\t\tsomeFunction(parameter1,\n"
12346                "\t\t             parameter2);\n"
12347                "\t}\n"
12348                "};",
12349                Tab);
12350   Tab.TabWidth = 8;
12351   Tab.IndentWidth = 4;
12352   verifyFormat("class TabWidth8Indent4 {\n"
12353                "    void f() {\n"
12354                "\tsomeFunction(parameter1,\n"
12355                "\t             parameter2);\n"
12356                "    }\n"
12357                "};",
12358                Tab);
12359   Tab.TabWidth = 8;
12360   Tab.IndentWidth = 8;
12361   EXPECT_EQ("/*\n"
12362             "              a\t\tcomment\n"
12363             "              in multiple lines\n"
12364             "       */",
12365             format("   /*\t \t \n"
12366                    " \t \t a\t\tcomment\t \t\n"
12367                    " \t \t in multiple lines\t\n"
12368                    " \t  */",
12369                    Tab));
12370   verifyFormat("{\n"
12371                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12372                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12373                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12374                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12375                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12376                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12377                "};",
12378                Tab);
12379   verifyFormat("enum AA {\n"
12380                "\ta1, // Force multiple lines\n"
12381                "\ta2,\n"
12382                "\ta3\n"
12383                "};",
12384                Tab);
12385   EXPECT_EQ("if (aaaaaaaa && // q\n"
12386             "    bb)         // w\n"
12387             "\t;",
12388             format("if (aaaaaaaa &&// q\n"
12389                    "bb)// w\n"
12390                    ";",
12391                    Tab));
12392   verifyFormat("class X {\n"
12393                "\tvoid f() {\n"
12394                "\t\tsomeFunction(parameter1,\n"
12395                "\t\t             parameter2);\n"
12396                "\t}\n"
12397                "};",
12398                Tab);
12399   verifyFormat("{\n"
12400                "\tQ(\n"
12401                "\t    {\n"
12402                "\t\t    int a;\n"
12403                "\t\t    someFunction(aaaaaaaa,\n"
12404                "\t\t                 bbbbbbb);\n"
12405                "\t    },\n"
12406                "\t    p);\n"
12407                "}",
12408                Tab);
12409   EXPECT_EQ("{\n"
12410             "\t/* aaaa\n"
12411             "\t   bbbb */\n"
12412             "}",
12413             format("{\n"
12414                    "/* aaaa\n"
12415                    "   bbbb */\n"
12416                    "}",
12417                    Tab));
12418   EXPECT_EQ("{\n"
12419             "\t/*\n"
12420             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12421             "\t  bbbbbbbbbbbbb\n"
12422             "\t*/\n"
12423             "}",
12424             format("{\n"
12425                    "/*\n"
12426                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12427                    "*/\n"
12428                    "}",
12429                    Tab));
12430   EXPECT_EQ("{\n"
12431             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12432             "\t// bbbbbbbbbbbbb\n"
12433             "}",
12434             format("{\n"
12435                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12436                    "}",
12437                    Tab));
12438   EXPECT_EQ("{\n"
12439             "\t/*\n"
12440             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12441             "\t  bbbbbbbbbbbbb\n"
12442             "\t*/\n"
12443             "}",
12444             format("{\n"
12445                    "\t/*\n"
12446                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12447                    "\t*/\n"
12448                    "}",
12449                    Tab));
12450   EXPECT_EQ("{\n"
12451             "\t/*\n"
12452             "\n"
12453             "\t*/\n"
12454             "}",
12455             format("{\n"
12456                    "\t/*\n"
12457                    "\n"
12458                    "\t*/\n"
12459                    "}",
12460                    Tab));
12461   EXPECT_EQ("{\n"
12462             "\t/*\n"
12463             " asdf\n"
12464             "\t*/\n"
12465             "}",
12466             format("{\n"
12467                    "\t/*\n"
12468                    " asdf\n"
12469                    "\t*/\n"
12470                    "}",
12471                    Tab));
12472   EXPECT_EQ("/* some\n"
12473             "   comment */",
12474             format(" \t \t /* some\n"
12475                    " \t \t    comment */",
12476                    Tab));
12477   EXPECT_EQ("int a; /* some\n"
12478             "   comment */",
12479             format(" \t \t int a; /* some\n"
12480                    " \t \t    comment */",
12481                    Tab));
12482   EXPECT_EQ("int a; /* some\n"
12483             "comment */",
12484             format(" \t \t int\ta; /* some\n"
12485                    " \t \t    comment */",
12486                    Tab));
12487   EXPECT_EQ("f(\"\t\t\"); /* some\n"
12488             "    comment */",
12489             format(" \t \t f(\"\t\t\"); /* some\n"
12490                    " \t \t    comment */",
12491                    Tab));
12492   EXPECT_EQ("{\n"
12493             "\t/*\n"
12494             "\t * Comment\n"
12495             "\t */\n"
12496             "\tint i;\n"
12497             "}",
12498             format("{\n"
12499                    "\t/*\n"
12500                    "\t * Comment\n"
12501                    "\t */\n"
12502                    "\t int i;\n"
12503                    "}",
12504                    Tab));
12505   Tab.TabWidth = 2;
12506   Tab.IndentWidth = 2;
12507   EXPECT_EQ("{\n"
12508             "\t/* aaaa\n"
12509             "\t   bbbb */\n"
12510             "}",
12511             format("{\n"
12512                    "/* aaaa\n"
12513                    "   bbbb */\n"
12514                    "}",
12515                    Tab));
12516   EXPECT_EQ("{\n"
12517             "\t/*\n"
12518             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12519             "\t  bbbbbbbbbbbbb\n"
12520             "\t*/\n"
12521             "}",
12522             format("{\n"
12523                    "/*\n"
12524                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12525                    "*/\n"
12526                    "}",
12527                    Tab));
12528   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
12529   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
12530   Tab.TabWidth = 4;
12531   Tab.IndentWidth = 4;
12532   verifyFormat("class Assign {\n"
12533                "\tvoid f() {\n"
12534                "\t\tint         x      = 123;\n"
12535                "\t\tint         random = 4;\n"
12536                "\t\tstd::string alphabet =\n"
12537                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
12538                "\t}\n"
12539                "};",
12540                Tab);
12541   Tab.AlignOperands = FormatStyle::OAS_Align;
12542   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
12543                "                 cccccccccccccccccccc;",
12544                Tab);
12545   // no alignment
12546   verifyFormat("int aaaaaaaaaa =\n"
12547                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
12548                Tab);
12549   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
12550                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
12551                "                        : 333333333333333;",
12552                Tab);
12553   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
12554   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
12555   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
12556                "               + cccccccccccccccccccc;",
12557                Tab);
12558 }
12559 
12560 TEST_F(FormatTest, ZeroTabWidth) {
12561   FormatStyle Tab = getLLVMStyleWithColumns(42);
12562   Tab.IndentWidth = 8;
12563   Tab.UseTab = FormatStyle::UT_Never;
12564   Tab.TabWidth = 0;
12565   EXPECT_EQ("void a(){\n"
12566             "    // line starts with '\t'\n"
12567             "};",
12568             format("void a(){\n"
12569                    "\t// line starts with '\t'\n"
12570                    "};",
12571                    Tab));
12572 
12573   EXPECT_EQ("void a(){\n"
12574             "    // line starts with '\t'\n"
12575             "};",
12576             format("void a(){\n"
12577                    "\t\t// line starts with '\t'\n"
12578                    "};",
12579                    Tab));
12580 
12581   Tab.UseTab = FormatStyle::UT_ForIndentation;
12582   EXPECT_EQ("void a(){\n"
12583             "    // line starts with '\t'\n"
12584             "};",
12585             format("void a(){\n"
12586                    "\t// line starts with '\t'\n"
12587                    "};",
12588                    Tab));
12589 
12590   EXPECT_EQ("void a(){\n"
12591             "    // line starts with '\t'\n"
12592             "};",
12593             format("void a(){\n"
12594                    "\t\t// line starts with '\t'\n"
12595                    "};",
12596                    Tab));
12597 
12598   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
12599   EXPECT_EQ("void a(){\n"
12600             "    // line starts with '\t'\n"
12601             "};",
12602             format("void a(){\n"
12603                    "\t// line starts with '\t'\n"
12604                    "};",
12605                    Tab));
12606 
12607   EXPECT_EQ("void a(){\n"
12608             "    // line starts with '\t'\n"
12609             "};",
12610             format("void a(){\n"
12611                    "\t\t// line starts with '\t'\n"
12612                    "};",
12613                    Tab));
12614 
12615   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
12616   EXPECT_EQ("void a(){\n"
12617             "    // line starts with '\t'\n"
12618             "};",
12619             format("void a(){\n"
12620                    "\t// line starts with '\t'\n"
12621                    "};",
12622                    Tab));
12623 
12624   EXPECT_EQ("void a(){\n"
12625             "    // line starts with '\t'\n"
12626             "};",
12627             format("void a(){\n"
12628                    "\t\t// line starts with '\t'\n"
12629                    "};",
12630                    Tab));
12631 
12632   Tab.UseTab = FormatStyle::UT_Always;
12633   EXPECT_EQ("void a(){\n"
12634             "// line starts with '\t'\n"
12635             "};",
12636             format("void a(){\n"
12637                    "\t// line starts with '\t'\n"
12638                    "};",
12639                    Tab));
12640 
12641   EXPECT_EQ("void a(){\n"
12642             "// line starts with '\t'\n"
12643             "};",
12644             format("void a(){\n"
12645                    "\t\t// line starts with '\t'\n"
12646                    "};",
12647                    Tab));
12648 }
12649 
12650 TEST_F(FormatTest, CalculatesOriginalColumn) {
12651   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12652             "q\"; /* some\n"
12653             "       comment */",
12654             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12655                    "q\"; /* some\n"
12656                    "       comment */",
12657                    getLLVMStyle()));
12658   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
12659             "/* some\n"
12660             "   comment */",
12661             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
12662                    " /* some\n"
12663                    "    comment */",
12664                    getLLVMStyle()));
12665   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12666             "qqq\n"
12667             "/* some\n"
12668             "   comment */",
12669             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12670                    "qqq\n"
12671                    " /* some\n"
12672                    "    comment */",
12673                    getLLVMStyle()));
12674   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12675             "wwww; /* some\n"
12676             "         comment */",
12677             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12678                    "wwww; /* some\n"
12679                    "         comment */",
12680                    getLLVMStyle()));
12681 }
12682 
12683 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
12684   FormatStyle NoSpace = getLLVMStyle();
12685   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
12686 
12687   verifyFormat("while(true)\n"
12688                "  continue;",
12689                NoSpace);
12690   verifyFormat("for(;;)\n"
12691                "  continue;",
12692                NoSpace);
12693   verifyFormat("if(true)\n"
12694                "  f();\n"
12695                "else if(true)\n"
12696                "  f();",
12697                NoSpace);
12698   verifyFormat("do {\n"
12699                "  do_something();\n"
12700                "} while(something());",
12701                NoSpace);
12702   verifyFormat("switch(x) {\n"
12703                "default:\n"
12704                "  break;\n"
12705                "}",
12706                NoSpace);
12707   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
12708   verifyFormat("size_t x = sizeof(x);", NoSpace);
12709   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
12710   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
12711   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
12712   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
12713   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
12714   verifyFormat("alignas(128) char a[128];", NoSpace);
12715   verifyFormat("size_t x = alignof(MyType);", NoSpace);
12716   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
12717   verifyFormat("int f() throw(Deprecated);", NoSpace);
12718   verifyFormat("typedef void (*cb)(int);", NoSpace);
12719   verifyFormat("T A::operator()();", NoSpace);
12720   verifyFormat("X A::operator++(T);", NoSpace);
12721   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
12722 
12723   FormatStyle Space = getLLVMStyle();
12724   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
12725 
12726   verifyFormat("int f ();", Space);
12727   verifyFormat("void f (int a, T b) {\n"
12728                "  while (true)\n"
12729                "    continue;\n"
12730                "}",
12731                Space);
12732   verifyFormat("if (true)\n"
12733                "  f ();\n"
12734                "else if (true)\n"
12735                "  f ();",
12736                Space);
12737   verifyFormat("do {\n"
12738                "  do_something ();\n"
12739                "} while (something ());",
12740                Space);
12741   verifyFormat("switch (x) {\n"
12742                "default:\n"
12743                "  break;\n"
12744                "}",
12745                Space);
12746   verifyFormat("A::A () : a (1) {}", Space);
12747   verifyFormat("void f () __attribute__ ((asdf));", Space);
12748   verifyFormat("*(&a + 1);\n"
12749                "&((&a)[1]);\n"
12750                "a[(b + c) * d];\n"
12751                "(((a + 1) * 2) + 3) * 4;",
12752                Space);
12753   verifyFormat("#define A(x) x", Space);
12754   verifyFormat("#define A (x) x", Space);
12755   verifyFormat("#if defined(x)\n"
12756                "#endif",
12757                Space);
12758   verifyFormat("auto i = std::make_unique<int> (5);", Space);
12759   verifyFormat("size_t x = sizeof (x);", Space);
12760   verifyFormat("auto f (int x) -> decltype (x);", Space);
12761   verifyFormat("auto f (int x) -> typeof (x);", Space);
12762   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
12763   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
12764   verifyFormat("int f (T x) noexcept (x.create ());", Space);
12765   verifyFormat("alignas (128) char a[128];", Space);
12766   verifyFormat("size_t x = alignof (MyType);", Space);
12767   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
12768   verifyFormat("int f () throw (Deprecated);", Space);
12769   verifyFormat("typedef void (*cb) (int);", Space);
12770   verifyFormat("T A::operator() ();", Space);
12771   verifyFormat("X A::operator++ (T);", Space);
12772   verifyFormat("auto lambda = [] () { return 0; };", Space);
12773   verifyFormat("int x = int (y);", Space);
12774 
12775   FormatStyle SomeSpace = getLLVMStyle();
12776   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
12777 
12778   verifyFormat("[]() -> float {}", SomeSpace);
12779   verifyFormat("[] (auto foo) {}", SomeSpace);
12780   verifyFormat("[foo]() -> int {}", SomeSpace);
12781   verifyFormat("int f();", SomeSpace);
12782   verifyFormat("void f (int a, T b) {\n"
12783                "  while (true)\n"
12784                "    continue;\n"
12785                "}",
12786                SomeSpace);
12787   verifyFormat("if (true)\n"
12788                "  f();\n"
12789                "else if (true)\n"
12790                "  f();",
12791                SomeSpace);
12792   verifyFormat("do {\n"
12793                "  do_something();\n"
12794                "} while (something());",
12795                SomeSpace);
12796   verifyFormat("switch (x) {\n"
12797                "default:\n"
12798                "  break;\n"
12799                "}",
12800                SomeSpace);
12801   verifyFormat("A::A() : a (1) {}", SomeSpace);
12802   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
12803   verifyFormat("*(&a + 1);\n"
12804                "&((&a)[1]);\n"
12805                "a[(b + c) * d];\n"
12806                "(((a + 1) * 2) + 3) * 4;",
12807                SomeSpace);
12808   verifyFormat("#define A(x) x", SomeSpace);
12809   verifyFormat("#define A (x) x", SomeSpace);
12810   verifyFormat("#if defined(x)\n"
12811                "#endif",
12812                SomeSpace);
12813   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
12814   verifyFormat("size_t x = sizeof (x);", SomeSpace);
12815   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
12816   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
12817   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
12818   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
12819   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
12820   verifyFormat("alignas (128) char a[128];", SomeSpace);
12821   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
12822   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
12823                SomeSpace);
12824   verifyFormat("int f() throw (Deprecated);", SomeSpace);
12825   verifyFormat("typedef void (*cb) (int);", SomeSpace);
12826   verifyFormat("T A::operator()();", SomeSpace);
12827   verifyFormat("X A::operator++ (T);", SomeSpace);
12828   verifyFormat("int x = int (y);", SomeSpace);
12829   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
12830 }
12831 
12832 TEST_F(FormatTest, SpaceAfterLogicalNot) {
12833   FormatStyle Spaces = getLLVMStyle();
12834   Spaces.SpaceAfterLogicalNot = true;
12835 
12836   verifyFormat("bool x = ! y", Spaces);
12837   verifyFormat("if (! isFailure())", Spaces);
12838   verifyFormat("if (! (a && b))", Spaces);
12839   verifyFormat("\"Error!\"", Spaces);
12840   verifyFormat("! ! x", Spaces);
12841 }
12842 
12843 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
12844   FormatStyle Spaces = getLLVMStyle();
12845 
12846   Spaces.SpacesInParentheses = true;
12847   verifyFormat("do_something( ::globalVar );", Spaces);
12848   verifyFormat("call( x, y, z );", Spaces);
12849   verifyFormat("call();", Spaces);
12850   verifyFormat("std::function<void( int, int )> callback;", Spaces);
12851   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
12852                Spaces);
12853   verifyFormat("while ( (bool)1 )\n"
12854                "  continue;",
12855                Spaces);
12856   verifyFormat("for ( ;; )\n"
12857                "  continue;",
12858                Spaces);
12859   verifyFormat("if ( true )\n"
12860                "  f();\n"
12861                "else if ( true )\n"
12862                "  f();",
12863                Spaces);
12864   verifyFormat("do {\n"
12865                "  do_something( (int)i );\n"
12866                "} while ( something() );",
12867                Spaces);
12868   verifyFormat("switch ( x ) {\n"
12869                "default:\n"
12870                "  break;\n"
12871                "}",
12872                Spaces);
12873 
12874   Spaces.SpacesInParentheses = false;
12875   Spaces.SpacesInCStyleCastParentheses = true;
12876   verifyFormat("Type *A = ( Type * )P;", Spaces);
12877   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
12878   verifyFormat("x = ( int32 )y;", Spaces);
12879   verifyFormat("int a = ( int )(2.0f);", Spaces);
12880   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
12881   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
12882   verifyFormat("#define x (( int )-1)", Spaces);
12883 
12884   // Run the first set of tests again with:
12885   Spaces.SpacesInParentheses = false;
12886   Spaces.SpaceInEmptyParentheses = true;
12887   Spaces.SpacesInCStyleCastParentheses = true;
12888   verifyFormat("call(x, y, z);", Spaces);
12889   verifyFormat("call( );", Spaces);
12890   verifyFormat("std::function<void(int, int)> callback;", Spaces);
12891   verifyFormat("while (( bool )1)\n"
12892                "  continue;",
12893                Spaces);
12894   verifyFormat("for (;;)\n"
12895                "  continue;",
12896                Spaces);
12897   verifyFormat("if (true)\n"
12898                "  f( );\n"
12899                "else if (true)\n"
12900                "  f( );",
12901                Spaces);
12902   verifyFormat("do {\n"
12903                "  do_something(( int )i);\n"
12904                "} while (something( ));",
12905                Spaces);
12906   verifyFormat("switch (x) {\n"
12907                "default:\n"
12908                "  break;\n"
12909                "}",
12910                Spaces);
12911 
12912   // Run the first set of tests again with:
12913   Spaces.SpaceAfterCStyleCast = true;
12914   verifyFormat("call(x, y, z);", Spaces);
12915   verifyFormat("call( );", Spaces);
12916   verifyFormat("std::function<void(int, int)> callback;", Spaces);
12917   verifyFormat("while (( bool ) 1)\n"
12918                "  continue;",
12919                Spaces);
12920   verifyFormat("for (;;)\n"
12921                "  continue;",
12922                Spaces);
12923   verifyFormat("if (true)\n"
12924                "  f( );\n"
12925                "else if (true)\n"
12926                "  f( );",
12927                Spaces);
12928   verifyFormat("do {\n"
12929                "  do_something(( int ) i);\n"
12930                "} while (something( ));",
12931                Spaces);
12932   verifyFormat("switch (x) {\n"
12933                "default:\n"
12934                "  break;\n"
12935                "}",
12936                Spaces);
12937 
12938   // Run subset of tests again with:
12939   Spaces.SpacesInCStyleCastParentheses = false;
12940   Spaces.SpaceAfterCStyleCast = true;
12941   verifyFormat("while ((bool) 1)\n"
12942                "  continue;",
12943                Spaces);
12944   verifyFormat("do {\n"
12945                "  do_something((int) i);\n"
12946                "} while (something( ));",
12947                Spaces);
12948 
12949   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
12950   verifyFormat("size_t idx = (size_t) a;", Spaces);
12951   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
12952   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
12953   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
12954   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
12955   Spaces.SpaceAfterCStyleCast = false;
12956   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
12957   verifyFormat("size_t idx = (size_t)a;", Spaces);
12958   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
12959   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
12960   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
12961   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
12962 }
12963 
12964 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
12965   verifyFormat("int a[5];");
12966   verifyFormat("a[3] += 42;");
12967 
12968   FormatStyle Spaces = getLLVMStyle();
12969   Spaces.SpacesInSquareBrackets = true;
12970   // Not lambdas.
12971   verifyFormat("int a[ 5 ];", Spaces);
12972   verifyFormat("a[ 3 ] += 42;", Spaces);
12973   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
12974   verifyFormat("double &operator[](int i) { return 0; }\n"
12975                "int i;",
12976                Spaces);
12977   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
12978   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
12979   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
12980   // Lambdas.
12981   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
12982   verifyFormat("return [ i, args... ] {};", Spaces);
12983   verifyFormat("int foo = [ &bar ]() {};", Spaces);
12984   verifyFormat("int foo = [ = ]() {};", Spaces);
12985   verifyFormat("int foo = [ & ]() {};", Spaces);
12986   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
12987   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
12988 }
12989 
12990 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
12991   FormatStyle NoSpaceStyle = getLLVMStyle();
12992   verifyFormat("int a[5];", NoSpaceStyle);
12993   verifyFormat("a[3] += 42;", NoSpaceStyle);
12994 
12995   verifyFormat("int a[1];", NoSpaceStyle);
12996   verifyFormat("int 1 [a];", NoSpaceStyle);
12997   verifyFormat("int a[1][2];", NoSpaceStyle);
12998   verifyFormat("a[7] = 5;", NoSpaceStyle);
12999   verifyFormat("int a = (f())[23];", NoSpaceStyle);
13000   verifyFormat("f([] {})", NoSpaceStyle);
13001 
13002   FormatStyle Space = getLLVMStyle();
13003   Space.SpaceBeforeSquareBrackets = true;
13004   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
13005   verifyFormat("return [i, args...] {};", Space);
13006 
13007   verifyFormat("int a [5];", Space);
13008   verifyFormat("a [3] += 42;", Space);
13009   verifyFormat("constexpr char hello []{\"hello\"};", Space);
13010   verifyFormat("double &operator[](int i) { return 0; }\n"
13011                "int i;",
13012                Space);
13013   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
13014   verifyFormat("int i = a [a][a]->f();", Space);
13015   verifyFormat("int i = (*b) [a]->f();", Space);
13016 
13017   verifyFormat("int a [1];", Space);
13018   verifyFormat("int 1 [a];", Space);
13019   verifyFormat("int a [1][2];", Space);
13020   verifyFormat("a [7] = 5;", Space);
13021   verifyFormat("int a = (f()) [23];", Space);
13022   verifyFormat("f([] {})", Space);
13023 }
13024 
13025 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
13026   verifyFormat("int a = 5;");
13027   verifyFormat("a += 42;");
13028   verifyFormat("a or_eq 8;");
13029 
13030   FormatStyle Spaces = getLLVMStyle();
13031   Spaces.SpaceBeforeAssignmentOperators = false;
13032   verifyFormat("int a= 5;", Spaces);
13033   verifyFormat("a+= 42;", Spaces);
13034   verifyFormat("a or_eq 8;", Spaces);
13035 }
13036 
13037 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
13038   verifyFormat("class Foo : public Bar {};");
13039   verifyFormat("Foo::Foo() : foo(1) {}");
13040   verifyFormat("for (auto a : b) {\n}");
13041   verifyFormat("int x = a ? b : c;");
13042   verifyFormat("{\n"
13043                "label0:\n"
13044                "  int x = 0;\n"
13045                "}");
13046   verifyFormat("switch (x) {\n"
13047                "case 1:\n"
13048                "default:\n"
13049                "}");
13050   verifyFormat("switch (allBraces) {\n"
13051                "case 1: {\n"
13052                "  break;\n"
13053                "}\n"
13054                "case 2: {\n"
13055                "  [[fallthrough]];\n"
13056                "}\n"
13057                "default: {\n"
13058                "  break;\n"
13059                "}\n"
13060                "}");
13061 
13062   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
13063   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
13064   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
13065   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
13066   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
13067   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
13068   verifyFormat("{\n"
13069                "label1:\n"
13070                "  int x = 0;\n"
13071                "}",
13072                CtorInitializerStyle);
13073   verifyFormat("switch (x) {\n"
13074                "case 1:\n"
13075                "default:\n"
13076                "}",
13077                CtorInitializerStyle);
13078   verifyFormat("switch (allBraces) {\n"
13079                "case 1: {\n"
13080                "  break;\n"
13081                "}\n"
13082                "case 2: {\n"
13083                "  [[fallthrough]];\n"
13084                "}\n"
13085                "default: {\n"
13086                "  break;\n"
13087                "}\n"
13088                "}",
13089                CtorInitializerStyle);
13090   CtorInitializerStyle.BreakConstructorInitializers =
13091       FormatStyle::BCIS_AfterColon;
13092   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
13093                "    aaaaaaaaaaaaaaaa(1),\n"
13094                "    bbbbbbbbbbbbbbbb(2) {}",
13095                CtorInitializerStyle);
13096   CtorInitializerStyle.BreakConstructorInitializers =
13097       FormatStyle::BCIS_BeforeComma;
13098   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
13099                "    : aaaaaaaaaaaaaaaa(1)\n"
13100                "    , bbbbbbbbbbbbbbbb(2) {}",
13101                CtorInitializerStyle);
13102   CtorInitializerStyle.BreakConstructorInitializers =
13103       FormatStyle::BCIS_BeforeColon;
13104   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
13105                "    : aaaaaaaaaaaaaaaa(1),\n"
13106                "      bbbbbbbbbbbbbbbb(2) {}",
13107                CtorInitializerStyle);
13108   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
13109   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
13110                ": aaaaaaaaaaaaaaaa(1),\n"
13111                "  bbbbbbbbbbbbbbbb(2) {}",
13112                CtorInitializerStyle);
13113 
13114   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
13115   InheritanceStyle.SpaceBeforeInheritanceColon = false;
13116   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
13117   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
13118   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
13119   verifyFormat("int x = a ? b : c;", InheritanceStyle);
13120   verifyFormat("{\n"
13121                "label2:\n"
13122                "  int x = 0;\n"
13123                "}",
13124                InheritanceStyle);
13125   verifyFormat("switch (x) {\n"
13126                "case 1:\n"
13127                "default:\n"
13128                "}",
13129                InheritanceStyle);
13130   verifyFormat("switch (allBraces) {\n"
13131                "case 1: {\n"
13132                "  break;\n"
13133                "}\n"
13134                "case 2: {\n"
13135                "  [[fallthrough]];\n"
13136                "}\n"
13137                "default: {\n"
13138                "  break;\n"
13139                "}\n"
13140                "}",
13141                InheritanceStyle);
13142   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
13143   verifyFormat("class Foooooooooooooooooooooo:\n"
13144                "    public aaaaaaaaaaaaaaaaaa,\n"
13145                "    public bbbbbbbbbbbbbbbbbb {\n"
13146                "}",
13147                InheritanceStyle);
13148   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
13149   verifyFormat("class Foooooooooooooooooooooo\n"
13150                "    : public aaaaaaaaaaaaaaaaaa\n"
13151                "    , public bbbbbbbbbbbbbbbbbb {\n"
13152                "}",
13153                InheritanceStyle);
13154   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
13155   verifyFormat("class Foooooooooooooooooooooo\n"
13156                "    : public aaaaaaaaaaaaaaaaaa,\n"
13157                "      public bbbbbbbbbbbbbbbbbb {\n"
13158                "}",
13159                InheritanceStyle);
13160   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
13161   verifyFormat("class Foooooooooooooooooooooo\n"
13162                ": public aaaaaaaaaaaaaaaaaa,\n"
13163                "  public bbbbbbbbbbbbbbbbbb {}",
13164                InheritanceStyle);
13165 
13166   FormatStyle ForLoopStyle = getLLVMStyle();
13167   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
13168   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
13169   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
13170   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
13171   verifyFormat("int x = a ? b : c;", ForLoopStyle);
13172   verifyFormat("{\n"
13173                "label2:\n"
13174                "  int x = 0;\n"
13175                "}",
13176                ForLoopStyle);
13177   verifyFormat("switch (x) {\n"
13178                "case 1:\n"
13179                "default:\n"
13180                "}",
13181                ForLoopStyle);
13182   verifyFormat("switch (allBraces) {\n"
13183                "case 1: {\n"
13184                "  break;\n"
13185                "}\n"
13186                "case 2: {\n"
13187                "  [[fallthrough]];\n"
13188                "}\n"
13189                "default: {\n"
13190                "  break;\n"
13191                "}\n"
13192                "}",
13193                ForLoopStyle);
13194 
13195   FormatStyle CaseStyle = getLLVMStyle();
13196   CaseStyle.SpaceBeforeCaseColon = true;
13197   verifyFormat("class Foo : public Bar {};", CaseStyle);
13198   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
13199   verifyFormat("for (auto a : b) {\n}", CaseStyle);
13200   verifyFormat("int x = a ? b : c;", CaseStyle);
13201   verifyFormat("switch (x) {\n"
13202                "case 1 :\n"
13203                "default :\n"
13204                "}",
13205                CaseStyle);
13206   verifyFormat("switch (allBraces) {\n"
13207                "case 1 : {\n"
13208                "  break;\n"
13209                "}\n"
13210                "case 2 : {\n"
13211                "  [[fallthrough]];\n"
13212                "}\n"
13213                "default : {\n"
13214                "  break;\n"
13215                "}\n"
13216                "}",
13217                CaseStyle);
13218 
13219   FormatStyle NoSpaceStyle = getLLVMStyle();
13220   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
13221   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
13222   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
13223   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
13224   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
13225   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
13226   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
13227   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
13228   verifyFormat("{\n"
13229                "label3:\n"
13230                "  int x = 0;\n"
13231                "}",
13232                NoSpaceStyle);
13233   verifyFormat("switch (x) {\n"
13234                "case 1:\n"
13235                "default:\n"
13236                "}",
13237                NoSpaceStyle);
13238   verifyFormat("switch (allBraces) {\n"
13239                "case 1: {\n"
13240                "  break;\n"
13241                "}\n"
13242                "case 2: {\n"
13243                "  [[fallthrough]];\n"
13244                "}\n"
13245                "default: {\n"
13246                "  break;\n"
13247                "}\n"
13248                "}",
13249                NoSpaceStyle);
13250 
13251   FormatStyle InvertedSpaceStyle = getLLVMStyle();
13252   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
13253   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
13254   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
13255   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
13256   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
13257   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
13258   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
13259   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
13260   verifyFormat("{\n"
13261                "label3:\n"
13262                "  int x = 0;\n"
13263                "}",
13264                InvertedSpaceStyle);
13265   verifyFormat("switch (x) {\n"
13266                "case 1 :\n"
13267                "case 2 : {\n"
13268                "  break;\n"
13269                "}\n"
13270                "default :\n"
13271                "  break;\n"
13272                "}",
13273                InvertedSpaceStyle);
13274   verifyFormat("switch (allBraces) {\n"
13275                "case 1 : {\n"
13276                "  break;\n"
13277                "}\n"
13278                "case 2 : {\n"
13279                "  [[fallthrough]];\n"
13280                "}\n"
13281                "default : {\n"
13282                "  break;\n"
13283                "}\n"
13284                "}",
13285                InvertedSpaceStyle);
13286 }
13287 
13288 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
13289   FormatStyle Style = getLLVMStyle();
13290 
13291   Style.PointerAlignment = FormatStyle::PAS_Left;
13292   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
13293   verifyFormat("void* const* x = NULL;", Style);
13294 
13295 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
13296   do {                                                                         \
13297     Style.PointerAlignment = FormatStyle::Pointers;                            \
13298     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
13299     verifyFormat(Code, Style);                                                 \
13300   } while (false)
13301 
13302   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
13303   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
13304   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
13305 
13306   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
13307   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
13308   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
13309 
13310   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
13311   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
13312   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
13313 
13314   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
13315   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
13316   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
13317 
13318   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
13319   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
13320                         SAPQ_Default);
13321   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
13322                         SAPQ_Default);
13323 
13324   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
13325   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
13326                         SAPQ_Before);
13327   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
13328                         SAPQ_Before);
13329 
13330   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
13331   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
13332   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
13333                         SAPQ_After);
13334 
13335   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
13336   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
13337   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
13338 
13339 #undef verifyQualifierSpaces
13340 
13341   FormatStyle Spaces = getLLVMStyle();
13342   Spaces.AttributeMacros.push_back("qualified");
13343   Spaces.PointerAlignment = FormatStyle::PAS_Right;
13344   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
13345   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
13346   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
13347   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
13348   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
13349   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13350   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
13351   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
13352   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
13353   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
13354   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
13355   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13356 
13357   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
13358   Spaces.PointerAlignment = FormatStyle::PAS_Left;
13359   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
13360   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
13361   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
13362   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
13363   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
13364   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13365   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
13366   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
13367   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
13368   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
13369   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
13370   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
13371   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13372 
13373   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
13374   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
13375   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
13376   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
13377   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
13378   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
13379   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
13380   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13381 }
13382 
13383 TEST_F(FormatTest, AlignConsecutiveMacros) {
13384   FormatStyle Style = getLLVMStyle();
13385   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13386   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13387   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
13388 
13389   verifyFormat("#define a 3\n"
13390                "#define bbbb 4\n"
13391                "#define ccc (5)",
13392                Style);
13393 
13394   verifyFormat("#define f(x) (x * x)\n"
13395                "#define fff(x, y, z) (x * y + z)\n"
13396                "#define ffff(x, y) (x - y)",
13397                Style);
13398 
13399   verifyFormat("#define foo(x, y) (x + y)\n"
13400                "#define bar (5, 6)(2 + 2)",
13401                Style);
13402 
13403   verifyFormat("#define a 3\n"
13404                "#define bbbb 4\n"
13405                "#define ccc (5)\n"
13406                "#define f(x) (x * x)\n"
13407                "#define fff(x, y, z) (x * y + z)\n"
13408                "#define ffff(x, y) (x - y)",
13409                Style);
13410 
13411   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13412   verifyFormat("#define a    3\n"
13413                "#define bbbb 4\n"
13414                "#define ccc  (5)",
13415                Style);
13416 
13417   verifyFormat("#define f(x)         (x * x)\n"
13418                "#define fff(x, y, z) (x * y + z)\n"
13419                "#define ffff(x, y)   (x - y)",
13420                Style);
13421 
13422   verifyFormat("#define foo(x, y) (x + y)\n"
13423                "#define bar       (5, 6)(2 + 2)",
13424                Style);
13425 
13426   verifyFormat("#define a            3\n"
13427                "#define bbbb         4\n"
13428                "#define ccc          (5)\n"
13429                "#define f(x)         (x * x)\n"
13430                "#define fff(x, y, z) (x * y + z)\n"
13431                "#define ffff(x, y)   (x - y)",
13432                Style);
13433 
13434   verifyFormat("#define a         5\n"
13435                "#define foo(x, y) (x + y)\n"
13436                "#define CCC       (6)\n"
13437                "auto lambda = []() {\n"
13438                "  auto  ii = 0;\n"
13439                "  float j  = 0;\n"
13440                "  return 0;\n"
13441                "};\n"
13442                "int   i  = 0;\n"
13443                "float i2 = 0;\n"
13444                "auto  v  = type{\n"
13445                "    i = 1,   //\n"
13446                "    (i = 2), //\n"
13447                "    i = 3    //\n"
13448                "};",
13449                Style);
13450 
13451   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
13452   Style.ColumnLimit = 20;
13453 
13454   verifyFormat("#define a          \\\n"
13455                "  \"aabbbbbbbbbbbb\"\n"
13456                "#define D          \\\n"
13457                "  \"aabbbbbbbbbbbb\" \\\n"
13458                "  \"ccddeeeeeeeee\"\n"
13459                "#define B          \\\n"
13460                "  \"QQQQQQQQQQQQQ\"  \\\n"
13461                "  \"FFFFFFFFFFFFF\"  \\\n"
13462                "  \"LLLLLLLL\"\n",
13463                Style);
13464 
13465   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13466   verifyFormat("#define a          \\\n"
13467                "  \"aabbbbbbbbbbbb\"\n"
13468                "#define D          \\\n"
13469                "  \"aabbbbbbbbbbbb\" \\\n"
13470                "  \"ccddeeeeeeeee\"\n"
13471                "#define B          \\\n"
13472                "  \"QQQQQQQQQQQQQ\"  \\\n"
13473                "  \"FFFFFFFFFFFFF\"  \\\n"
13474                "  \"LLLLLLLL\"\n",
13475                Style);
13476 
13477   // Test across comments
13478   Style.MaxEmptyLinesToKeep = 10;
13479   Style.ReflowComments = false;
13480   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
13481   EXPECT_EQ("#define a    3\n"
13482             "// line comment\n"
13483             "#define bbbb 4\n"
13484             "#define ccc  (5)",
13485             format("#define a 3\n"
13486                    "// line comment\n"
13487                    "#define bbbb 4\n"
13488                    "#define ccc (5)",
13489                    Style));
13490 
13491   EXPECT_EQ("#define a    3\n"
13492             "/* block comment */\n"
13493             "#define bbbb 4\n"
13494             "#define ccc  (5)",
13495             format("#define a  3\n"
13496                    "/* block comment */\n"
13497                    "#define bbbb 4\n"
13498                    "#define ccc (5)",
13499                    Style));
13500 
13501   EXPECT_EQ("#define a    3\n"
13502             "/* multi-line *\n"
13503             " * block comment */\n"
13504             "#define bbbb 4\n"
13505             "#define ccc  (5)",
13506             format("#define a 3\n"
13507                    "/* multi-line *\n"
13508                    " * block comment */\n"
13509                    "#define bbbb 4\n"
13510                    "#define ccc (5)",
13511                    Style));
13512 
13513   EXPECT_EQ("#define a    3\n"
13514             "// multi-line line comment\n"
13515             "//\n"
13516             "#define bbbb 4\n"
13517             "#define ccc  (5)",
13518             format("#define a  3\n"
13519                    "// multi-line line comment\n"
13520                    "//\n"
13521                    "#define bbbb 4\n"
13522                    "#define ccc (5)",
13523                    Style));
13524 
13525   EXPECT_EQ("#define a 3\n"
13526             "// empty lines still break.\n"
13527             "\n"
13528             "#define bbbb 4\n"
13529             "#define ccc  (5)",
13530             format("#define a     3\n"
13531                    "// empty lines still break.\n"
13532                    "\n"
13533                    "#define bbbb     4\n"
13534                    "#define ccc  (5)",
13535                    Style));
13536 
13537   // Test across empty lines
13538   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
13539   EXPECT_EQ("#define a    3\n"
13540             "\n"
13541             "#define bbbb 4\n"
13542             "#define ccc  (5)",
13543             format("#define a 3\n"
13544                    "\n"
13545                    "#define bbbb 4\n"
13546                    "#define ccc (5)",
13547                    Style));
13548 
13549   EXPECT_EQ("#define a    3\n"
13550             "\n"
13551             "\n"
13552             "\n"
13553             "#define bbbb 4\n"
13554             "#define ccc  (5)",
13555             format("#define a        3\n"
13556                    "\n"
13557                    "\n"
13558                    "\n"
13559                    "#define bbbb 4\n"
13560                    "#define ccc (5)",
13561                    Style));
13562 
13563   EXPECT_EQ("#define a 3\n"
13564             "// comments should break alignment\n"
13565             "//\n"
13566             "#define bbbb 4\n"
13567             "#define ccc  (5)",
13568             format("#define a        3\n"
13569                    "// comments should break alignment\n"
13570                    "//\n"
13571                    "#define bbbb 4\n"
13572                    "#define ccc (5)",
13573                    Style));
13574 
13575   // Test across empty lines and comments
13576   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
13577   verifyFormat("#define a    3\n"
13578                "\n"
13579                "// line comment\n"
13580                "#define bbbb 4\n"
13581                "#define ccc  (5)",
13582                Style);
13583 
13584   EXPECT_EQ("#define a    3\n"
13585             "\n"
13586             "\n"
13587             "/* multi-line *\n"
13588             " * block comment */\n"
13589             "\n"
13590             "\n"
13591             "#define bbbb 4\n"
13592             "#define ccc  (5)",
13593             format("#define a 3\n"
13594                    "\n"
13595                    "\n"
13596                    "/* multi-line *\n"
13597                    " * block comment */\n"
13598                    "\n"
13599                    "\n"
13600                    "#define bbbb 4\n"
13601                    "#define ccc (5)",
13602                    Style));
13603 
13604   EXPECT_EQ("#define a    3\n"
13605             "\n"
13606             "\n"
13607             "/* multi-line *\n"
13608             " * block comment */\n"
13609             "\n"
13610             "\n"
13611             "#define bbbb 4\n"
13612             "#define ccc  (5)",
13613             format("#define a 3\n"
13614                    "\n"
13615                    "\n"
13616                    "/* multi-line *\n"
13617                    " * block comment */\n"
13618                    "\n"
13619                    "\n"
13620                    "#define bbbb 4\n"
13621                    "#define ccc       (5)",
13622                    Style));
13623 }
13624 
13625 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
13626   FormatStyle Alignment = getLLVMStyle();
13627   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13628   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
13629 
13630   Alignment.MaxEmptyLinesToKeep = 10;
13631   /* Test alignment across empty lines */
13632   EXPECT_EQ("int a           = 5;\n"
13633             "\n"
13634             "int oneTwoThree = 123;",
13635             format("int a       = 5;\n"
13636                    "\n"
13637                    "int oneTwoThree= 123;",
13638                    Alignment));
13639   EXPECT_EQ("int a           = 5;\n"
13640             "int one         = 1;\n"
13641             "\n"
13642             "int oneTwoThree = 123;",
13643             format("int a = 5;\n"
13644                    "int one = 1;\n"
13645                    "\n"
13646                    "int oneTwoThree = 123;",
13647                    Alignment));
13648   EXPECT_EQ("int a           = 5;\n"
13649             "int one         = 1;\n"
13650             "\n"
13651             "int oneTwoThree = 123;\n"
13652             "int oneTwo      = 12;",
13653             format("int a = 5;\n"
13654                    "int one = 1;\n"
13655                    "\n"
13656                    "int oneTwoThree = 123;\n"
13657                    "int oneTwo = 12;",
13658                    Alignment));
13659 
13660   /* Test across comments */
13661   EXPECT_EQ("int a = 5;\n"
13662             "/* block comment */\n"
13663             "int oneTwoThree = 123;",
13664             format("int a = 5;\n"
13665                    "/* block comment */\n"
13666                    "int oneTwoThree=123;",
13667                    Alignment));
13668 
13669   EXPECT_EQ("int a = 5;\n"
13670             "// line comment\n"
13671             "int oneTwoThree = 123;",
13672             format("int a = 5;\n"
13673                    "// line comment\n"
13674                    "int oneTwoThree=123;",
13675                    Alignment));
13676 
13677   /* Test across comments and newlines */
13678   EXPECT_EQ("int a = 5;\n"
13679             "\n"
13680             "/* block comment */\n"
13681             "int oneTwoThree = 123;",
13682             format("int a = 5;\n"
13683                    "\n"
13684                    "/* block comment */\n"
13685                    "int oneTwoThree=123;",
13686                    Alignment));
13687 
13688   EXPECT_EQ("int a = 5;\n"
13689             "\n"
13690             "// line comment\n"
13691             "int oneTwoThree = 123;",
13692             format("int a = 5;\n"
13693                    "\n"
13694                    "// line comment\n"
13695                    "int oneTwoThree=123;",
13696                    Alignment));
13697 }
13698 
13699 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
13700   FormatStyle Alignment = getLLVMStyle();
13701   Alignment.AlignConsecutiveDeclarations =
13702       FormatStyle::ACS_AcrossEmptyLinesAndComments;
13703   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
13704 
13705   Alignment.MaxEmptyLinesToKeep = 10;
13706   /* Test alignment across empty lines */
13707   EXPECT_EQ("int         a = 5;\n"
13708             "\n"
13709             "float const oneTwoThree = 123;",
13710             format("int a = 5;\n"
13711                    "\n"
13712                    "float const oneTwoThree = 123;",
13713                    Alignment));
13714   EXPECT_EQ("int         a = 5;\n"
13715             "float const one = 1;\n"
13716             "\n"
13717             "int         oneTwoThree = 123;",
13718             format("int a = 5;\n"
13719                    "float const one = 1;\n"
13720                    "\n"
13721                    "int oneTwoThree = 123;",
13722                    Alignment));
13723 
13724   /* Test across comments */
13725   EXPECT_EQ("float const a = 5;\n"
13726             "/* block comment */\n"
13727             "int         oneTwoThree = 123;",
13728             format("float const a = 5;\n"
13729                    "/* block comment */\n"
13730                    "int oneTwoThree=123;",
13731                    Alignment));
13732 
13733   EXPECT_EQ("float const a = 5;\n"
13734             "// line comment\n"
13735             "int         oneTwoThree = 123;",
13736             format("float const a = 5;\n"
13737                    "// line comment\n"
13738                    "int oneTwoThree=123;",
13739                    Alignment));
13740 
13741   /* Test across comments and newlines */
13742   EXPECT_EQ("float const a = 5;\n"
13743             "\n"
13744             "/* block comment */\n"
13745             "int         oneTwoThree = 123;",
13746             format("float const a = 5;\n"
13747                    "\n"
13748                    "/* block comment */\n"
13749                    "int         oneTwoThree=123;",
13750                    Alignment));
13751 
13752   EXPECT_EQ("float const a = 5;\n"
13753             "\n"
13754             "// line comment\n"
13755             "int         oneTwoThree = 123;",
13756             format("float const a = 5;\n"
13757                    "\n"
13758                    "// line comment\n"
13759                    "int oneTwoThree=123;",
13760                    Alignment));
13761 }
13762 
13763 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
13764   FormatStyle Alignment = getLLVMStyle();
13765   Alignment.AlignConsecutiveBitFields =
13766       FormatStyle::ACS_AcrossEmptyLinesAndComments;
13767 
13768   Alignment.MaxEmptyLinesToKeep = 10;
13769   /* Test alignment across empty lines */
13770   EXPECT_EQ("int a            : 5;\n"
13771             "\n"
13772             "int longbitfield : 6;",
13773             format("int a : 5;\n"
13774                    "\n"
13775                    "int longbitfield : 6;",
13776                    Alignment));
13777   EXPECT_EQ("int a            : 5;\n"
13778             "int one          : 1;\n"
13779             "\n"
13780             "int longbitfield : 6;",
13781             format("int a : 5;\n"
13782                    "int one : 1;\n"
13783                    "\n"
13784                    "int longbitfield : 6;",
13785                    Alignment));
13786 
13787   /* Test across comments */
13788   EXPECT_EQ("int a            : 5;\n"
13789             "/* block comment */\n"
13790             "int longbitfield : 6;",
13791             format("int a : 5;\n"
13792                    "/* block comment */\n"
13793                    "int longbitfield : 6;",
13794                    Alignment));
13795   EXPECT_EQ("int a            : 5;\n"
13796             "int one          : 1;\n"
13797             "// line comment\n"
13798             "int longbitfield : 6;",
13799             format("int a : 5;\n"
13800                    "int one : 1;\n"
13801                    "// line comment\n"
13802                    "int longbitfield : 6;",
13803                    Alignment));
13804 
13805   /* Test across comments and newlines */
13806   EXPECT_EQ("int a            : 5;\n"
13807             "/* block comment */\n"
13808             "\n"
13809             "int longbitfield : 6;",
13810             format("int a : 5;\n"
13811                    "/* block comment */\n"
13812                    "\n"
13813                    "int longbitfield : 6;",
13814                    Alignment));
13815   EXPECT_EQ("int a            : 5;\n"
13816             "int one          : 1;\n"
13817             "\n"
13818             "// line comment\n"
13819             "\n"
13820             "int longbitfield : 6;",
13821             format("int a : 5;\n"
13822                    "int one : 1;\n"
13823                    "\n"
13824                    "// line comment \n"
13825                    "\n"
13826                    "int longbitfield : 6;",
13827                    Alignment));
13828 }
13829 
13830 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
13831   FormatStyle Alignment = getLLVMStyle();
13832   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13833   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
13834 
13835   Alignment.MaxEmptyLinesToKeep = 10;
13836   /* Test alignment across empty lines */
13837   EXPECT_EQ("int a = 5;\n"
13838             "\n"
13839             "int oneTwoThree = 123;",
13840             format("int a       = 5;\n"
13841                    "\n"
13842                    "int oneTwoThree= 123;",
13843                    Alignment));
13844   EXPECT_EQ("int a   = 5;\n"
13845             "int one = 1;\n"
13846             "\n"
13847             "int oneTwoThree = 123;",
13848             format("int a = 5;\n"
13849                    "int one = 1;\n"
13850                    "\n"
13851                    "int oneTwoThree = 123;",
13852                    Alignment));
13853 
13854   /* Test across comments */
13855   EXPECT_EQ("int a           = 5;\n"
13856             "/* block comment */\n"
13857             "int oneTwoThree = 123;",
13858             format("int a = 5;\n"
13859                    "/* block comment */\n"
13860                    "int oneTwoThree=123;",
13861                    Alignment));
13862 
13863   EXPECT_EQ("int a           = 5;\n"
13864             "// line comment\n"
13865             "int oneTwoThree = 123;",
13866             format("int a = 5;\n"
13867                    "// line comment\n"
13868                    "int oneTwoThree=123;",
13869                    Alignment));
13870 
13871   EXPECT_EQ("int a           = 5;\n"
13872             "/*\n"
13873             " * multi-line block comment\n"
13874             " */\n"
13875             "int oneTwoThree = 123;",
13876             format("int a = 5;\n"
13877                    "/*\n"
13878                    " * multi-line block comment\n"
13879                    " */\n"
13880                    "int oneTwoThree=123;",
13881                    Alignment));
13882 
13883   EXPECT_EQ("int a           = 5;\n"
13884             "//\n"
13885             "// multi-line line comment\n"
13886             "//\n"
13887             "int oneTwoThree = 123;",
13888             format("int a = 5;\n"
13889                    "//\n"
13890                    "// multi-line line comment\n"
13891                    "//\n"
13892                    "int oneTwoThree=123;",
13893                    Alignment));
13894 
13895   /* Test across comments and newlines */
13896   EXPECT_EQ("int a = 5;\n"
13897             "\n"
13898             "/* block comment */\n"
13899             "int oneTwoThree = 123;",
13900             format("int a = 5;\n"
13901                    "\n"
13902                    "/* block comment */\n"
13903                    "int oneTwoThree=123;",
13904                    Alignment));
13905 
13906   EXPECT_EQ("int a = 5;\n"
13907             "\n"
13908             "// line comment\n"
13909             "int oneTwoThree = 123;",
13910             format("int a = 5;\n"
13911                    "\n"
13912                    "// line comment\n"
13913                    "int oneTwoThree=123;",
13914                    Alignment));
13915 }
13916 
13917 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
13918   FormatStyle Alignment = getLLVMStyle();
13919   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13920   Alignment.AlignConsecutiveAssignments =
13921       FormatStyle::ACS_AcrossEmptyLinesAndComments;
13922   verifyFormat("int a           = 5;\n"
13923                "int oneTwoThree = 123;",
13924                Alignment);
13925   verifyFormat("int a           = method();\n"
13926                "int oneTwoThree = 133;",
13927                Alignment);
13928   verifyFormat("a &= 5;\n"
13929                "bcd *= 5;\n"
13930                "ghtyf += 5;\n"
13931                "dvfvdb -= 5;\n"
13932                "a /= 5;\n"
13933                "vdsvsv %= 5;\n"
13934                "sfdbddfbdfbb ^= 5;\n"
13935                "dvsdsv |= 5;\n"
13936                "int dsvvdvsdvvv = 123;",
13937                Alignment);
13938   verifyFormat("int i = 1, j = 10;\n"
13939                "something = 2000;",
13940                Alignment);
13941   verifyFormat("something = 2000;\n"
13942                "int i = 1, j = 10;\n",
13943                Alignment);
13944   verifyFormat("something = 2000;\n"
13945                "another   = 911;\n"
13946                "int i = 1, j = 10;\n"
13947                "oneMore = 1;\n"
13948                "i       = 2;",
13949                Alignment);
13950   verifyFormat("int a   = 5;\n"
13951                "int one = 1;\n"
13952                "method();\n"
13953                "int oneTwoThree = 123;\n"
13954                "int oneTwo      = 12;",
13955                Alignment);
13956   verifyFormat("int oneTwoThree = 123;\n"
13957                "int oneTwo      = 12;\n"
13958                "method();\n",
13959                Alignment);
13960   verifyFormat("int oneTwoThree = 123; // comment\n"
13961                "int oneTwo      = 12;  // comment",
13962                Alignment);
13963 
13964   // Bug 25167
13965   /* Uncomment when fixed
13966     verifyFormat("#if A\n"
13967                  "#else\n"
13968                  "int aaaaaaaa = 12;\n"
13969                  "#endif\n"
13970                  "#if B\n"
13971                  "#else\n"
13972                  "int a = 12;\n"
13973                  "#endif\n",
13974                  Alignment);
13975     verifyFormat("enum foo {\n"
13976                  "#if A\n"
13977                  "#else\n"
13978                  "  aaaaaaaa = 12;\n"
13979                  "#endif\n"
13980                  "#if B\n"
13981                  "#else\n"
13982                  "  a = 12;\n"
13983                  "#endif\n"
13984                  "};\n",
13985                  Alignment);
13986   */
13987 
13988   Alignment.MaxEmptyLinesToKeep = 10;
13989   /* Test alignment across empty lines */
13990   EXPECT_EQ("int a           = 5;\n"
13991             "\n"
13992             "int oneTwoThree = 123;",
13993             format("int a       = 5;\n"
13994                    "\n"
13995                    "int oneTwoThree= 123;",
13996                    Alignment));
13997   EXPECT_EQ("int a           = 5;\n"
13998             "int one         = 1;\n"
13999             "\n"
14000             "int oneTwoThree = 123;",
14001             format("int a = 5;\n"
14002                    "int one = 1;\n"
14003                    "\n"
14004                    "int oneTwoThree = 123;",
14005                    Alignment));
14006   EXPECT_EQ("int a           = 5;\n"
14007             "int one         = 1;\n"
14008             "\n"
14009             "int oneTwoThree = 123;\n"
14010             "int oneTwo      = 12;",
14011             format("int a = 5;\n"
14012                    "int one = 1;\n"
14013                    "\n"
14014                    "int oneTwoThree = 123;\n"
14015                    "int oneTwo = 12;",
14016                    Alignment));
14017 
14018   /* Test across comments */
14019   EXPECT_EQ("int a           = 5;\n"
14020             "/* block comment */\n"
14021             "int oneTwoThree = 123;",
14022             format("int a = 5;\n"
14023                    "/* block comment */\n"
14024                    "int oneTwoThree=123;",
14025                    Alignment));
14026 
14027   EXPECT_EQ("int a           = 5;\n"
14028             "// line comment\n"
14029             "int oneTwoThree = 123;",
14030             format("int a = 5;\n"
14031                    "// line comment\n"
14032                    "int oneTwoThree=123;",
14033                    Alignment));
14034 
14035   /* Test across comments and newlines */
14036   EXPECT_EQ("int a           = 5;\n"
14037             "\n"
14038             "/* block comment */\n"
14039             "int oneTwoThree = 123;",
14040             format("int a = 5;\n"
14041                    "\n"
14042                    "/* block comment */\n"
14043                    "int oneTwoThree=123;",
14044                    Alignment));
14045 
14046   EXPECT_EQ("int a           = 5;\n"
14047             "\n"
14048             "// line comment\n"
14049             "int oneTwoThree = 123;",
14050             format("int a = 5;\n"
14051                    "\n"
14052                    "// line comment\n"
14053                    "int oneTwoThree=123;",
14054                    Alignment));
14055 
14056   EXPECT_EQ("int a           = 5;\n"
14057             "//\n"
14058             "// multi-line line comment\n"
14059             "//\n"
14060             "int oneTwoThree = 123;",
14061             format("int a = 5;\n"
14062                    "//\n"
14063                    "// multi-line line comment\n"
14064                    "//\n"
14065                    "int oneTwoThree=123;",
14066                    Alignment));
14067 
14068   EXPECT_EQ("int a           = 5;\n"
14069             "/*\n"
14070             " *  multi-line block comment\n"
14071             " */\n"
14072             "int oneTwoThree = 123;",
14073             format("int a = 5;\n"
14074                    "/*\n"
14075                    " *  multi-line block comment\n"
14076                    " */\n"
14077                    "int oneTwoThree=123;",
14078                    Alignment));
14079 
14080   EXPECT_EQ("int a           = 5;\n"
14081             "\n"
14082             "/* block comment */\n"
14083             "\n"
14084             "\n"
14085             "\n"
14086             "int oneTwoThree = 123;",
14087             format("int a = 5;\n"
14088                    "\n"
14089                    "/* block comment */\n"
14090                    "\n"
14091                    "\n"
14092                    "\n"
14093                    "int oneTwoThree=123;",
14094                    Alignment));
14095 
14096   EXPECT_EQ("int a           = 5;\n"
14097             "\n"
14098             "// line comment\n"
14099             "\n"
14100             "\n"
14101             "\n"
14102             "int oneTwoThree = 123;",
14103             format("int a = 5;\n"
14104                    "\n"
14105                    "// line comment\n"
14106                    "\n"
14107                    "\n"
14108                    "\n"
14109                    "int oneTwoThree=123;",
14110                    Alignment));
14111 
14112   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
14113   verifyFormat("#define A \\\n"
14114                "  int aaaa       = 12; \\\n"
14115                "  int b          = 23; \\\n"
14116                "  int ccc        = 234; \\\n"
14117                "  int dddddddddd = 2345;",
14118                Alignment);
14119   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14120   verifyFormat("#define A               \\\n"
14121                "  int aaaa       = 12;  \\\n"
14122                "  int b          = 23;  \\\n"
14123                "  int ccc        = 234; \\\n"
14124                "  int dddddddddd = 2345;",
14125                Alignment);
14126   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
14127   verifyFormat("#define A                                                      "
14128                "                \\\n"
14129                "  int aaaa       = 12;                                         "
14130                "                \\\n"
14131                "  int b          = 23;                                         "
14132                "                \\\n"
14133                "  int ccc        = 234;                                        "
14134                "                \\\n"
14135                "  int dddddddddd = 2345;",
14136                Alignment);
14137   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
14138                "k = 4, int l = 5,\n"
14139                "                  int m = 6) {\n"
14140                "  int j      = 10;\n"
14141                "  otherThing = 1;\n"
14142                "}",
14143                Alignment);
14144   verifyFormat("void SomeFunction(int parameter = 0) {\n"
14145                "  int i   = 1;\n"
14146                "  int j   = 2;\n"
14147                "  int big = 10000;\n"
14148                "}",
14149                Alignment);
14150   verifyFormat("class C {\n"
14151                "public:\n"
14152                "  int i            = 1;\n"
14153                "  virtual void f() = 0;\n"
14154                "};",
14155                Alignment);
14156   verifyFormat("int i = 1;\n"
14157                "if (SomeType t = getSomething()) {\n"
14158                "}\n"
14159                "int j   = 2;\n"
14160                "int big = 10000;",
14161                Alignment);
14162   verifyFormat("int j = 7;\n"
14163                "for (int k = 0; k < N; ++k) {\n"
14164                "}\n"
14165                "int j   = 2;\n"
14166                "int big = 10000;\n"
14167                "}",
14168                Alignment);
14169   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14170   verifyFormat("int i = 1;\n"
14171                "LooooooooooongType loooooooooooooooooooooongVariable\n"
14172                "    = someLooooooooooooooooongFunction();\n"
14173                "int j = 2;",
14174                Alignment);
14175   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
14176   verifyFormat("int i = 1;\n"
14177                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
14178                "    someLooooooooooooooooongFunction();\n"
14179                "int j = 2;",
14180                Alignment);
14181 
14182   verifyFormat("auto lambda = []() {\n"
14183                "  auto i = 0;\n"
14184                "  return 0;\n"
14185                "};\n"
14186                "int i  = 0;\n"
14187                "auto v = type{\n"
14188                "    i = 1,   //\n"
14189                "    (i = 2), //\n"
14190                "    i = 3    //\n"
14191                "};",
14192                Alignment);
14193 
14194   verifyFormat(
14195       "int i      = 1;\n"
14196       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
14197       "                          loooooooooooooooooooooongParameterB);\n"
14198       "int j      = 2;",
14199       Alignment);
14200 
14201   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
14202                "          typename B   = very_long_type_name_1,\n"
14203                "          typename T_2 = very_long_type_name_2>\n"
14204                "auto foo() {}\n",
14205                Alignment);
14206   verifyFormat("int a, b = 1;\n"
14207                "int c  = 2;\n"
14208                "int dd = 3;\n",
14209                Alignment);
14210   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
14211                "float b[1][] = {{3.f}};\n",
14212                Alignment);
14213   verifyFormat("for (int i = 0; i < 1; i++)\n"
14214                "  int x = 1;\n",
14215                Alignment);
14216   verifyFormat("for (i = 0; i < 1; i++)\n"
14217                "  x = 1;\n"
14218                "y = 1;\n",
14219                Alignment);
14220 
14221   Alignment.ReflowComments = true;
14222   Alignment.ColumnLimit = 50;
14223   EXPECT_EQ("int x   = 0;\n"
14224             "int yy  = 1; /// specificlennospace\n"
14225             "int zzz = 2;\n",
14226             format("int x   = 0;\n"
14227                    "int yy  = 1; ///specificlennospace\n"
14228                    "int zzz = 2;\n",
14229                    Alignment));
14230 }
14231 
14232 TEST_F(FormatTest, AlignConsecutiveAssignments) {
14233   FormatStyle Alignment = getLLVMStyle();
14234   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14235   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14236   verifyFormat("int a = 5;\n"
14237                "int oneTwoThree = 123;",
14238                Alignment);
14239   verifyFormat("int a = 5;\n"
14240                "int oneTwoThree = 123;",
14241                Alignment);
14242 
14243   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14244   verifyFormat("int a           = 5;\n"
14245                "int oneTwoThree = 123;",
14246                Alignment);
14247   verifyFormat("int a           = method();\n"
14248                "int oneTwoThree = 133;",
14249                Alignment);
14250   verifyFormat("a &= 5;\n"
14251                "bcd *= 5;\n"
14252                "ghtyf += 5;\n"
14253                "dvfvdb -= 5;\n"
14254                "a /= 5;\n"
14255                "vdsvsv %= 5;\n"
14256                "sfdbddfbdfbb ^= 5;\n"
14257                "dvsdsv |= 5;\n"
14258                "int dsvvdvsdvvv = 123;",
14259                Alignment);
14260   verifyFormat("int i = 1, j = 10;\n"
14261                "something = 2000;",
14262                Alignment);
14263   verifyFormat("something = 2000;\n"
14264                "int i = 1, j = 10;\n",
14265                Alignment);
14266   verifyFormat("something = 2000;\n"
14267                "another   = 911;\n"
14268                "int i = 1, j = 10;\n"
14269                "oneMore = 1;\n"
14270                "i       = 2;",
14271                Alignment);
14272   verifyFormat("int a   = 5;\n"
14273                "int one = 1;\n"
14274                "method();\n"
14275                "int oneTwoThree = 123;\n"
14276                "int oneTwo      = 12;",
14277                Alignment);
14278   verifyFormat("int oneTwoThree = 123;\n"
14279                "int oneTwo      = 12;\n"
14280                "method();\n",
14281                Alignment);
14282   verifyFormat("int oneTwoThree = 123; // comment\n"
14283                "int oneTwo      = 12;  // comment",
14284                Alignment);
14285 
14286   // Bug 25167
14287   /* Uncomment when fixed
14288     verifyFormat("#if A\n"
14289                  "#else\n"
14290                  "int aaaaaaaa = 12;\n"
14291                  "#endif\n"
14292                  "#if B\n"
14293                  "#else\n"
14294                  "int a = 12;\n"
14295                  "#endif\n",
14296                  Alignment);
14297     verifyFormat("enum foo {\n"
14298                  "#if A\n"
14299                  "#else\n"
14300                  "  aaaaaaaa = 12;\n"
14301                  "#endif\n"
14302                  "#if B\n"
14303                  "#else\n"
14304                  "  a = 12;\n"
14305                  "#endif\n"
14306                  "};\n",
14307                  Alignment);
14308   */
14309 
14310   EXPECT_EQ("int a = 5;\n"
14311             "\n"
14312             "int oneTwoThree = 123;",
14313             format("int a       = 5;\n"
14314                    "\n"
14315                    "int oneTwoThree= 123;",
14316                    Alignment));
14317   EXPECT_EQ("int a   = 5;\n"
14318             "int one = 1;\n"
14319             "\n"
14320             "int oneTwoThree = 123;",
14321             format("int a = 5;\n"
14322                    "int one = 1;\n"
14323                    "\n"
14324                    "int oneTwoThree = 123;",
14325                    Alignment));
14326   EXPECT_EQ("int a   = 5;\n"
14327             "int one = 1;\n"
14328             "\n"
14329             "int oneTwoThree = 123;\n"
14330             "int oneTwo      = 12;",
14331             format("int a = 5;\n"
14332                    "int one = 1;\n"
14333                    "\n"
14334                    "int oneTwoThree = 123;\n"
14335                    "int oneTwo = 12;",
14336                    Alignment));
14337   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
14338   verifyFormat("#define A \\\n"
14339                "  int aaaa       = 12; \\\n"
14340                "  int b          = 23; \\\n"
14341                "  int ccc        = 234; \\\n"
14342                "  int dddddddddd = 2345;",
14343                Alignment);
14344   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14345   verifyFormat("#define A               \\\n"
14346                "  int aaaa       = 12;  \\\n"
14347                "  int b          = 23;  \\\n"
14348                "  int ccc        = 234; \\\n"
14349                "  int dddddddddd = 2345;",
14350                Alignment);
14351   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
14352   verifyFormat("#define A                                                      "
14353                "                \\\n"
14354                "  int aaaa       = 12;                                         "
14355                "                \\\n"
14356                "  int b          = 23;                                         "
14357                "                \\\n"
14358                "  int ccc        = 234;                                        "
14359                "                \\\n"
14360                "  int dddddddddd = 2345;",
14361                Alignment);
14362   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
14363                "k = 4, int l = 5,\n"
14364                "                  int m = 6) {\n"
14365                "  int j      = 10;\n"
14366                "  otherThing = 1;\n"
14367                "}",
14368                Alignment);
14369   verifyFormat("void SomeFunction(int parameter = 0) {\n"
14370                "  int i   = 1;\n"
14371                "  int j   = 2;\n"
14372                "  int big = 10000;\n"
14373                "}",
14374                Alignment);
14375   verifyFormat("class C {\n"
14376                "public:\n"
14377                "  int i            = 1;\n"
14378                "  virtual void f() = 0;\n"
14379                "};",
14380                Alignment);
14381   verifyFormat("int i = 1;\n"
14382                "if (SomeType t = getSomething()) {\n"
14383                "}\n"
14384                "int j   = 2;\n"
14385                "int big = 10000;",
14386                Alignment);
14387   verifyFormat("int j = 7;\n"
14388                "for (int k = 0; k < N; ++k) {\n"
14389                "}\n"
14390                "int j   = 2;\n"
14391                "int big = 10000;\n"
14392                "}",
14393                Alignment);
14394   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14395   verifyFormat("int i = 1;\n"
14396                "LooooooooooongType loooooooooooooooooooooongVariable\n"
14397                "    = someLooooooooooooooooongFunction();\n"
14398                "int j = 2;",
14399                Alignment);
14400   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
14401   verifyFormat("int i = 1;\n"
14402                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
14403                "    someLooooooooooooooooongFunction();\n"
14404                "int j = 2;",
14405                Alignment);
14406 
14407   verifyFormat("auto lambda = []() {\n"
14408                "  auto i = 0;\n"
14409                "  return 0;\n"
14410                "};\n"
14411                "int i  = 0;\n"
14412                "auto v = type{\n"
14413                "    i = 1,   //\n"
14414                "    (i = 2), //\n"
14415                "    i = 3    //\n"
14416                "};",
14417                Alignment);
14418 
14419   verifyFormat(
14420       "int i      = 1;\n"
14421       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
14422       "                          loooooooooooooooooooooongParameterB);\n"
14423       "int j      = 2;",
14424       Alignment);
14425 
14426   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
14427                "          typename B   = very_long_type_name_1,\n"
14428                "          typename T_2 = very_long_type_name_2>\n"
14429                "auto foo() {}\n",
14430                Alignment);
14431   verifyFormat("int a, b = 1;\n"
14432                "int c  = 2;\n"
14433                "int dd = 3;\n",
14434                Alignment);
14435   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
14436                "float b[1][] = {{3.f}};\n",
14437                Alignment);
14438   verifyFormat("for (int i = 0; i < 1; i++)\n"
14439                "  int x = 1;\n",
14440                Alignment);
14441   verifyFormat("for (i = 0; i < 1; i++)\n"
14442                "  x = 1;\n"
14443                "y = 1;\n",
14444                Alignment);
14445 
14446   Alignment.ReflowComments = true;
14447   Alignment.ColumnLimit = 50;
14448   EXPECT_EQ("int x   = 0;\n"
14449             "int yy  = 1; /// specificlennospace\n"
14450             "int zzz = 2;\n",
14451             format("int x   = 0;\n"
14452                    "int yy  = 1; ///specificlennospace\n"
14453                    "int zzz = 2;\n",
14454                    Alignment));
14455 }
14456 
14457 TEST_F(FormatTest, AlignConsecutiveBitFields) {
14458   FormatStyle Alignment = getLLVMStyle();
14459   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
14460   verifyFormat("int const a     : 5;\n"
14461                "int oneTwoThree : 23;",
14462                Alignment);
14463 
14464   // Initializers are allowed starting with c++2a
14465   verifyFormat("int const a     : 5 = 1;\n"
14466                "int oneTwoThree : 23 = 0;",
14467                Alignment);
14468 
14469   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14470   verifyFormat("int const a           : 5;\n"
14471                "int       oneTwoThree : 23;",
14472                Alignment);
14473 
14474   verifyFormat("int const a           : 5;  // comment\n"
14475                "int       oneTwoThree : 23; // comment",
14476                Alignment);
14477 
14478   verifyFormat("int const a           : 5 = 1;\n"
14479                "int       oneTwoThree : 23 = 0;",
14480                Alignment);
14481 
14482   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14483   verifyFormat("int const a           : 5  = 1;\n"
14484                "int       oneTwoThree : 23 = 0;",
14485                Alignment);
14486   verifyFormat("int const a           : 5  = {1};\n"
14487                "int       oneTwoThree : 23 = 0;",
14488                Alignment);
14489 
14490   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
14491   verifyFormat("int const a          :5;\n"
14492                "int       oneTwoThree:23;",
14493                Alignment);
14494 
14495   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
14496   verifyFormat("int const a           :5;\n"
14497                "int       oneTwoThree :23;",
14498                Alignment);
14499 
14500   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
14501   verifyFormat("int const a          : 5;\n"
14502                "int       oneTwoThree: 23;",
14503                Alignment);
14504 
14505   // Known limitations: ':' is only recognized as a bitfield colon when
14506   // followed by a number.
14507   /*
14508   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
14509                "int a           : 5;",
14510                Alignment);
14511   */
14512 }
14513 
14514 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
14515   FormatStyle Alignment = getLLVMStyle();
14516   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14517   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
14518   verifyFormat("float const a = 5;\n"
14519                "int oneTwoThree = 123;",
14520                Alignment);
14521   verifyFormat("int a = 5;\n"
14522                "float const oneTwoThree = 123;",
14523                Alignment);
14524 
14525   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14526   verifyFormat("float const a = 5;\n"
14527                "int         oneTwoThree = 123;",
14528                Alignment);
14529   verifyFormat("int         a = method();\n"
14530                "float const oneTwoThree = 133;",
14531                Alignment);
14532   verifyFormat("int i = 1, j = 10;\n"
14533                "something = 2000;",
14534                Alignment);
14535   verifyFormat("something = 2000;\n"
14536                "int i = 1, j = 10;\n",
14537                Alignment);
14538   verifyFormat("float      something = 2000;\n"
14539                "double     another = 911;\n"
14540                "int        i = 1, j = 10;\n"
14541                "const int *oneMore = 1;\n"
14542                "unsigned   i = 2;",
14543                Alignment);
14544   verifyFormat("float a = 5;\n"
14545                "int   one = 1;\n"
14546                "method();\n"
14547                "const double       oneTwoThree = 123;\n"
14548                "const unsigned int oneTwo = 12;",
14549                Alignment);
14550   verifyFormat("int      oneTwoThree{0}; // comment\n"
14551                "unsigned oneTwo;         // comment",
14552                Alignment);
14553   verifyFormat("unsigned int *      a;\n"
14554                "int *               b;\n"
14555                "unsigned int Const *c;\n"
14556                "unsigned int const *d;\n"
14557                "unsigned int Const &e;\n"
14558                "unsigned int const &f;",
14559                Alignment);
14560   verifyFormat("Const unsigned int *c;\n"
14561                "const unsigned int *d;\n"
14562                "Const unsigned int &e;\n"
14563                "const unsigned int &f;\n"
14564                "const unsigned      g;\n"
14565                "Const unsigned      h;",
14566                Alignment);
14567   EXPECT_EQ("float const a = 5;\n"
14568             "\n"
14569             "int oneTwoThree = 123;",
14570             format("float const   a = 5;\n"
14571                    "\n"
14572                    "int           oneTwoThree= 123;",
14573                    Alignment));
14574   EXPECT_EQ("float a = 5;\n"
14575             "int   one = 1;\n"
14576             "\n"
14577             "unsigned oneTwoThree = 123;",
14578             format("float    a = 5;\n"
14579                    "int      one = 1;\n"
14580                    "\n"
14581                    "unsigned oneTwoThree = 123;",
14582                    Alignment));
14583   EXPECT_EQ("float a = 5;\n"
14584             "int   one = 1;\n"
14585             "\n"
14586             "unsigned oneTwoThree = 123;\n"
14587             "int      oneTwo = 12;",
14588             format("float    a = 5;\n"
14589                    "int one = 1;\n"
14590                    "\n"
14591                    "unsigned oneTwoThree = 123;\n"
14592                    "int oneTwo = 12;",
14593                    Alignment));
14594   // Function prototype alignment
14595   verifyFormat("int    a();\n"
14596                "double b();",
14597                Alignment);
14598   verifyFormat("int    a(int x);\n"
14599                "double b();",
14600                Alignment);
14601   unsigned OldColumnLimit = Alignment.ColumnLimit;
14602   // We need to set ColumnLimit to zero, in order to stress nested alignments,
14603   // otherwise the function parameters will be re-flowed onto a single line.
14604   Alignment.ColumnLimit = 0;
14605   EXPECT_EQ("int    a(int   x,\n"
14606             "         float y);\n"
14607             "double b(int    x,\n"
14608             "         double y);",
14609             format("int a(int x,\n"
14610                    " float y);\n"
14611                    "double b(int x,\n"
14612                    " double y);",
14613                    Alignment));
14614   // This ensures that function parameters of function declarations are
14615   // correctly indented when their owning functions are indented.
14616   // The failure case here is for 'double y' to not be indented enough.
14617   EXPECT_EQ("double a(int x);\n"
14618             "int    b(int    y,\n"
14619             "         double z);",
14620             format("double a(int x);\n"
14621                    "int b(int y,\n"
14622                    " double z);",
14623                    Alignment));
14624   // Set ColumnLimit low so that we induce wrapping immediately after
14625   // the function name and opening paren.
14626   Alignment.ColumnLimit = 13;
14627   verifyFormat("int function(\n"
14628                "    int  x,\n"
14629                "    bool y);",
14630                Alignment);
14631   Alignment.ColumnLimit = OldColumnLimit;
14632   // Ensure function pointers don't screw up recursive alignment
14633   verifyFormat("int    a(int x, void (*fp)(int y));\n"
14634                "double b();",
14635                Alignment);
14636   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14637   // Ensure recursive alignment is broken by function braces, so that the
14638   // "a = 1" does not align with subsequent assignments inside the function
14639   // body.
14640   verifyFormat("int func(int a = 1) {\n"
14641                "  int b  = 2;\n"
14642                "  int cc = 3;\n"
14643                "}",
14644                Alignment);
14645   verifyFormat("float      something = 2000;\n"
14646                "double     another   = 911;\n"
14647                "int        i = 1, j = 10;\n"
14648                "const int *oneMore = 1;\n"
14649                "unsigned   i       = 2;",
14650                Alignment);
14651   verifyFormat("int      oneTwoThree = {0}; // comment\n"
14652                "unsigned oneTwo      = 0;   // comment",
14653                Alignment);
14654   // Make sure that scope is correctly tracked, in the absence of braces
14655   verifyFormat("for (int i = 0; i < n; i++)\n"
14656                "  j = i;\n"
14657                "double x = 1;\n",
14658                Alignment);
14659   verifyFormat("if (int i = 0)\n"
14660                "  j = i;\n"
14661                "double x = 1;\n",
14662                Alignment);
14663   // Ensure operator[] and operator() are comprehended
14664   verifyFormat("struct test {\n"
14665                "  long long int foo();\n"
14666                "  int           operator[](int a);\n"
14667                "  double        bar();\n"
14668                "};\n",
14669                Alignment);
14670   verifyFormat("struct test {\n"
14671                "  long long int foo();\n"
14672                "  int           operator()(int a);\n"
14673                "  double        bar();\n"
14674                "};\n",
14675                Alignment);
14676   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
14677             "  int const i   = 1;\n"
14678             "  int *     j   = 2;\n"
14679             "  int       big = 10000;\n"
14680             "\n"
14681             "  unsigned oneTwoThree = 123;\n"
14682             "  int      oneTwo      = 12;\n"
14683             "  method();\n"
14684             "  float k  = 2;\n"
14685             "  int   ll = 10000;\n"
14686             "}",
14687             format("void SomeFunction(int parameter= 0) {\n"
14688                    " int const  i= 1;\n"
14689                    "  int *j=2;\n"
14690                    " int big  =  10000;\n"
14691                    "\n"
14692                    "unsigned oneTwoThree  =123;\n"
14693                    "int oneTwo = 12;\n"
14694                    "  method();\n"
14695                    "float k= 2;\n"
14696                    "int ll=10000;\n"
14697                    "}",
14698                    Alignment));
14699   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14700   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
14701   verifyFormat("#define A \\\n"
14702                "  int       aaaa = 12; \\\n"
14703                "  float     b = 23; \\\n"
14704                "  const int ccc = 234; \\\n"
14705                "  unsigned  dddddddddd = 2345;",
14706                Alignment);
14707   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14708   verifyFormat("#define A              \\\n"
14709                "  int       aaaa = 12; \\\n"
14710                "  float     b = 23;    \\\n"
14711                "  const int ccc = 234; \\\n"
14712                "  unsigned  dddddddddd = 2345;",
14713                Alignment);
14714   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
14715   Alignment.ColumnLimit = 30;
14716   verifyFormat("#define A                    \\\n"
14717                "  int       aaaa = 12;       \\\n"
14718                "  float     b = 23;          \\\n"
14719                "  const int ccc = 234;       \\\n"
14720                "  int       dddddddddd = 2345;",
14721                Alignment);
14722   Alignment.ColumnLimit = 80;
14723   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
14724                "k = 4, int l = 5,\n"
14725                "                  int m = 6) {\n"
14726                "  const int j = 10;\n"
14727                "  otherThing = 1;\n"
14728                "}",
14729                Alignment);
14730   verifyFormat("void SomeFunction(int parameter = 0) {\n"
14731                "  int const i = 1;\n"
14732                "  int *     j = 2;\n"
14733                "  int       big = 10000;\n"
14734                "}",
14735                Alignment);
14736   verifyFormat("class C {\n"
14737                "public:\n"
14738                "  int          i = 1;\n"
14739                "  virtual void f() = 0;\n"
14740                "};",
14741                Alignment);
14742   verifyFormat("float i = 1;\n"
14743                "if (SomeType t = getSomething()) {\n"
14744                "}\n"
14745                "const unsigned j = 2;\n"
14746                "int            big = 10000;",
14747                Alignment);
14748   verifyFormat("float j = 7;\n"
14749                "for (int k = 0; k < N; ++k) {\n"
14750                "}\n"
14751                "unsigned j = 2;\n"
14752                "int      big = 10000;\n"
14753                "}",
14754                Alignment);
14755   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14756   verifyFormat("float              i = 1;\n"
14757                "LooooooooooongType loooooooooooooooooooooongVariable\n"
14758                "    = someLooooooooooooooooongFunction();\n"
14759                "int j = 2;",
14760                Alignment);
14761   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
14762   verifyFormat("int                i = 1;\n"
14763                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
14764                "    someLooooooooooooooooongFunction();\n"
14765                "int j = 2;",
14766                Alignment);
14767 
14768   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14769   verifyFormat("auto lambda = []() {\n"
14770                "  auto  ii = 0;\n"
14771                "  float j  = 0;\n"
14772                "  return 0;\n"
14773                "};\n"
14774                "int   i  = 0;\n"
14775                "float i2 = 0;\n"
14776                "auto  v  = type{\n"
14777                "    i = 1,   //\n"
14778                "    (i = 2), //\n"
14779                "    i = 3    //\n"
14780                "};",
14781                Alignment);
14782   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14783 
14784   verifyFormat(
14785       "int      i = 1;\n"
14786       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
14787       "                          loooooooooooooooooooooongParameterB);\n"
14788       "int      j = 2;",
14789       Alignment);
14790 
14791   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
14792   // We expect declarations and assignments to align, as long as it doesn't
14793   // exceed the column limit, starting a new alignment sequence whenever it
14794   // happens.
14795   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14796   Alignment.ColumnLimit = 30;
14797   verifyFormat("float    ii              = 1;\n"
14798                "unsigned j               = 2;\n"
14799                "int someVerylongVariable = 1;\n"
14800                "AnotherLongType  ll = 123456;\n"
14801                "VeryVeryLongType k  = 2;\n"
14802                "int              myvar = 1;",
14803                Alignment);
14804   Alignment.ColumnLimit = 80;
14805   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14806 
14807   verifyFormat(
14808       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
14809       "          typename LongType, typename B>\n"
14810       "auto foo() {}\n",
14811       Alignment);
14812   verifyFormat("float a, b = 1;\n"
14813                "int   c = 2;\n"
14814                "int   dd = 3;\n",
14815                Alignment);
14816   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
14817                "float b[1][] = {{3.f}};\n",
14818                Alignment);
14819   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14820   verifyFormat("float a, b = 1;\n"
14821                "int   c  = 2;\n"
14822                "int   dd = 3;\n",
14823                Alignment);
14824   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
14825                "float b[1][] = {{3.f}};\n",
14826                Alignment);
14827   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14828 
14829   Alignment.ColumnLimit = 30;
14830   Alignment.BinPackParameters = false;
14831   verifyFormat("void foo(float     a,\n"
14832                "         float     b,\n"
14833                "         int       c,\n"
14834                "         uint32_t *d) {\n"
14835                "  int *  e = 0;\n"
14836                "  float  f = 0;\n"
14837                "  double g = 0;\n"
14838                "}\n"
14839                "void bar(ino_t     a,\n"
14840                "         int       b,\n"
14841                "         uint32_t *c,\n"
14842                "         bool      d) {}\n",
14843                Alignment);
14844   Alignment.BinPackParameters = true;
14845   Alignment.ColumnLimit = 80;
14846 
14847   // Bug 33507
14848   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
14849   verifyFormat(
14850       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
14851       "  static const Version verVs2017;\n"
14852       "  return true;\n"
14853       "});\n",
14854       Alignment);
14855   Alignment.PointerAlignment = FormatStyle::PAS_Right;
14856 
14857   // See llvm.org/PR35641
14858   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14859   verifyFormat("int func() { //\n"
14860                "  int      b;\n"
14861                "  unsigned c;\n"
14862                "}",
14863                Alignment);
14864 
14865   // See PR37175
14866   FormatStyle Style = getMozillaStyle();
14867   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14868   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
14869             "foo(int a);",
14870             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
14871 
14872   Alignment.PointerAlignment = FormatStyle::PAS_Left;
14873   verifyFormat("unsigned int*       a;\n"
14874                "int*                b;\n"
14875                "unsigned int Const* c;\n"
14876                "unsigned int const* d;\n"
14877                "unsigned int Const& e;\n"
14878                "unsigned int const& f;",
14879                Alignment);
14880   verifyFormat("Const unsigned int* c;\n"
14881                "const unsigned int* d;\n"
14882                "Const unsigned int& e;\n"
14883                "const unsigned int& f;\n"
14884                "const unsigned      g;\n"
14885                "Const unsigned      h;",
14886                Alignment);
14887 
14888   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
14889   verifyFormat("unsigned int *       a;\n"
14890                "int *                b;\n"
14891                "unsigned int Const * c;\n"
14892                "unsigned int const * d;\n"
14893                "unsigned int Const & e;\n"
14894                "unsigned int const & f;",
14895                Alignment);
14896   verifyFormat("Const unsigned int * c;\n"
14897                "const unsigned int * d;\n"
14898                "Const unsigned int & e;\n"
14899                "const unsigned int & f;\n"
14900                "const unsigned       g;\n"
14901                "Const unsigned       h;",
14902                Alignment);
14903 }
14904 
14905 TEST_F(FormatTest, AlignWithLineBreaks) {
14906   auto Style = getLLVMStyleWithColumns(120);
14907 
14908   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
14909   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
14910   verifyFormat("void foo() {\n"
14911                "  int myVar = 5;\n"
14912                "  double x = 3.14;\n"
14913                "  auto str = \"Hello \"\n"
14914                "             \"World\";\n"
14915                "  auto s = \"Hello \"\n"
14916                "           \"Again\";\n"
14917                "}",
14918                Style);
14919 
14920   // clang-format off
14921   verifyFormat("void foo() {\n"
14922                "  const int capacityBefore = Entries.capacity();\n"
14923                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14924                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14925                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14926                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14927                "}",
14928                Style);
14929   // clang-format on
14930 
14931   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14932   verifyFormat("void foo() {\n"
14933                "  int myVar = 5;\n"
14934                "  double x  = 3.14;\n"
14935                "  auto str  = \"Hello \"\n"
14936                "              \"World\";\n"
14937                "  auto s    = \"Hello \"\n"
14938                "              \"Again\";\n"
14939                "}",
14940                Style);
14941 
14942   // clang-format off
14943   verifyFormat("void foo() {\n"
14944                "  const int capacityBefore = Entries.capacity();\n"
14945                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14946                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14947                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14948                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14949                "}",
14950                Style);
14951   // clang-format on
14952 
14953   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14954   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14955   verifyFormat("void foo() {\n"
14956                "  int    myVar = 5;\n"
14957                "  double x = 3.14;\n"
14958                "  auto   str = \"Hello \"\n"
14959                "               \"World\";\n"
14960                "  auto   s = \"Hello \"\n"
14961                "             \"Again\";\n"
14962                "}",
14963                Style);
14964 
14965   // clang-format off
14966   verifyFormat("void foo() {\n"
14967                "  const int  capacityBefore = Entries.capacity();\n"
14968                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14969                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14970                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14971                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14972                "}",
14973                Style);
14974   // clang-format on
14975 
14976   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14977   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14978 
14979   verifyFormat("void foo() {\n"
14980                "  int    myVar = 5;\n"
14981                "  double x     = 3.14;\n"
14982                "  auto   str   = \"Hello \"\n"
14983                "                 \"World\";\n"
14984                "  auto   s     = \"Hello \"\n"
14985                "                 \"Again\";\n"
14986                "}",
14987                Style);
14988 
14989   // clang-format off
14990   verifyFormat("void foo() {\n"
14991                "  const int  capacityBefore = Entries.capacity();\n"
14992                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14993                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14994                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14995                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14996                "}",
14997                Style);
14998   // clang-format on
14999 }
15000 
15001 TEST_F(FormatTest, LinuxBraceBreaking) {
15002   FormatStyle LinuxBraceStyle = getLLVMStyle();
15003   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
15004   verifyFormat("namespace a\n"
15005                "{\n"
15006                "class A\n"
15007                "{\n"
15008                "  void f()\n"
15009                "  {\n"
15010                "    if (true) {\n"
15011                "      a();\n"
15012                "      b();\n"
15013                "    } else {\n"
15014                "      a();\n"
15015                "    }\n"
15016                "  }\n"
15017                "  void g() { return; }\n"
15018                "};\n"
15019                "struct B {\n"
15020                "  int x;\n"
15021                "};\n"
15022                "} // namespace a\n",
15023                LinuxBraceStyle);
15024   verifyFormat("enum X {\n"
15025                "  Y = 0,\n"
15026                "}\n",
15027                LinuxBraceStyle);
15028   verifyFormat("struct S {\n"
15029                "  int Type;\n"
15030                "  union {\n"
15031                "    int x;\n"
15032                "    double y;\n"
15033                "  } Value;\n"
15034                "  class C\n"
15035                "  {\n"
15036                "    MyFavoriteType Value;\n"
15037                "  } Class;\n"
15038                "}\n",
15039                LinuxBraceStyle);
15040 }
15041 
15042 TEST_F(FormatTest, MozillaBraceBreaking) {
15043   FormatStyle MozillaBraceStyle = getLLVMStyle();
15044   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
15045   MozillaBraceStyle.FixNamespaceComments = false;
15046   verifyFormat("namespace a {\n"
15047                "class A\n"
15048                "{\n"
15049                "  void f()\n"
15050                "  {\n"
15051                "    if (true) {\n"
15052                "      a();\n"
15053                "      b();\n"
15054                "    }\n"
15055                "  }\n"
15056                "  void g() { return; }\n"
15057                "};\n"
15058                "enum E\n"
15059                "{\n"
15060                "  A,\n"
15061                "  // foo\n"
15062                "  B,\n"
15063                "  C\n"
15064                "};\n"
15065                "struct B\n"
15066                "{\n"
15067                "  int x;\n"
15068                "};\n"
15069                "}\n",
15070                MozillaBraceStyle);
15071   verifyFormat("struct S\n"
15072                "{\n"
15073                "  int Type;\n"
15074                "  union\n"
15075                "  {\n"
15076                "    int x;\n"
15077                "    double y;\n"
15078                "  } Value;\n"
15079                "  class C\n"
15080                "  {\n"
15081                "    MyFavoriteType Value;\n"
15082                "  } Class;\n"
15083                "}\n",
15084                MozillaBraceStyle);
15085 }
15086 
15087 TEST_F(FormatTest, StroustrupBraceBreaking) {
15088   FormatStyle StroustrupBraceStyle = getLLVMStyle();
15089   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
15090   verifyFormat("namespace a {\n"
15091                "class A {\n"
15092                "  void f()\n"
15093                "  {\n"
15094                "    if (true) {\n"
15095                "      a();\n"
15096                "      b();\n"
15097                "    }\n"
15098                "  }\n"
15099                "  void g() { return; }\n"
15100                "};\n"
15101                "struct B {\n"
15102                "  int x;\n"
15103                "};\n"
15104                "} // namespace a\n",
15105                StroustrupBraceStyle);
15106 
15107   verifyFormat("void foo()\n"
15108                "{\n"
15109                "  if (a) {\n"
15110                "    a();\n"
15111                "  }\n"
15112                "  else {\n"
15113                "    b();\n"
15114                "  }\n"
15115                "}\n",
15116                StroustrupBraceStyle);
15117 
15118   verifyFormat("#ifdef _DEBUG\n"
15119                "int foo(int i = 0)\n"
15120                "#else\n"
15121                "int foo(int i = 5)\n"
15122                "#endif\n"
15123                "{\n"
15124                "  return i;\n"
15125                "}",
15126                StroustrupBraceStyle);
15127 
15128   verifyFormat("void foo() {}\n"
15129                "void bar()\n"
15130                "#ifdef _DEBUG\n"
15131                "{\n"
15132                "  foo();\n"
15133                "}\n"
15134                "#else\n"
15135                "{\n"
15136                "}\n"
15137                "#endif",
15138                StroustrupBraceStyle);
15139 
15140   verifyFormat("void foobar() { int i = 5; }\n"
15141                "#ifdef _DEBUG\n"
15142                "void bar() {}\n"
15143                "#else\n"
15144                "void bar() { foobar(); }\n"
15145                "#endif",
15146                StroustrupBraceStyle);
15147 }
15148 
15149 TEST_F(FormatTest, AllmanBraceBreaking) {
15150   FormatStyle AllmanBraceStyle = getLLVMStyle();
15151   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
15152 
15153   EXPECT_EQ("namespace a\n"
15154             "{\n"
15155             "void f();\n"
15156             "void g();\n"
15157             "} // namespace a\n",
15158             format("namespace a\n"
15159                    "{\n"
15160                    "void f();\n"
15161                    "void g();\n"
15162                    "}\n",
15163                    AllmanBraceStyle));
15164 
15165   verifyFormat("namespace a\n"
15166                "{\n"
15167                "class A\n"
15168                "{\n"
15169                "  void f()\n"
15170                "  {\n"
15171                "    if (true)\n"
15172                "    {\n"
15173                "      a();\n"
15174                "      b();\n"
15175                "    }\n"
15176                "  }\n"
15177                "  void g() { return; }\n"
15178                "};\n"
15179                "struct B\n"
15180                "{\n"
15181                "  int x;\n"
15182                "};\n"
15183                "union C\n"
15184                "{\n"
15185                "};\n"
15186                "} // namespace a",
15187                AllmanBraceStyle);
15188 
15189   verifyFormat("void f()\n"
15190                "{\n"
15191                "  if (true)\n"
15192                "  {\n"
15193                "    a();\n"
15194                "  }\n"
15195                "  else if (false)\n"
15196                "  {\n"
15197                "    b();\n"
15198                "  }\n"
15199                "  else\n"
15200                "  {\n"
15201                "    c();\n"
15202                "  }\n"
15203                "}\n",
15204                AllmanBraceStyle);
15205 
15206   verifyFormat("void f()\n"
15207                "{\n"
15208                "  for (int i = 0; i < 10; ++i)\n"
15209                "  {\n"
15210                "    a();\n"
15211                "  }\n"
15212                "  while (false)\n"
15213                "  {\n"
15214                "    b();\n"
15215                "  }\n"
15216                "  do\n"
15217                "  {\n"
15218                "    c();\n"
15219                "  } while (false)\n"
15220                "}\n",
15221                AllmanBraceStyle);
15222 
15223   verifyFormat("void f(int a)\n"
15224                "{\n"
15225                "  switch (a)\n"
15226                "  {\n"
15227                "  case 0:\n"
15228                "    break;\n"
15229                "  case 1:\n"
15230                "  {\n"
15231                "    break;\n"
15232                "  }\n"
15233                "  case 2:\n"
15234                "  {\n"
15235                "  }\n"
15236                "  break;\n"
15237                "  default:\n"
15238                "    break;\n"
15239                "  }\n"
15240                "}\n",
15241                AllmanBraceStyle);
15242 
15243   verifyFormat("enum X\n"
15244                "{\n"
15245                "  Y = 0,\n"
15246                "}\n",
15247                AllmanBraceStyle);
15248   verifyFormat("enum X\n"
15249                "{\n"
15250                "  Y = 0\n"
15251                "}\n",
15252                AllmanBraceStyle);
15253 
15254   verifyFormat("@interface BSApplicationController ()\n"
15255                "{\n"
15256                "@private\n"
15257                "  id _extraIvar;\n"
15258                "}\n"
15259                "@end\n",
15260                AllmanBraceStyle);
15261 
15262   verifyFormat("#ifdef _DEBUG\n"
15263                "int foo(int i = 0)\n"
15264                "#else\n"
15265                "int foo(int i = 5)\n"
15266                "#endif\n"
15267                "{\n"
15268                "  return i;\n"
15269                "}",
15270                AllmanBraceStyle);
15271 
15272   verifyFormat("void foo() {}\n"
15273                "void bar()\n"
15274                "#ifdef _DEBUG\n"
15275                "{\n"
15276                "  foo();\n"
15277                "}\n"
15278                "#else\n"
15279                "{\n"
15280                "}\n"
15281                "#endif",
15282                AllmanBraceStyle);
15283 
15284   verifyFormat("void foobar() { int i = 5; }\n"
15285                "#ifdef _DEBUG\n"
15286                "void bar() {}\n"
15287                "#else\n"
15288                "void bar() { foobar(); }\n"
15289                "#endif",
15290                AllmanBraceStyle);
15291 
15292   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
15293             FormatStyle::SLS_All);
15294 
15295   verifyFormat("[](int i) { return i + 2; };\n"
15296                "[](int i, int j)\n"
15297                "{\n"
15298                "  auto x = i + j;\n"
15299                "  auto y = i * j;\n"
15300                "  return x ^ y;\n"
15301                "};\n"
15302                "void foo()\n"
15303                "{\n"
15304                "  auto shortLambda = [](int i) { return i + 2; };\n"
15305                "  auto longLambda = [](int i, int j)\n"
15306                "  {\n"
15307                "    auto x = i + j;\n"
15308                "    auto y = i * j;\n"
15309                "    return x ^ y;\n"
15310                "  };\n"
15311                "}",
15312                AllmanBraceStyle);
15313 
15314   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
15315 
15316   verifyFormat("[](int i)\n"
15317                "{\n"
15318                "  return i + 2;\n"
15319                "};\n"
15320                "[](int i, int j)\n"
15321                "{\n"
15322                "  auto x = i + j;\n"
15323                "  auto y = i * j;\n"
15324                "  return x ^ y;\n"
15325                "};\n"
15326                "void foo()\n"
15327                "{\n"
15328                "  auto shortLambda = [](int i)\n"
15329                "  {\n"
15330                "    return i + 2;\n"
15331                "  };\n"
15332                "  auto longLambda = [](int i, int j)\n"
15333                "  {\n"
15334                "    auto x = i + j;\n"
15335                "    auto y = i * j;\n"
15336                "    return x ^ y;\n"
15337                "  };\n"
15338                "}",
15339                AllmanBraceStyle);
15340 
15341   // Reset
15342   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
15343 
15344   // This shouldn't affect ObjC blocks..
15345   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
15346                "  // ...\n"
15347                "  int i;\n"
15348                "}];",
15349                AllmanBraceStyle);
15350   verifyFormat("void (^block)(void) = ^{\n"
15351                "  // ...\n"
15352                "  int i;\n"
15353                "};",
15354                AllmanBraceStyle);
15355   // .. or dict literals.
15356   verifyFormat("void f()\n"
15357                "{\n"
15358                "  // ...\n"
15359                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
15360                "}",
15361                AllmanBraceStyle);
15362   verifyFormat("void f()\n"
15363                "{\n"
15364                "  // ...\n"
15365                "  [object someMethod:@{a : @\"b\"}];\n"
15366                "}",
15367                AllmanBraceStyle);
15368   verifyFormat("int f()\n"
15369                "{ // comment\n"
15370                "  return 42;\n"
15371                "}",
15372                AllmanBraceStyle);
15373 
15374   AllmanBraceStyle.ColumnLimit = 19;
15375   verifyFormat("void f() { int i; }", AllmanBraceStyle);
15376   AllmanBraceStyle.ColumnLimit = 18;
15377   verifyFormat("void f()\n"
15378                "{\n"
15379                "  int i;\n"
15380                "}",
15381                AllmanBraceStyle);
15382   AllmanBraceStyle.ColumnLimit = 80;
15383 
15384   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
15385   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
15386       FormatStyle::SIS_WithoutElse;
15387   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
15388   verifyFormat("void f(bool b)\n"
15389                "{\n"
15390                "  if (b)\n"
15391                "  {\n"
15392                "    return;\n"
15393                "  }\n"
15394                "}\n",
15395                BreakBeforeBraceShortIfs);
15396   verifyFormat("void f(bool b)\n"
15397                "{\n"
15398                "  if constexpr (b)\n"
15399                "  {\n"
15400                "    return;\n"
15401                "  }\n"
15402                "}\n",
15403                BreakBeforeBraceShortIfs);
15404   verifyFormat("void f(bool b)\n"
15405                "{\n"
15406                "  if CONSTEXPR (b)\n"
15407                "  {\n"
15408                "    return;\n"
15409                "  }\n"
15410                "}\n",
15411                BreakBeforeBraceShortIfs);
15412   verifyFormat("void f(bool b)\n"
15413                "{\n"
15414                "  if (b) return;\n"
15415                "}\n",
15416                BreakBeforeBraceShortIfs);
15417   verifyFormat("void f(bool b)\n"
15418                "{\n"
15419                "  if constexpr (b) return;\n"
15420                "}\n",
15421                BreakBeforeBraceShortIfs);
15422   verifyFormat("void f(bool b)\n"
15423                "{\n"
15424                "  if CONSTEXPR (b) return;\n"
15425                "}\n",
15426                BreakBeforeBraceShortIfs);
15427   verifyFormat("void f(bool b)\n"
15428                "{\n"
15429                "  while (b)\n"
15430                "  {\n"
15431                "    return;\n"
15432                "  }\n"
15433                "}\n",
15434                BreakBeforeBraceShortIfs);
15435 }
15436 
15437 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
15438   FormatStyle WhitesmithsBraceStyle = getLLVMStyle();
15439   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
15440 
15441   // Make a few changes to the style for testing purposes
15442   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
15443       FormatStyle::SFS_Empty;
15444   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
15445   WhitesmithsBraceStyle.ColumnLimit = 0;
15446 
15447   // FIXME: this test case can't decide whether there should be a blank line
15448   // after the ~D() line or not. It adds one if one doesn't exist in the test
15449   // and it removes the line if one exists.
15450   /*
15451   verifyFormat("class A;\n"
15452                "namespace B\n"
15453                "  {\n"
15454                "class C;\n"
15455                "// Comment\n"
15456                "class D\n"
15457                "  {\n"
15458                "public:\n"
15459                "  D();\n"
15460                "  ~D() {}\n"
15461                "private:\n"
15462                "  enum E\n"
15463                "    {\n"
15464                "    F\n"
15465                "    }\n"
15466                "  };\n"
15467                "  } // namespace B\n",
15468                WhitesmithsBraceStyle);
15469   */
15470 
15471   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
15472   verifyFormat("namespace a\n"
15473                "  {\n"
15474                "class A\n"
15475                "  {\n"
15476                "  void f()\n"
15477                "    {\n"
15478                "    if (true)\n"
15479                "      {\n"
15480                "      a();\n"
15481                "      b();\n"
15482                "      }\n"
15483                "    }\n"
15484                "  void g()\n"
15485                "    {\n"
15486                "    return;\n"
15487                "    }\n"
15488                "  };\n"
15489                "struct B\n"
15490                "  {\n"
15491                "  int x;\n"
15492                "  };\n"
15493                "  } // namespace a",
15494                WhitesmithsBraceStyle);
15495 
15496   verifyFormat("namespace a\n"
15497                "  {\n"
15498                "namespace b\n"
15499                "  {\n"
15500                "class A\n"
15501                "  {\n"
15502                "  void f()\n"
15503                "    {\n"
15504                "    if (true)\n"
15505                "      {\n"
15506                "      a();\n"
15507                "      b();\n"
15508                "      }\n"
15509                "    }\n"
15510                "  void g()\n"
15511                "    {\n"
15512                "    return;\n"
15513                "    }\n"
15514                "  };\n"
15515                "struct B\n"
15516                "  {\n"
15517                "  int x;\n"
15518                "  };\n"
15519                "  } // namespace b\n"
15520                "  } // namespace a",
15521                WhitesmithsBraceStyle);
15522 
15523   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
15524   verifyFormat("namespace a\n"
15525                "  {\n"
15526                "namespace b\n"
15527                "  {\n"
15528                "  class A\n"
15529                "    {\n"
15530                "    void f()\n"
15531                "      {\n"
15532                "      if (true)\n"
15533                "        {\n"
15534                "        a();\n"
15535                "        b();\n"
15536                "        }\n"
15537                "      }\n"
15538                "    void g()\n"
15539                "      {\n"
15540                "      return;\n"
15541                "      }\n"
15542                "    };\n"
15543                "  struct B\n"
15544                "    {\n"
15545                "    int x;\n"
15546                "    };\n"
15547                "  } // namespace b\n"
15548                "  } // namespace a",
15549                WhitesmithsBraceStyle);
15550 
15551   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
15552   verifyFormat("namespace a\n"
15553                "  {\n"
15554                "  namespace b\n"
15555                "    {\n"
15556                "    class A\n"
15557                "      {\n"
15558                "      void f()\n"
15559                "        {\n"
15560                "        if (true)\n"
15561                "          {\n"
15562                "          a();\n"
15563                "          b();\n"
15564                "          }\n"
15565                "        }\n"
15566                "      void g()\n"
15567                "        {\n"
15568                "        return;\n"
15569                "        }\n"
15570                "      };\n"
15571                "    struct B\n"
15572                "      {\n"
15573                "      int x;\n"
15574                "      };\n"
15575                "    } // namespace b\n"
15576                "  }   // namespace a",
15577                WhitesmithsBraceStyle);
15578 
15579   verifyFormat("void f()\n"
15580                "  {\n"
15581                "  if (true)\n"
15582                "    {\n"
15583                "    a();\n"
15584                "    }\n"
15585                "  else if (false)\n"
15586                "    {\n"
15587                "    b();\n"
15588                "    }\n"
15589                "  else\n"
15590                "    {\n"
15591                "    c();\n"
15592                "    }\n"
15593                "  }\n",
15594                WhitesmithsBraceStyle);
15595 
15596   verifyFormat("void f()\n"
15597                "  {\n"
15598                "  for (int i = 0; i < 10; ++i)\n"
15599                "    {\n"
15600                "    a();\n"
15601                "    }\n"
15602                "  while (false)\n"
15603                "    {\n"
15604                "    b();\n"
15605                "    }\n"
15606                "  do\n"
15607                "    {\n"
15608                "    c();\n"
15609                "    } while (false)\n"
15610                "  }\n",
15611                WhitesmithsBraceStyle);
15612 
15613   WhitesmithsBraceStyle.IndentCaseLabels = true;
15614   verifyFormat("void switchTest1(int a)\n"
15615                "  {\n"
15616                "  switch (a)\n"
15617                "    {\n"
15618                "    case 2:\n"
15619                "      {\n"
15620                "      }\n"
15621                "      break;\n"
15622                "    }\n"
15623                "  }\n",
15624                WhitesmithsBraceStyle);
15625 
15626   verifyFormat("void switchTest2(int a)\n"
15627                "  {\n"
15628                "  switch (a)\n"
15629                "    {\n"
15630                "    case 0:\n"
15631                "      break;\n"
15632                "    case 1:\n"
15633                "      {\n"
15634                "      break;\n"
15635                "      }\n"
15636                "    case 2:\n"
15637                "      {\n"
15638                "      }\n"
15639                "      break;\n"
15640                "    default:\n"
15641                "      break;\n"
15642                "    }\n"
15643                "  }\n",
15644                WhitesmithsBraceStyle);
15645 
15646   verifyFormat("void switchTest3(int a)\n"
15647                "  {\n"
15648                "  switch (a)\n"
15649                "    {\n"
15650                "    case 0:\n"
15651                "      {\n"
15652                "      foo(x);\n"
15653                "      }\n"
15654                "      break;\n"
15655                "    default:\n"
15656                "      {\n"
15657                "      foo(1);\n"
15658                "      }\n"
15659                "      break;\n"
15660                "    }\n"
15661                "  }\n",
15662                WhitesmithsBraceStyle);
15663 
15664   WhitesmithsBraceStyle.IndentCaseLabels = false;
15665 
15666   verifyFormat("void switchTest4(int a)\n"
15667                "  {\n"
15668                "  switch (a)\n"
15669                "    {\n"
15670                "  case 2:\n"
15671                "    {\n"
15672                "    }\n"
15673                "    break;\n"
15674                "    }\n"
15675                "  }\n",
15676                WhitesmithsBraceStyle);
15677 
15678   verifyFormat("void switchTest5(int a)\n"
15679                "  {\n"
15680                "  switch (a)\n"
15681                "    {\n"
15682                "  case 0:\n"
15683                "    break;\n"
15684                "  case 1:\n"
15685                "    {\n"
15686                "    foo();\n"
15687                "    break;\n"
15688                "    }\n"
15689                "  case 2:\n"
15690                "    {\n"
15691                "    }\n"
15692                "    break;\n"
15693                "  default:\n"
15694                "    break;\n"
15695                "    }\n"
15696                "  }\n",
15697                WhitesmithsBraceStyle);
15698 
15699   verifyFormat("void switchTest6(int a)\n"
15700                "  {\n"
15701                "  switch (a)\n"
15702                "    {\n"
15703                "  case 0:\n"
15704                "    {\n"
15705                "    foo(x);\n"
15706                "    }\n"
15707                "    break;\n"
15708                "  default:\n"
15709                "    {\n"
15710                "    foo(1);\n"
15711                "    }\n"
15712                "    break;\n"
15713                "    }\n"
15714                "  }\n",
15715                WhitesmithsBraceStyle);
15716 
15717   verifyFormat("enum X\n"
15718                "  {\n"
15719                "  Y = 0, // testing\n"
15720                "  }\n",
15721                WhitesmithsBraceStyle);
15722 
15723   verifyFormat("enum X\n"
15724                "  {\n"
15725                "  Y = 0\n"
15726                "  }\n",
15727                WhitesmithsBraceStyle);
15728   verifyFormat("enum X\n"
15729                "  {\n"
15730                "  Y = 0,\n"
15731                "  Z = 1\n"
15732                "  };\n",
15733                WhitesmithsBraceStyle);
15734 
15735   verifyFormat("@interface BSApplicationController ()\n"
15736                "  {\n"
15737                "@private\n"
15738                "  id _extraIvar;\n"
15739                "  }\n"
15740                "@end\n",
15741                WhitesmithsBraceStyle);
15742 
15743   verifyFormat("#ifdef _DEBUG\n"
15744                "int foo(int i = 0)\n"
15745                "#else\n"
15746                "int foo(int i = 5)\n"
15747                "#endif\n"
15748                "  {\n"
15749                "  return i;\n"
15750                "  }",
15751                WhitesmithsBraceStyle);
15752 
15753   verifyFormat("void foo() {}\n"
15754                "void bar()\n"
15755                "#ifdef _DEBUG\n"
15756                "  {\n"
15757                "  foo();\n"
15758                "  }\n"
15759                "#else\n"
15760                "  {\n"
15761                "  }\n"
15762                "#endif",
15763                WhitesmithsBraceStyle);
15764 
15765   verifyFormat("void foobar()\n"
15766                "  {\n"
15767                "  int i = 5;\n"
15768                "  }\n"
15769                "#ifdef _DEBUG\n"
15770                "void bar()\n"
15771                "  {\n"
15772                "  }\n"
15773                "#else\n"
15774                "void bar()\n"
15775                "  {\n"
15776                "  foobar();\n"
15777                "  }\n"
15778                "#endif",
15779                WhitesmithsBraceStyle);
15780 
15781   // This shouldn't affect ObjC blocks..
15782   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
15783                "  // ...\n"
15784                "  int i;\n"
15785                "}];",
15786                WhitesmithsBraceStyle);
15787   verifyFormat("void (^block)(void) = ^{\n"
15788                "  // ...\n"
15789                "  int i;\n"
15790                "};",
15791                WhitesmithsBraceStyle);
15792   // .. or dict literals.
15793   verifyFormat("void f()\n"
15794                "  {\n"
15795                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
15796                "  }",
15797                WhitesmithsBraceStyle);
15798 
15799   verifyFormat("int f()\n"
15800                "  { // comment\n"
15801                "  return 42;\n"
15802                "  }",
15803                WhitesmithsBraceStyle);
15804 
15805   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
15806   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
15807       FormatStyle::SIS_Always;
15808   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
15809   verifyFormat("void f(bool b)\n"
15810                "  {\n"
15811                "  if (b)\n"
15812                "    {\n"
15813                "    return;\n"
15814                "    }\n"
15815                "  }\n",
15816                BreakBeforeBraceShortIfs);
15817   verifyFormat("void f(bool b)\n"
15818                "  {\n"
15819                "  if (b) return;\n"
15820                "  }\n",
15821                BreakBeforeBraceShortIfs);
15822   verifyFormat("void f(bool b)\n"
15823                "  {\n"
15824                "  while (b)\n"
15825                "    {\n"
15826                "    return;\n"
15827                "    }\n"
15828                "  }\n",
15829                BreakBeforeBraceShortIfs);
15830 }
15831 
15832 TEST_F(FormatTest, GNUBraceBreaking) {
15833   FormatStyle GNUBraceStyle = getLLVMStyle();
15834   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
15835   verifyFormat("namespace a\n"
15836                "{\n"
15837                "class A\n"
15838                "{\n"
15839                "  void f()\n"
15840                "  {\n"
15841                "    int a;\n"
15842                "    {\n"
15843                "      int b;\n"
15844                "    }\n"
15845                "    if (true)\n"
15846                "      {\n"
15847                "        a();\n"
15848                "        b();\n"
15849                "      }\n"
15850                "  }\n"
15851                "  void g() { return; }\n"
15852                "}\n"
15853                "} // namespace a",
15854                GNUBraceStyle);
15855 
15856   verifyFormat("void f()\n"
15857                "{\n"
15858                "  if (true)\n"
15859                "    {\n"
15860                "      a();\n"
15861                "    }\n"
15862                "  else if (false)\n"
15863                "    {\n"
15864                "      b();\n"
15865                "    }\n"
15866                "  else\n"
15867                "    {\n"
15868                "      c();\n"
15869                "    }\n"
15870                "}\n",
15871                GNUBraceStyle);
15872 
15873   verifyFormat("void f()\n"
15874                "{\n"
15875                "  for (int i = 0; i < 10; ++i)\n"
15876                "    {\n"
15877                "      a();\n"
15878                "    }\n"
15879                "  while (false)\n"
15880                "    {\n"
15881                "      b();\n"
15882                "    }\n"
15883                "  do\n"
15884                "    {\n"
15885                "      c();\n"
15886                "    }\n"
15887                "  while (false);\n"
15888                "}\n",
15889                GNUBraceStyle);
15890 
15891   verifyFormat("void f(int a)\n"
15892                "{\n"
15893                "  switch (a)\n"
15894                "    {\n"
15895                "    case 0:\n"
15896                "      break;\n"
15897                "    case 1:\n"
15898                "      {\n"
15899                "        break;\n"
15900                "      }\n"
15901                "    case 2:\n"
15902                "      {\n"
15903                "      }\n"
15904                "      break;\n"
15905                "    default:\n"
15906                "      break;\n"
15907                "    }\n"
15908                "}\n",
15909                GNUBraceStyle);
15910 
15911   verifyFormat("enum X\n"
15912                "{\n"
15913                "  Y = 0,\n"
15914                "}\n",
15915                GNUBraceStyle);
15916 
15917   verifyFormat("@interface BSApplicationController ()\n"
15918                "{\n"
15919                "@private\n"
15920                "  id _extraIvar;\n"
15921                "}\n"
15922                "@end\n",
15923                GNUBraceStyle);
15924 
15925   verifyFormat("#ifdef _DEBUG\n"
15926                "int foo(int i = 0)\n"
15927                "#else\n"
15928                "int foo(int i = 5)\n"
15929                "#endif\n"
15930                "{\n"
15931                "  return i;\n"
15932                "}",
15933                GNUBraceStyle);
15934 
15935   verifyFormat("void foo() {}\n"
15936                "void bar()\n"
15937                "#ifdef _DEBUG\n"
15938                "{\n"
15939                "  foo();\n"
15940                "}\n"
15941                "#else\n"
15942                "{\n"
15943                "}\n"
15944                "#endif",
15945                GNUBraceStyle);
15946 
15947   verifyFormat("void foobar() { int i = 5; }\n"
15948                "#ifdef _DEBUG\n"
15949                "void bar() {}\n"
15950                "#else\n"
15951                "void bar() { foobar(); }\n"
15952                "#endif",
15953                GNUBraceStyle);
15954 }
15955 
15956 TEST_F(FormatTest, WebKitBraceBreaking) {
15957   FormatStyle WebKitBraceStyle = getLLVMStyle();
15958   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
15959   WebKitBraceStyle.FixNamespaceComments = false;
15960   verifyFormat("namespace a {\n"
15961                "class A {\n"
15962                "  void f()\n"
15963                "  {\n"
15964                "    if (true) {\n"
15965                "      a();\n"
15966                "      b();\n"
15967                "    }\n"
15968                "  }\n"
15969                "  void g() { return; }\n"
15970                "};\n"
15971                "enum E {\n"
15972                "  A,\n"
15973                "  // foo\n"
15974                "  B,\n"
15975                "  C\n"
15976                "};\n"
15977                "struct B {\n"
15978                "  int x;\n"
15979                "};\n"
15980                "}\n",
15981                WebKitBraceStyle);
15982   verifyFormat("struct S {\n"
15983                "  int Type;\n"
15984                "  union {\n"
15985                "    int x;\n"
15986                "    double y;\n"
15987                "  } Value;\n"
15988                "  class C {\n"
15989                "    MyFavoriteType Value;\n"
15990                "  } Class;\n"
15991                "};\n",
15992                WebKitBraceStyle);
15993 }
15994 
15995 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
15996   verifyFormat("void f() {\n"
15997                "  try {\n"
15998                "  } catch (const Exception &e) {\n"
15999                "  }\n"
16000                "}\n",
16001                getLLVMStyle());
16002 }
16003 
16004 TEST_F(FormatTest, UnderstandsPragmas) {
16005   verifyFormat("#pragma omp reduction(| : var)");
16006   verifyFormat("#pragma omp reduction(+ : var)");
16007 
16008   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
16009             "(including parentheses).",
16010             format("#pragma    mark   Any non-hyphenated or hyphenated string "
16011                    "(including parentheses)."));
16012 }
16013 
16014 TEST_F(FormatTest, UnderstandPragmaOption) {
16015   verifyFormat("#pragma option -C -A");
16016 
16017   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
16018 }
16019 
16020 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
16021   FormatStyle Style = getLLVMStyle();
16022   Style.ColumnLimit = 20;
16023 
16024   // See PR41213
16025   EXPECT_EQ("/*\n"
16026             " *\t9012345\n"
16027             " * /8901\n"
16028             " */",
16029             format("/*\n"
16030                    " *\t9012345 /8901\n"
16031                    " */",
16032                    Style));
16033   EXPECT_EQ("/*\n"
16034             " *345678\n"
16035             " *\t/8901\n"
16036             " */",
16037             format("/*\n"
16038                    " *345678\t/8901\n"
16039                    " */",
16040                    Style));
16041 
16042   verifyFormat("int a; // the\n"
16043                "       // comment",
16044                Style);
16045   EXPECT_EQ("int a; /* first line\n"
16046             "        * second\n"
16047             "        * line third\n"
16048             "        * line\n"
16049             "        */",
16050             format("int a; /* first line\n"
16051                    "        * second\n"
16052                    "        * line third\n"
16053                    "        * line\n"
16054                    "        */",
16055                    Style));
16056   EXPECT_EQ("int a; // first line\n"
16057             "       // second\n"
16058             "       // line third\n"
16059             "       // line",
16060             format("int a; // first line\n"
16061                    "       // second line\n"
16062                    "       // third line",
16063                    Style));
16064 
16065   Style.PenaltyExcessCharacter = 90;
16066   verifyFormat("int a; // the comment", Style);
16067   EXPECT_EQ("int a; // the comment\n"
16068             "       // aaa",
16069             format("int a; // the comment aaa", Style));
16070   EXPECT_EQ("int a; /* first line\n"
16071             "        * second line\n"
16072             "        * third line\n"
16073             "        */",
16074             format("int a; /* first line\n"
16075                    "        * second line\n"
16076                    "        * third line\n"
16077                    "        */",
16078                    Style));
16079   EXPECT_EQ("int a; // first line\n"
16080             "       // second line\n"
16081             "       // third line",
16082             format("int a; // first line\n"
16083                    "       // second line\n"
16084                    "       // third line",
16085                    Style));
16086   // FIXME: Investigate why this is not getting the same layout as the test
16087   // above.
16088   EXPECT_EQ("int a; /* first line\n"
16089             "        * second line\n"
16090             "        * third line\n"
16091             "        */",
16092             format("int a; /* first line second line third line"
16093                    "\n*/",
16094                    Style));
16095 
16096   EXPECT_EQ("// foo bar baz bazfoo\n"
16097             "// foo bar foo bar\n",
16098             format("// foo bar baz bazfoo\n"
16099                    "// foo bar foo           bar\n",
16100                    Style));
16101   EXPECT_EQ("// foo bar baz bazfoo\n"
16102             "// foo bar foo bar\n",
16103             format("// foo bar baz      bazfoo\n"
16104                    "// foo            bar foo bar\n",
16105                    Style));
16106 
16107   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
16108   // next one.
16109   EXPECT_EQ("// foo bar baz bazfoo\n"
16110             "// bar foo bar\n",
16111             format("// foo bar baz      bazfoo bar\n"
16112                    "// foo            bar\n",
16113                    Style));
16114 
16115   EXPECT_EQ("// foo bar baz bazfoo\n"
16116             "// foo bar baz bazfoo\n"
16117             "// bar foo bar\n",
16118             format("// foo bar baz      bazfoo\n"
16119                    "// foo bar baz      bazfoo bar\n"
16120                    "// foo bar\n",
16121                    Style));
16122 
16123   EXPECT_EQ("// foo bar baz bazfoo\n"
16124             "// foo bar baz bazfoo\n"
16125             "// bar foo bar\n",
16126             format("// foo bar baz      bazfoo\n"
16127                    "// foo bar baz      bazfoo bar\n"
16128                    "// foo           bar\n",
16129                    Style));
16130 
16131   // Make sure we do not keep protruding characters if strict mode reflow is
16132   // cheaper than keeping protruding characters.
16133   Style.ColumnLimit = 21;
16134   EXPECT_EQ(
16135       "// foo foo foo foo\n"
16136       "// foo foo foo foo\n"
16137       "// foo foo foo foo\n",
16138       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
16139 
16140   EXPECT_EQ("int a = /* long block\n"
16141             "           comment */\n"
16142             "    42;",
16143             format("int a = /* long block comment */ 42;", Style));
16144 }
16145 
16146 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
16147   for (size_t i = 1; i < Styles.size(); ++i)                                   \
16148   EXPECT_EQ(Styles[0], Styles[i])                                              \
16149       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
16150 
16151 TEST_F(FormatTest, GetsPredefinedStyleByName) {
16152   SmallVector<FormatStyle, 3> Styles;
16153   Styles.resize(3);
16154 
16155   Styles[0] = getLLVMStyle();
16156   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
16157   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
16158   EXPECT_ALL_STYLES_EQUAL(Styles);
16159 
16160   Styles[0] = getGoogleStyle();
16161   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
16162   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
16163   EXPECT_ALL_STYLES_EQUAL(Styles);
16164 
16165   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
16166   EXPECT_TRUE(
16167       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
16168   EXPECT_TRUE(
16169       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
16170   EXPECT_ALL_STYLES_EQUAL(Styles);
16171 
16172   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
16173   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
16174   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
16175   EXPECT_ALL_STYLES_EQUAL(Styles);
16176 
16177   Styles[0] = getMozillaStyle();
16178   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
16179   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
16180   EXPECT_ALL_STYLES_EQUAL(Styles);
16181 
16182   Styles[0] = getWebKitStyle();
16183   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
16184   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
16185   EXPECT_ALL_STYLES_EQUAL(Styles);
16186 
16187   Styles[0] = getGNUStyle();
16188   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
16189   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
16190   EXPECT_ALL_STYLES_EQUAL(Styles);
16191 
16192   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
16193 }
16194 
16195 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
16196   SmallVector<FormatStyle, 8> Styles;
16197   Styles.resize(2);
16198 
16199   Styles[0] = getGoogleStyle();
16200   Styles[1] = getLLVMStyle();
16201   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
16202   EXPECT_ALL_STYLES_EQUAL(Styles);
16203 
16204   Styles.resize(5);
16205   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
16206   Styles[1] = getLLVMStyle();
16207   Styles[1].Language = FormatStyle::LK_JavaScript;
16208   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
16209 
16210   Styles[2] = getLLVMStyle();
16211   Styles[2].Language = FormatStyle::LK_JavaScript;
16212   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
16213                                   "BasedOnStyle: Google",
16214                                   &Styles[2])
16215                    .value());
16216 
16217   Styles[3] = getLLVMStyle();
16218   Styles[3].Language = FormatStyle::LK_JavaScript;
16219   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
16220                                   "Language: JavaScript",
16221                                   &Styles[3])
16222                    .value());
16223 
16224   Styles[4] = getLLVMStyle();
16225   Styles[4].Language = FormatStyle::LK_JavaScript;
16226   EXPECT_EQ(0, parseConfiguration("---\n"
16227                                   "BasedOnStyle: LLVM\n"
16228                                   "IndentWidth: 123\n"
16229                                   "---\n"
16230                                   "BasedOnStyle: Google\n"
16231                                   "Language: JavaScript",
16232                                   &Styles[4])
16233                    .value());
16234   EXPECT_ALL_STYLES_EQUAL(Styles);
16235 }
16236 
16237 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
16238   Style.FIELD = false;                                                         \
16239   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
16240   EXPECT_TRUE(Style.FIELD);                                                    \
16241   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
16242   EXPECT_FALSE(Style.FIELD);
16243 
16244 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
16245 
16246 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
16247   Style.STRUCT.FIELD = false;                                                  \
16248   EXPECT_EQ(0,                                                                 \
16249             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
16250                 .value());                                                     \
16251   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
16252   EXPECT_EQ(0,                                                                 \
16253             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
16254                 .value());                                                     \
16255   EXPECT_FALSE(Style.STRUCT.FIELD);
16256 
16257 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
16258   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
16259 
16260 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
16261   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
16262   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
16263   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
16264 
16265 TEST_F(FormatTest, ParsesConfigurationBools) {
16266   FormatStyle Style = {};
16267   Style.Language = FormatStyle::LK_Cpp;
16268   CHECK_PARSE_BOOL(AlignTrailingComments);
16269   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
16270   CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine);
16271   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
16272   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
16273   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
16274   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
16275   CHECK_PARSE_BOOL(BinPackArguments);
16276   CHECK_PARSE_BOOL(BinPackParameters);
16277   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
16278   CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
16279   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
16280   CHECK_PARSE_BOOL(BreakStringLiterals);
16281   CHECK_PARSE_BOOL(CompactNamespaces);
16282   CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
16283   CHECK_PARSE_BOOL(DeriveLineEnding);
16284   CHECK_PARSE_BOOL(DerivePointerAlignment);
16285   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
16286   CHECK_PARSE_BOOL(DisableFormat);
16287   CHECK_PARSE_BOOL(IndentAccessModifiers);
16288   CHECK_PARSE_BOOL(IndentCaseLabels);
16289   CHECK_PARSE_BOOL(IndentCaseBlocks);
16290   CHECK_PARSE_BOOL(IndentGotoLabels);
16291   CHECK_PARSE_BOOL(IndentRequires);
16292   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
16293   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
16294   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
16295   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
16296   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
16297   CHECK_PARSE_BOOL(ReflowComments);
16298   CHECK_PARSE_BOOL(SortUsingDeclarations);
16299   CHECK_PARSE_BOOL(SpacesInParentheses);
16300   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
16301   CHECK_PARSE_BOOL(SpacesInAngles);
16302   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
16303   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
16304   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
16305   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
16306   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
16307   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
16308   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
16309   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
16310   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
16311   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
16312   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
16313   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
16314   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
16315   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
16316   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
16317   CHECK_PARSE_BOOL(UseCRLF);
16318 
16319   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
16320   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
16321   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
16322   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
16323   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
16324   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
16325   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
16326   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
16327   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
16328   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
16329   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
16330   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
16331   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
16332   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
16333   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
16334   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
16335   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
16336 }
16337 
16338 #undef CHECK_PARSE_BOOL
16339 
16340 TEST_F(FormatTest, ParsesConfiguration) {
16341   FormatStyle Style = {};
16342   Style.Language = FormatStyle::LK_Cpp;
16343   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
16344   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
16345               ConstructorInitializerIndentWidth, 1234u);
16346   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
16347   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
16348   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
16349   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
16350   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
16351               PenaltyBreakBeforeFirstCallParameter, 1234u);
16352   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
16353               PenaltyBreakTemplateDeclaration, 1234u);
16354   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
16355   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
16356               PenaltyReturnTypeOnItsOwnLine, 1234u);
16357   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
16358               SpacesBeforeTrailingComments, 1234u);
16359   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
16360   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
16361   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
16362 
16363   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16364   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
16365               FormatStyle::ACS_None);
16366   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
16367               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
16368   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
16369               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
16370   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
16371               AlignConsecutiveAssignments,
16372               FormatStyle::ACS_AcrossEmptyLinesAndComments);
16373   // For backwards compability, false / true should still parse
16374   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
16375               FormatStyle::ACS_None);
16376   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
16377               FormatStyle::ACS_Consecutive);
16378 
16379   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
16380   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
16381               FormatStyle::ACS_None);
16382   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
16383               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
16384   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
16385               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
16386   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
16387               AlignConsecutiveBitFields,
16388               FormatStyle::ACS_AcrossEmptyLinesAndComments);
16389   // For backwards compability, false / true should still parse
16390   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
16391               FormatStyle::ACS_None);
16392   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
16393               FormatStyle::ACS_Consecutive);
16394 
16395   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16396   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
16397               FormatStyle::ACS_None);
16398   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
16399               FormatStyle::ACS_Consecutive);
16400   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
16401               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
16402   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
16403               AlignConsecutiveMacros,
16404               FormatStyle::ACS_AcrossEmptyLinesAndComments);
16405   // For backwards compability, false / true should still parse
16406   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
16407               FormatStyle::ACS_None);
16408   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
16409               FormatStyle::ACS_Consecutive);
16410 
16411   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16412   CHECK_PARSE("AlignConsecutiveDeclarations: None",
16413               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
16414   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
16415               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
16416   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
16417               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
16418   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
16419               AlignConsecutiveDeclarations,
16420               FormatStyle::ACS_AcrossEmptyLinesAndComments);
16421   // For backwards compability, false / true should still parse
16422   CHECK_PARSE("AlignConsecutiveDeclarations: false",
16423               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
16424   CHECK_PARSE("AlignConsecutiveDeclarations: true",
16425               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
16426 
16427   Style.PointerAlignment = FormatStyle::PAS_Middle;
16428   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
16429               FormatStyle::PAS_Left);
16430   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
16431               FormatStyle::PAS_Right);
16432   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
16433               FormatStyle::PAS_Middle);
16434   // For backward compatibility:
16435   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
16436               FormatStyle::PAS_Left);
16437   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
16438               FormatStyle::PAS_Right);
16439   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
16440               FormatStyle::PAS_Middle);
16441 
16442   Style.Standard = FormatStyle::LS_Auto;
16443   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
16444   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
16445   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
16446   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
16447   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
16448   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
16449   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
16450   // Legacy aliases:
16451   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
16452   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
16453   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
16454   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
16455 
16456   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16457   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
16458               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
16459   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
16460               FormatStyle::BOS_None);
16461   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
16462               FormatStyle::BOS_All);
16463   // For backward compatibility:
16464   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
16465               FormatStyle::BOS_None);
16466   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
16467               FormatStyle::BOS_All);
16468 
16469   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
16470   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
16471               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
16472   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
16473               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
16474   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
16475               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
16476   // For backward compatibility:
16477   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
16478               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
16479 
16480   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
16481   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
16482               FormatStyle::BILS_BeforeComma);
16483   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
16484               FormatStyle::BILS_AfterColon);
16485   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
16486               FormatStyle::BILS_BeforeColon);
16487   // For backward compatibility:
16488   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
16489               FormatStyle::BILS_BeforeComma);
16490 
16491   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
16492   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
16493               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
16494   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
16495               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
16496   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
16497               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
16498   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
16499               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
16500 
16501   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
16502   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
16503               FormatStyle::BAS_Align);
16504   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
16505               FormatStyle::BAS_DontAlign);
16506   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
16507               FormatStyle::BAS_AlwaysBreak);
16508   // For backward compatibility:
16509   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
16510               FormatStyle::BAS_DontAlign);
16511   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
16512               FormatStyle::BAS_Align);
16513 
16514   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16515   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
16516               FormatStyle::ENAS_DontAlign);
16517   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
16518               FormatStyle::ENAS_Left);
16519   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
16520               FormatStyle::ENAS_Right);
16521   // For backward compatibility:
16522   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
16523               FormatStyle::ENAS_Left);
16524   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
16525               FormatStyle::ENAS_Right);
16526 
16527   Style.AlignOperands = FormatStyle::OAS_Align;
16528   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
16529               FormatStyle::OAS_DontAlign);
16530   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
16531   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
16532               FormatStyle::OAS_AlignAfterOperator);
16533   // For backward compatibility:
16534   CHECK_PARSE("AlignOperands: false", AlignOperands,
16535               FormatStyle::OAS_DontAlign);
16536   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
16537 
16538   Style.UseTab = FormatStyle::UT_ForIndentation;
16539   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
16540   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
16541   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
16542   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
16543               FormatStyle::UT_ForContinuationAndIndentation);
16544   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
16545               FormatStyle::UT_AlignWithSpaces);
16546   // For backward compatibility:
16547   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
16548   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
16549 
16550   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
16551   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
16552               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
16553   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
16554               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
16555   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
16556               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
16557   // For backward compatibility:
16558   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
16559               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
16560   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
16561               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
16562 
16563   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
16564   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
16565               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
16566   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
16567               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
16568   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
16569               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
16570   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
16571               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
16572   // For backward compatibility:
16573   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
16574               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
16575   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
16576               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
16577 
16578   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
16579   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
16580               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
16581   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
16582               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
16583   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
16584               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
16585   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
16586               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
16587 
16588   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
16589   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
16590               FormatStyle::SBPO_Never);
16591   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
16592               FormatStyle::SBPO_Always);
16593   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
16594               FormatStyle::SBPO_ControlStatements);
16595   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
16596               FormatStyle::SBPO_NonEmptyParentheses);
16597   // For backward compatibility:
16598   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
16599               FormatStyle::SBPO_Never);
16600   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
16601               FormatStyle::SBPO_ControlStatements);
16602 
16603   Style.ColumnLimit = 123;
16604   FormatStyle BaseStyle = getLLVMStyle();
16605   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
16606   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
16607 
16608   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
16609   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
16610               FormatStyle::BS_Attach);
16611   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
16612               FormatStyle::BS_Linux);
16613   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
16614               FormatStyle::BS_Mozilla);
16615   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
16616               FormatStyle::BS_Stroustrup);
16617   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
16618               FormatStyle::BS_Allman);
16619   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
16620               FormatStyle::BS_Whitesmiths);
16621   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
16622   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
16623               FormatStyle::BS_WebKit);
16624   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
16625               FormatStyle::BS_Custom);
16626 
16627   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
16628   CHECK_PARSE("BraceWrapping:\n"
16629               "  AfterControlStatement: MultiLine",
16630               BraceWrapping.AfterControlStatement,
16631               FormatStyle::BWACS_MultiLine);
16632   CHECK_PARSE("BraceWrapping:\n"
16633               "  AfterControlStatement: Always",
16634               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
16635   CHECK_PARSE("BraceWrapping:\n"
16636               "  AfterControlStatement: Never",
16637               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
16638   // For backward compatibility:
16639   CHECK_PARSE("BraceWrapping:\n"
16640               "  AfterControlStatement: true",
16641               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
16642   CHECK_PARSE("BraceWrapping:\n"
16643               "  AfterControlStatement: false",
16644               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
16645 
16646   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
16647   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
16648               FormatStyle::RTBS_None);
16649   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
16650               FormatStyle::RTBS_All);
16651   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
16652               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
16653   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
16654               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
16655   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
16656               AlwaysBreakAfterReturnType,
16657               FormatStyle::RTBS_TopLevelDefinitions);
16658 
16659   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
16660   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
16661               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
16662   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
16663               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
16664   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
16665               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
16666   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
16667               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
16668   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
16669               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
16670 
16671   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
16672   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
16673               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
16674   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
16675               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
16676   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
16677               AlwaysBreakAfterDefinitionReturnType,
16678               FormatStyle::DRTBS_TopLevel);
16679 
16680   Style.NamespaceIndentation = FormatStyle::NI_All;
16681   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
16682               FormatStyle::NI_None);
16683   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
16684               FormatStyle::NI_Inner);
16685   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
16686               FormatStyle::NI_All);
16687 
16688   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
16689   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
16690               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
16691   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
16692               AllowShortIfStatementsOnASingleLine,
16693               FormatStyle::SIS_WithoutElse);
16694   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
16695               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Always);
16696   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
16697               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
16698   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
16699               AllowShortIfStatementsOnASingleLine,
16700               FormatStyle::SIS_WithoutElse);
16701 
16702   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
16703   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
16704               FormatStyle::IEBS_AfterExternBlock);
16705   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
16706               FormatStyle::IEBS_Indent);
16707   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
16708               FormatStyle::IEBS_NoIndent);
16709   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
16710               FormatStyle::IEBS_Indent);
16711   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
16712               FormatStyle::IEBS_NoIndent);
16713 
16714   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
16715   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
16716               FormatStyle::BFCS_Both);
16717   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
16718               FormatStyle::BFCS_None);
16719   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
16720               FormatStyle::BFCS_Before);
16721   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
16722               FormatStyle::BFCS_After);
16723 
16724   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
16725   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
16726               FormatStyle::SJSIO_After);
16727   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
16728               FormatStyle::SJSIO_Before);
16729 
16730   // FIXME: This is required because parsing a configuration simply overwrites
16731   // the first N elements of the list instead of resetting it.
16732   Style.ForEachMacros.clear();
16733   std::vector<std::string> BoostForeach;
16734   BoostForeach.push_back("BOOST_FOREACH");
16735   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
16736   std::vector<std::string> BoostAndQForeach;
16737   BoostAndQForeach.push_back("BOOST_FOREACH");
16738   BoostAndQForeach.push_back("Q_FOREACH");
16739   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
16740               BoostAndQForeach);
16741 
16742   Style.AttributeMacros.clear();
16743   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
16744               std::vector<std::string>{"__capability"});
16745   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
16746               std::vector<std::string>({"attr1", "attr2"}));
16747 
16748   Style.StatementAttributeLikeMacros.clear();
16749   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
16750               StatementAttributeLikeMacros,
16751               std::vector<std::string>({"emit", "Q_EMIT"}));
16752 
16753   Style.StatementMacros.clear();
16754   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
16755               std::vector<std::string>{"QUNUSED"});
16756   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
16757               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
16758 
16759   Style.NamespaceMacros.clear();
16760   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
16761               std::vector<std::string>{"TESTSUITE"});
16762   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
16763               std::vector<std::string>({"TESTSUITE", "SUITE"}));
16764 
16765   Style.WhitespaceSensitiveMacros.clear();
16766   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
16767               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
16768   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
16769               WhitespaceSensitiveMacros,
16770               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
16771   Style.WhitespaceSensitiveMacros.clear();
16772   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
16773               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
16774   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
16775               WhitespaceSensitiveMacros,
16776               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
16777 
16778   Style.IncludeStyle.IncludeCategories.clear();
16779   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
16780       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
16781   CHECK_PARSE("IncludeCategories:\n"
16782               "  - Regex: abc/.*\n"
16783               "    Priority: 2\n"
16784               "  - Regex: .*\n"
16785               "    Priority: 1\n"
16786               "    CaseSensitive: true\n",
16787               IncludeStyle.IncludeCategories, ExpectedCategories);
16788   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
16789               "abc$");
16790   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
16791               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
16792 
16793   Style.SortIncludes = FormatStyle::SI_Never;
16794   CHECK_PARSE("SortIncludes: true", SortIncludes,
16795               FormatStyle::SI_CaseSensitive);
16796   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
16797   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
16798               FormatStyle::SI_CaseInsensitive);
16799   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
16800               FormatStyle::SI_CaseSensitive);
16801   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
16802 
16803   Style.RawStringFormats.clear();
16804   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
16805       {
16806           FormatStyle::LK_TextProto,
16807           {"pb", "proto"},
16808           {"PARSE_TEXT_PROTO"},
16809           /*CanonicalDelimiter=*/"",
16810           "llvm",
16811       },
16812       {
16813           FormatStyle::LK_Cpp,
16814           {"cc", "cpp"},
16815           {"C_CODEBLOCK", "CPPEVAL"},
16816           /*CanonicalDelimiter=*/"cc",
16817           /*BasedOnStyle=*/"",
16818       },
16819   };
16820 
16821   CHECK_PARSE("RawStringFormats:\n"
16822               "  - Language: TextProto\n"
16823               "    Delimiters:\n"
16824               "      - 'pb'\n"
16825               "      - 'proto'\n"
16826               "    EnclosingFunctions:\n"
16827               "      - 'PARSE_TEXT_PROTO'\n"
16828               "    BasedOnStyle: llvm\n"
16829               "  - Language: Cpp\n"
16830               "    Delimiters:\n"
16831               "      - 'cc'\n"
16832               "      - 'cpp'\n"
16833               "    EnclosingFunctions:\n"
16834               "      - 'C_CODEBLOCK'\n"
16835               "      - 'CPPEVAL'\n"
16836               "    CanonicalDelimiter: 'cc'",
16837               RawStringFormats, ExpectedRawStringFormats);
16838 
16839   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16840               "  Minimum: 0\n"
16841               "  Maximum: 0",
16842               SpacesInLineCommentPrefix.Minimum, 0u);
16843   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
16844   Style.SpacesInLineCommentPrefix.Minimum = 1;
16845   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16846               "  Minimum: 2",
16847               SpacesInLineCommentPrefix.Minimum, 0u);
16848   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16849               "  Maximum: -1",
16850               SpacesInLineCommentPrefix.Maximum, -1u);
16851   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16852               "  Minimum: 2",
16853               SpacesInLineCommentPrefix.Minimum, 2u);
16854   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16855               "  Maximum: 1",
16856               SpacesInLineCommentPrefix.Maximum, 1u);
16857   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
16858 }
16859 
16860 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
16861   FormatStyle Style = {};
16862   Style.Language = FormatStyle::LK_Cpp;
16863   CHECK_PARSE("Language: Cpp\n"
16864               "IndentWidth: 12",
16865               IndentWidth, 12u);
16866   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
16867                                "IndentWidth: 34",
16868                                &Style),
16869             ParseError::Unsuitable);
16870   FormatStyle BinPackedTCS = {};
16871   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
16872   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
16873                                "InsertTrailingCommas: Wrapped",
16874                                &BinPackedTCS),
16875             ParseError::BinPackTrailingCommaConflict);
16876   EXPECT_EQ(12u, Style.IndentWidth);
16877   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
16878   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
16879 
16880   Style.Language = FormatStyle::LK_JavaScript;
16881   CHECK_PARSE("Language: JavaScript\n"
16882               "IndentWidth: 12",
16883               IndentWidth, 12u);
16884   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
16885   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
16886                                "IndentWidth: 34",
16887                                &Style),
16888             ParseError::Unsuitable);
16889   EXPECT_EQ(23u, Style.IndentWidth);
16890   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
16891   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
16892 
16893   CHECK_PARSE("BasedOnStyle: LLVM\n"
16894               "IndentWidth: 67",
16895               IndentWidth, 67u);
16896 
16897   CHECK_PARSE("---\n"
16898               "Language: JavaScript\n"
16899               "IndentWidth: 12\n"
16900               "---\n"
16901               "Language: Cpp\n"
16902               "IndentWidth: 34\n"
16903               "...\n",
16904               IndentWidth, 12u);
16905 
16906   Style.Language = FormatStyle::LK_Cpp;
16907   CHECK_PARSE("---\n"
16908               "Language: JavaScript\n"
16909               "IndentWidth: 12\n"
16910               "---\n"
16911               "Language: Cpp\n"
16912               "IndentWidth: 34\n"
16913               "...\n",
16914               IndentWidth, 34u);
16915   CHECK_PARSE("---\n"
16916               "IndentWidth: 78\n"
16917               "---\n"
16918               "Language: JavaScript\n"
16919               "IndentWidth: 56\n"
16920               "...\n",
16921               IndentWidth, 78u);
16922 
16923   Style.ColumnLimit = 123;
16924   Style.IndentWidth = 234;
16925   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
16926   Style.TabWidth = 345;
16927   EXPECT_FALSE(parseConfiguration("---\n"
16928                                   "IndentWidth: 456\n"
16929                                   "BreakBeforeBraces: Allman\n"
16930                                   "---\n"
16931                                   "Language: JavaScript\n"
16932                                   "IndentWidth: 111\n"
16933                                   "TabWidth: 111\n"
16934                                   "---\n"
16935                                   "Language: Cpp\n"
16936                                   "BreakBeforeBraces: Stroustrup\n"
16937                                   "TabWidth: 789\n"
16938                                   "...\n",
16939                                   &Style));
16940   EXPECT_EQ(123u, Style.ColumnLimit);
16941   EXPECT_EQ(456u, Style.IndentWidth);
16942   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
16943   EXPECT_EQ(789u, Style.TabWidth);
16944 
16945   EXPECT_EQ(parseConfiguration("---\n"
16946                                "Language: JavaScript\n"
16947                                "IndentWidth: 56\n"
16948                                "---\n"
16949                                "IndentWidth: 78\n"
16950                                "...\n",
16951                                &Style),
16952             ParseError::Error);
16953   EXPECT_EQ(parseConfiguration("---\n"
16954                                "Language: JavaScript\n"
16955                                "IndentWidth: 56\n"
16956                                "---\n"
16957                                "Language: JavaScript\n"
16958                                "IndentWidth: 78\n"
16959                                "...\n",
16960                                &Style),
16961             ParseError::Error);
16962 
16963   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
16964 }
16965 
16966 #undef CHECK_PARSE
16967 
16968 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
16969   FormatStyle Style = {};
16970   Style.Language = FormatStyle::LK_JavaScript;
16971   Style.BreakBeforeTernaryOperators = true;
16972   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
16973   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
16974 
16975   Style.BreakBeforeTernaryOperators = true;
16976   EXPECT_EQ(0, parseConfiguration("---\n"
16977                                   "BasedOnStyle: Google\n"
16978                                   "---\n"
16979                                   "Language: JavaScript\n"
16980                                   "IndentWidth: 76\n"
16981                                   "...\n",
16982                                   &Style)
16983                    .value());
16984   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
16985   EXPECT_EQ(76u, Style.IndentWidth);
16986   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
16987 }
16988 
16989 TEST_F(FormatTest, ConfigurationRoundTripTest) {
16990   FormatStyle Style = getLLVMStyle();
16991   std::string YAML = configurationAsText(Style);
16992   FormatStyle ParsedStyle = {};
16993   ParsedStyle.Language = FormatStyle::LK_Cpp;
16994   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
16995   EXPECT_EQ(Style, ParsedStyle);
16996 }
16997 
16998 TEST_F(FormatTest, WorksFor8bitEncodings) {
16999   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
17000             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
17001             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
17002             "\"\xef\xee\xf0\xf3...\"",
17003             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
17004                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
17005                    "\xef\xee\xf0\xf3...\"",
17006                    getLLVMStyleWithColumns(12)));
17007 }
17008 
17009 TEST_F(FormatTest, HandlesUTF8BOM) {
17010   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
17011   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
17012             format("\xef\xbb\xbf#include <iostream>"));
17013   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
17014             format("\xef\xbb\xbf\n#include <iostream>"));
17015 }
17016 
17017 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
17018 #if !defined(_MSC_VER)
17019 
17020 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
17021   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
17022                getLLVMStyleWithColumns(35));
17023   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
17024                getLLVMStyleWithColumns(31));
17025   verifyFormat("// Однажды в студёную зимнюю пору...",
17026                getLLVMStyleWithColumns(36));
17027   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
17028   verifyFormat("/* Однажды в студёную зимнюю пору... */",
17029                getLLVMStyleWithColumns(39));
17030   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
17031                getLLVMStyleWithColumns(35));
17032 }
17033 
17034 TEST_F(FormatTest, SplitsUTF8Strings) {
17035   // Non-printable characters' width is currently considered to be the length in
17036   // bytes in UTF8. The characters can be displayed in very different manner
17037   // (zero-width, single width with a substitution glyph, expanded to their code
17038   // (e.g. "<8d>"), so there's no single correct way to handle them.
17039   EXPECT_EQ("\"aaaaÄ\"\n"
17040             "\"\xc2\x8d\";",
17041             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
17042   EXPECT_EQ("\"aaaaaaaÄ\"\n"
17043             "\"\xc2\x8d\";",
17044             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
17045   EXPECT_EQ("\"Однажды, в \"\n"
17046             "\"студёную \"\n"
17047             "\"зимнюю \"\n"
17048             "\"пору,\"",
17049             format("\"Однажды, в студёную зимнюю пору,\"",
17050                    getLLVMStyleWithColumns(13)));
17051   EXPECT_EQ(
17052       "\"一 二 三 \"\n"
17053       "\"四 五六 \"\n"
17054       "\"七 八 九 \"\n"
17055       "\"十\"",
17056       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
17057   EXPECT_EQ("\"一\t\"\n"
17058             "\"二 \t\"\n"
17059             "\"三 四 \"\n"
17060             "\"五\t\"\n"
17061             "\"六 \t\"\n"
17062             "\"七 \"\n"
17063             "\"八九十\tqq\"",
17064             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
17065                    getLLVMStyleWithColumns(11)));
17066 
17067   // UTF8 character in an escape sequence.
17068   EXPECT_EQ("\"aaaaaa\"\n"
17069             "\"\\\xC2\x8D\"",
17070             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
17071 }
17072 
17073 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
17074   EXPECT_EQ("const char *sssss =\n"
17075             "    \"一二三四五六七八\\\n"
17076             " 九 十\";",
17077             format("const char *sssss = \"一二三四五六七八\\\n"
17078                    " 九 十\";",
17079                    getLLVMStyleWithColumns(30)));
17080 }
17081 
17082 TEST_F(FormatTest, SplitsUTF8LineComments) {
17083   EXPECT_EQ("// aaaaÄ\xc2\x8d",
17084             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
17085   EXPECT_EQ("// Я из лесу\n"
17086             "// вышел; был\n"
17087             "// сильный\n"
17088             "// мороз.",
17089             format("// Я из лесу вышел; был сильный мороз.",
17090                    getLLVMStyleWithColumns(13)));
17091   EXPECT_EQ("// 一二三\n"
17092             "// 四五六七\n"
17093             "// 八  九\n"
17094             "// 十",
17095             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
17096 }
17097 
17098 TEST_F(FormatTest, SplitsUTF8BlockComments) {
17099   EXPECT_EQ("/* Гляжу,\n"
17100             " * поднимается\n"
17101             " * медленно в\n"
17102             " * гору\n"
17103             " * Лошадка,\n"
17104             " * везущая\n"
17105             " * хворосту\n"
17106             " * воз. */",
17107             format("/* Гляжу, поднимается медленно в гору\n"
17108                    " * Лошадка, везущая хворосту воз. */",
17109                    getLLVMStyleWithColumns(13)));
17110   EXPECT_EQ(
17111       "/* 一二三\n"
17112       " * 四五六七\n"
17113       " * 八  九\n"
17114       " * 十  */",
17115       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
17116   EXPECT_EQ("/* �������� ��������\n"
17117             " * ��������\n"
17118             " * ������-�� */",
17119             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
17120 }
17121 
17122 #endif // _MSC_VER
17123 
17124 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
17125   FormatStyle Style = getLLVMStyle();
17126 
17127   Style.ConstructorInitializerIndentWidth = 4;
17128   verifyFormat(
17129       "SomeClass::Constructor()\n"
17130       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
17131       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
17132       Style);
17133 
17134   Style.ConstructorInitializerIndentWidth = 2;
17135   verifyFormat(
17136       "SomeClass::Constructor()\n"
17137       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
17138       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
17139       Style);
17140 
17141   Style.ConstructorInitializerIndentWidth = 0;
17142   verifyFormat(
17143       "SomeClass::Constructor()\n"
17144       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
17145       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
17146       Style);
17147   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
17148   verifyFormat(
17149       "SomeLongTemplateVariableName<\n"
17150       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
17151       Style);
17152   verifyFormat("bool smaller = 1 < "
17153                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
17154                "                       "
17155                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
17156                Style);
17157 
17158   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
17159   verifyFormat("SomeClass::Constructor() :\n"
17160                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
17161                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
17162                Style);
17163 }
17164 
17165 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
17166   FormatStyle Style = getLLVMStyle();
17167   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
17168   Style.ConstructorInitializerIndentWidth = 4;
17169   verifyFormat("SomeClass::Constructor()\n"
17170                "    : a(a)\n"
17171                "    , b(b)\n"
17172                "    , c(c) {}",
17173                Style);
17174   verifyFormat("SomeClass::Constructor()\n"
17175                "    : a(a) {}",
17176                Style);
17177 
17178   Style.ColumnLimit = 0;
17179   verifyFormat("SomeClass::Constructor()\n"
17180                "    : a(a) {}",
17181                Style);
17182   verifyFormat("SomeClass::Constructor() noexcept\n"
17183                "    : a(a) {}",
17184                Style);
17185   verifyFormat("SomeClass::Constructor()\n"
17186                "    : a(a)\n"
17187                "    , b(b)\n"
17188                "    , c(c) {}",
17189                Style);
17190   verifyFormat("SomeClass::Constructor()\n"
17191                "    : a(a) {\n"
17192                "  foo();\n"
17193                "  bar();\n"
17194                "}",
17195                Style);
17196 
17197   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
17198   verifyFormat("SomeClass::Constructor()\n"
17199                "    : a(a)\n"
17200                "    , b(b)\n"
17201                "    , c(c) {\n}",
17202                Style);
17203   verifyFormat("SomeClass::Constructor()\n"
17204                "    : a(a) {\n}",
17205                Style);
17206 
17207   Style.ColumnLimit = 80;
17208   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
17209   Style.ConstructorInitializerIndentWidth = 2;
17210   verifyFormat("SomeClass::Constructor()\n"
17211                "  : a(a)\n"
17212                "  , b(b)\n"
17213                "  , c(c) {}",
17214                Style);
17215 
17216   Style.ConstructorInitializerIndentWidth = 0;
17217   verifyFormat("SomeClass::Constructor()\n"
17218                ": a(a)\n"
17219                ", b(b)\n"
17220                ", c(c) {}",
17221                Style);
17222 
17223   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
17224   Style.ConstructorInitializerIndentWidth = 4;
17225   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
17226   verifyFormat(
17227       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
17228       Style);
17229   verifyFormat(
17230       "SomeClass::Constructor()\n"
17231       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
17232       Style);
17233   Style.ConstructorInitializerIndentWidth = 4;
17234   Style.ColumnLimit = 60;
17235   verifyFormat("SomeClass::Constructor()\n"
17236                "    : aaaaaaaa(aaaaaaaa)\n"
17237                "    , aaaaaaaa(aaaaaaaa)\n"
17238                "    , aaaaaaaa(aaaaaaaa) {}",
17239                Style);
17240 }
17241 
17242 TEST_F(FormatTest, Destructors) {
17243   verifyFormat("void F(int &i) { i.~int(); }");
17244   verifyFormat("void F(int &i) { i->~int(); }");
17245 }
17246 
17247 TEST_F(FormatTest, FormatsWithWebKitStyle) {
17248   FormatStyle Style = getWebKitStyle();
17249 
17250   // Don't indent in outer namespaces.
17251   verifyFormat("namespace outer {\n"
17252                "int i;\n"
17253                "namespace inner {\n"
17254                "    int i;\n"
17255                "} // namespace inner\n"
17256                "} // namespace outer\n"
17257                "namespace other_outer {\n"
17258                "int i;\n"
17259                "}",
17260                Style);
17261 
17262   // Don't indent case labels.
17263   verifyFormat("switch (variable) {\n"
17264                "case 1:\n"
17265                "case 2:\n"
17266                "    doSomething();\n"
17267                "    break;\n"
17268                "default:\n"
17269                "    ++variable;\n"
17270                "}",
17271                Style);
17272 
17273   // Wrap before binary operators.
17274   EXPECT_EQ("void f()\n"
17275             "{\n"
17276             "    if (aaaaaaaaaaaaaaaa\n"
17277             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
17278             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
17279             "        return;\n"
17280             "}",
17281             format("void f() {\n"
17282                    "if (aaaaaaaaaaaaaaaa\n"
17283                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
17284                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
17285                    "return;\n"
17286                    "}",
17287                    Style));
17288 
17289   // Allow functions on a single line.
17290   verifyFormat("void f() { return; }", Style);
17291 
17292   // Allow empty blocks on a single line and insert a space in empty blocks.
17293   EXPECT_EQ("void f() { }", format("void f() {}", Style));
17294   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
17295   // However, don't merge non-empty short loops.
17296   EXPECT_EQ("while (true) {\n"
17297             "    continue;\n"
17298             "}",
17299             format("while (true) { continue; }", Style));
17300 
17301   // Constructor initializers are formatted one per line with the "," on the
17302   // new line.
17303   verifyFormat("Constructor()\n"
17304                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
17305                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
17306                "          aaaaaaaaaaaaaa)\n"
17307                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
17308                "{\n"
17309                "}",
17310                Style);
17311   verifyFormat("SomeClass::Constructor()\n"
17312                "    : a(a)\n"
17313                "{\n"
17314                "}",
17315                Style);
17316   EXPECT_EQ("SomeClass::Constructor()\n"
17317             "    : a(a)\n"
17318             "{\n"
17319             "}",
17320             format("SomeClass::Constructor():a(a){}", Style));
17321   verifyFormat("SomeClass::Constructor()\n"
17322                "    : a(a)\n"
17323                "    , b(b)\n"
17324                "    , c(c)\n"
17325                "{\n"
17326                "}",
17327                Style);
17328   verifyFormat("SomeClass::Constructor()\n"
17329                "    : a(a)\n"
17330                "{\n"
17331                "    foo();\n"
17332                "    bar();\n"
17333                "}",
17334                Style);
17335 
17336   // Access specifiers should be aligned left.
17337   verifyFormat("class C {\n"
17338                "public:\n"
17339                "    int i;\n"
17340                "};",
17341                Style);
17342 
17343   // Do not align comments.
17344   verifyFormat("int a; // Do not\n"
17345                "double b; // align comments.",
17346                Style);
17347 
17348   // Do not align operands.
17349   EXPECT_EQ("ASSERT(aaaa\n"
17350             "    || bbbb);",
17351             format("ASSERT ( aaaa\n||bbbb);", Style));
17352 
17353   // Accept input's line breaks.
17354   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
17355             "    || bbbbbbbbbbbbbbb) {\n"
17356             "    i++;\n"
17357             "}",
17358             format("if (aaaaaaaaaaaaaaa\n"
17359                    "|| bbbbbbbbbbbbbbb) { i++; }",
17360                    Style));
17361   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
17362             "    i++;\n"
17363             "}",
17364             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
17365 
17366   // Don't automatically break all macro definitions (llvm.org/PR17842).
17367   verifyFormat("#define aNumber 10", Style);
17368   // However, generally keep the line breaks that the user authored.
17369   EXPECT_EQ("#define aNumber \\\n"
17370             "    10",
17371             format("#define aNumber \\\n"
17372                    " 10",
17373                    Style));
17374 
17375   // Keep empty and one-element array literals on a single line.
17376   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
17377             "                                  copyItems:YES];",
17378             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
17379                    "copyItems:YES];",
17380                    Style));
17381   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
17382             "                                  copyItems:YES];",
17383             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
17384                    "             copyItems:YES];",
17385                    Style));
17386   // FIXME: This does not seem right, there should be more indentation before
17387   // the array literal's entries. Nested blocks have the same problem.
17388   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
17389             "    @\"a\",\n"
17390             "    @\"a\"\n"
17391             "]\n"
17392             "                                  copyItems:YES];",
17393             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
17394                    "     @\"a\",\n"
17395                    "     @\"a\"\n"
17396                    "     ]\n"
17397                    "       copyItems:YES];",
17398                    Style));
17399   EXPECT_EQ(
17400       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
17401       "                                  copyItems:YES];",
17402       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
17403              "   copyItems:YES];",
17404              Style));
17405 
17406   verifyFormat("[self.a b:c c:d];", Style);
17407   EXPECT_EQ("[self.a b:c\n"
17408             "        c:d];",
17409             format("[self.a b:c\n"
17410                    "c:d];",
17411                    Style));
17412 }
17413 
17414 TEST_F(FormatTest, FormatsLambdas) {
17415   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
17416   verifyFormat(
17417       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
17418   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
17419   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
17420   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
17421   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
17422   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
17423   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
17424   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
17425   verifyFormat("int x = f(*+[] {});");
17426   verifyFormat("void f() {\n"
17427                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
17428                "}\n");
17429   verifyFormat("void f() {\n"
17430                "  other(x.begin(), //\n"
17431                "        x.end(),   //\n"
17432                "        [&](int, int) { return 1; });\n"
17433                "}\n");
17434   verifyFormat("void f() {\n"
17435                "  other.other.other.other.other(\n"
17436                "      x.begin(), x.end(),\n"
17437                "      [something, rather](int, int, int, int, int, int, int) { "
17438                "return 1; });\n"
17439                "}\n");
17440   verifyFormat(
17441       "void f() {\n"
17442       "  other.other.other.other.other(\n"
17443       "      x.begin(), x.end(),\n"
17444       "      [something, rather](int, int, int, int, int, int, int) {\n"
17445       "        //\n"
17446       "      });\n"
17447       "}\n");
17448   verifyFormat("SomeFunction([]() { // A cool function...\n"
17449                "  return 43;\n"
17450                "});");
17451   EXPECT_EQ("SomeFunction([]() {\n"
17452             "#define A a\n"
17453             "  return 43;\n"
17454             "});",
17455             format("SomeFunction([](){\n"
17456                    "#define A a\n"
17457                    "return 43;\n"
17458                    "});"));
17459   verifyFormat("void f() {\n"
17460                "  SomeFunction([](decltype(x), A *a) {});\n"
17461                "  SomeFunction([](typeof(x), A *a) {});\n"
17462                "  SomeFunction([](_Atomic(x), A *a) {});\n"
17463                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
17464                "}");
17465   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
17466                "    [](const aaaaaaaaaa &a) { return a; });");
17467   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
17468                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
17469                "});");
17470   verifyFormat("Constructor()\n"
17471                "    : Field([] { // comment\n"
17472                "        int i;\n"
17473                "      }) {}");
17474   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
17475                "  return some_parameter.size();\n"
17476                "};");
17477   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
17478                "    [](const string &s) { return s; };");
17479   verifyFormat("int i = aaaaaa ? 1 //\n"
17480                "               : [] {\n"
17481                "                   return 2; //\n"
17482                "                 }();");
17483   verifyFormat("llvm::errs() << \"number of twos is \"\n"
17484                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
17485                "                  return x == 2; // force break\n"
17486                "                });");
17487   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
17488                "    [=](int iiiiiiiiiiii) {\n"
17489                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
17490                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
17491                "    });",
17492                getLLVMStyleWithColumns(60));
17493   verifyFormat("SomeFunction({[&] {\n"
17494                "                // comment\n"
17495                "              },\n"
17496                "              [&] {\n"
17497                "                // comment\n"
17498                "              }});");
17499   verifyFormat("SomeFunction({[&] {\n"
17500                "  // comment\n"
17501                "}});");
17502   verifyFormat(
17503       "virtual aaaaaaaaaaaaaaaa(\n"
17504       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
17505       "    aaaaa aaaaaaaaa);");
17506 
17507   // Lambdas with return types.
17508   verifyFormat("int c = []() -> int { return 2; }();\n");
17509   verifyFormat("int c = []() -> int * { return 2; }();\n");
17510   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
17511   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
17512   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
17513   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
17514   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
17515   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
17516   verifyFormat("[a, a]() -> a<1> {};");
17517   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
17518   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
17519   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
17520   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
17521   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
17522   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
17523   verifyFormat("[]() -> foo<!5> { return {}; };");
17524   verifyFormat("[]() -> foo<~5> { return {}; };");
17525   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
17526   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
17527   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
17528   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
17529   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
17530   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
17531   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
17532   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
17533   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
17534   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
17535   verifyFormat("namespace bar {\n"
17536                "// broken:\n"
17537                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
17538                "} // namespace bar");
17539   verifyFormat("namespace bar {\n"
17540                "// broken:\n"
17541                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
17542                "} // namespace bar");
17543   verifyFormat("namespace bar {\n"
17544                "// broken:\n"
17545                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
17546                "} // namespace bar");
17547   verifyFormat("namespace bar {\n"
17548                "// broken:\n"
17549                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
17550                "} // namespace bar");
17551   verifyFormat("namespace bar {\n"
17552                "// broken:\n"
17553                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
17554                "} // namespace bar");
17555   verifyFormat("namespace bar {\n"
17556                "// broken:\n"
17557                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
17558                "} // namespace bar");
17559   verifyFormat("namespace bar {\n"
17560                "// broken:\n"
17561                "auto foo{[]() -> foo<!5> { return {}; }};\n"
17562                "} // namespace bar");
17563   verifyFormat("namespace bar {\n"
17564                "// broken:\n"
17565                "auto foo{[]() -> foo<~5> { return {}; }};\n"
17566                "} // namespace bar");
17567   verifyFormat("namespace bar {\n"
17568                "// broken:\n"
17569                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
17570                "} // namespace bar");
17571   verifyFormat("namespace bar {\n"
17572                "// broken:\n"
17573                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
17574                "} // namespace bar");
17575   verifyFormat("namespace bar {\n"
17576                "// broken:\n"
17577                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
17578                "} // namespace bar");
17579   verifyFormat("namespace bar {\n"
17580                "// broken:\n"
17581                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
17582                "} // namespace bar");
17583   verifyFormat("namespace bar {\n"
17584                "// broken:\n"
17585                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
17586                "} // namespace bar");
17587   verifyFormat("namespace bar {\n"
17588                "// broken:\n"
17589                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
17590                "} // namespace bar");
17591   verifyFormat("namespace bar {\n"
17592                "// broken:\n"
17593                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
17594                "} // namespace bar");
17595   verifyFormat("namespace bar {\n"
17596                "// broken:\n"
17597                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
17598                "} // namespace bar");
17599   verifyFormat("namespace bar {\n"
17600                "// broken:\n"
17601                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
17602                "} // namespace bar");
17603   verifyFormat("namespace bar {\n"
17604                "// broken:\n"
17605                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
17606                "} // namespace bar");
17607   verifyFormat("[]() -> a<1> {};");
17608   verifyFormat("[]() -> a<1> { ; };");
17609   verifyFormat("[]() -> a<1> { ; }();");
17610   verifyFormat("[a, a]() -> a<true> {};");
17611   verifyFormat("[]() -> a<true> {};");
17612   verifyFormat("[]() -> a<true> { ; };");
17613   verifyFormat("[]() -> a<true> { ; }();");
17614   verifyFormat("[a, a]() -> a<false> {};");
17615   verifyFormat("[]() -> a<false> {};");
17616   verifyFormat("[]() -> a<false> { ; };");
17617   verifyFormat("[]() -> a<false> { ; }();");
17618   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
17619   verifyFormat("namespace bar {\n"
17620                "auto foo{[]() -> foo<false> { ; }};\n"
17621                "} // namespace bar");
17622   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
17623                "                   int j) -> int {\n"
17624                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
17625                "};");
17626   verifyFormat(
17627       "aaaaaaaaaaaaaaaaaaaaaa(\n"
17628       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
17629       "      return aaaaaaaaaaaaaaaaa;\n"
17630       "    });",
17631       getLLVMStyleWithColumns(70));
17632   verifyFormat("[]() //\n"
17633                "    -> int {\n"
17634                "  return 1; //\n"
17635                "};");
17636   verifyFormat("[]() -> Void<T...> {};");
17637   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
17638 
17639   // Lambdas with explicit template argument lists.
17640   verifyFormat(
17641       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
17642 
17643   // Multiple lambdas in the same parentheses change indentation rules. These
17644   // lambdas are forced to start on new lines.
17645   verifyFormat("SomeFunction(\n"
17646                "    []() {\n"
17647                "      //\n"
17648                "    },\n"
17649                "    []() {\n"
17650                "      //\n"
17651                "    });");
17652 
17653   // A lambda passed as arg0 is always pushed to the next line.
17654   verifyFormat("SomeFunction(\n"
17655                "    [this] {\n"
17656                "      //\n"
17657                "    },\n"
17658                "    1);\n");
17659 
17660   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
17661   // the arg0 case above.
17662   auto Style = getGoogleStyle();
17663   Style.BinPackArguments = false;
17664   verifyFormat("SomeFunction(\n"
17665                "    a,\n"
17666                "    [this] {\n"
17667                "      //\n"
17668                "    },\n"
17669                "    b);\n",
17670                Style);
17671   verifyFormat("SomeFunction(\n"
17672                "    a,\n"
17673                "    [this] {\n"
17674                "      //\n"
17675                "    },\n"
17676                "    b);\n");
17677 
17678   // A lambda with a very long line forces arg0 to be pushed out irrespective of
17679   // the BinPackArguments value (as long as the code is wide enough).
17680   verifyFormat(
17681       "something->SomeFunction(\n"
17682       "    a,\n"
17683       "    [this] {\n"
17684       "      "
17685       "D0000000000000000000000000000000000000000000000000000000000001();\n"
17686       "    },\n"
17687       "    b);\n");
17688 
17689   // A multi-line lambda is pulled up as long as the introducer fits on the
17690   // previous line and there are no further args.
17691   verifyFormat("function(1, [this, that] {\n"
17692                "  //\n"
17693                "});\n");
17694   verifyFormat("function([this, that] {\n"
17695                "  //\n"
17696                "});\n");
17697   // FIXME: this format is not ideal and we should consider forcing the first
17698   // arg onto its own line.
17699   verifyFormat("function(a, b, c, //\n"
17700                "         d, [this, that] {\n"
17701                "           //\n"
17702                "         });\n");
17703 
17704   // Multiple lambdas are treated correctly even when there is a short arg0.
17705   verifyFormat("SomeFunction(\n"
17706                "    1,\n"
17707                "    [this] {\n"
17708                "      //\n"
17709                "    },\n"
17710                "    [this] {\n"
17711                "      //\n"
17712                "    },\n"
17713                "    1);\n");
17714 
17715   // More complex introducers.
17716   verifyFormat("return [i, args...] {};");
17717 
17718   // Not lambdas.
17719   verifyFormat("constexpr char hello[]{\"hello\"};");
17720   verifyFormat("double &operator[](int i) { return 0; }\n"
17721                "int i;");
17722   verifyFormat("std::unique_ptr<int[]> foo() {}");
17723   verifyFormat("int i = a[a][a]->f();");
17724   verifyFormat("int i = (*b)[a]->f();");
17725 
17726   // Other corner cases.
17727   verifyFormat("void f() {\n"
17728                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
17729                "  );\n"
17730                "}");
17731 
17732   // Lambdas created through weird macros.
17733   verifyFormat("void f() {\n"
17734                "  MACRO((const AA &a) { return 1; });\n"
17735                "  MACRO((AA &a) { return 1; });\n"
17736                "}");
17737 
17738   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
17739                "      doo_dah();\n"
17740                "      doo_dah();\n"
17741                "    })) {\n"
17742                "}");
17743   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
17744                "                doo_dah();\n"
17745                "                doo_dah();\n"
17746                "              })) {\n"
17747                "}");
17748   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
17749                "                doo_dah();\n"
17750                "                doo_dah();\n"
17751                "              })) {\n"
17752                "}");
17753   verifyFormat("auto lambda = []() {\n"
17754                "  int a = 2\n"
17755                "#if A\n"
17756                "          + 2\n"
17757                "#endif\n"
17758                "      ;\n"
17759                "};");
17760 
17761   // Lambdas with complex multiline introducers.
17762   verifyFormat(
17763       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
17764       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
17765       "        -> ::std::unordered_set<\n"
17766       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
17767       "      //\n"
17768       "    });");
17769 
17770   FormatStyle DoNotMerge = getLLVMStyle();
17771   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17772   verifyFormat("auto c = []() {\n"
17773                "  return b;\n"
17774                "};",
17775                "auto c = []() { return b; };", DoNotMerge);
17776   verifyFormat("auto c = []() {\n"
17777                "};",
17778                " auto c = []() {};", DoNotMerge);
17779 
17780   FormatStyle MergeEmptyOnly = getLLVMStyle();
17781   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
17782   verifyFormat("auto c = []() {\n"
17783                "  return b;\n"
17784                "};",
17785                "auto c = []() {\n"
17786                "  return b;\n"
17787                " };",
17788                MergeEmptyOnly);
17789   verifyFormat("auto c = []() {};",
17790                "auto c = []() {\n"
17791                "};",
17792                MergeEmptyOnly);
17793 
17794   FormatStyle MergeInline = getLLVMStyle();
17795   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
17796   verifyFormat("auto c = []() {\n"
17797                "  return b;\n"
17798                "};",
17799                "auto c = []() { return b; };", MergeInline);
17800   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
17801                MergeInline);
17802   verifyFormat("function([]() { return b; }, a)",
17803                "function([]() { return b; }, a)", MergeInline);
17804   verifyFormat("function(a, []() { return b; })",
17805                "function(a, []() { return b; })", MergeInline);
17806 
17807   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
17808   // AllowShortLambdasOnASingleLine
17809   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
17810   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
17811   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
17812   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17813       FormatStyle::ShortLambdaStyle::SLS_None;
17814   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
17815                "    []()\n"
17816                "    {\n"
17817                "      return 17;\n"
17818                "    });",
17819                LLVMWithBeforeLambdaBody);
17820   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
17821                "    []()\n"
17822                "    {\n"
17823                "    });",
17824                LLVMWithBeforeLambdaBody);
17825   verifyFormat("auto fct_SLS_None = []()\n"
17826                "{\n"
17827                "  return 17;\n"
17828                "};",
17829                LLVMWithBeforeLambdaBody);
17830   verifyFormat("TwoNestedLambdas_SLS_None(\n"
17831                "    []()\n"
17832                "    {\n"
17833                "      return Call(\n"
17834                "          []()\n"
17835                "          {\n"
17836                "            return 17;\n"
17837                "          });\n"
17838                "    });",
17839                LLVMWithBeforeLambdaBody);
17840   verifyFormat("void Fct()\n"
17841                "{\n"
17842                "  return {[]()\n"
17843                "          {\n"
17844                "            return 17;\n"
17845                "          }};\n"
17846                "}",
17847                LLVMWithBeforeLambdaBody);
17848 
17849   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17850       FormatStyle::ShortLambdaStyle::SLS_Empty;
17851   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
17852                "    []()\n"
17853                "    {\n"
17854                "      return 17;\n"
17855                "    });",
17856                LLVMWithBeforeLambdaBody);
17857   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
17858                LLVMWithBeforeLambdaBody);
17859   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
17860                "ongFunctionName_SLS_Empty(\n"
17861                "    []() {});",
17862                LLVMWithBeforeLambdaBody);
17863   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
17864                "                                []()\n"
17865                "                                {\n"
17866                "                                  return 17;\n"
17867                "                                });",
17868                LLVMWithBeforeLambdaBody);
17869   verifyFormat("auto fct_SLS_Empty = []()\n"
17870                "{\n"
17871                "  return 17;\n"
17872                "};",
17873                LLVMWithBeforeLambdaBody);
17874   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
17875                "    []()\n"
17876                "    {\n"
17877                "      return Call([]() {});\n"
17878                "    });",
17879                LLVMWithBeforeLambdaBody);
17880   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
17881                "                           []()\n"
17882                "                           {\n"
17883                "                             return Call([]() {});\n"
17884                "                           });",
17885                LLVMWithBeforeLambdaBody);
17886   verifyFormat(
17887       "FctWithLongLineInLambda_SLS_Empty(\n"
17888       "    []()\n"
17889       "    {\n"
17890       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17891       "                               AndShouldNotBeConsiderAsInline,\n"
17892       "                               LambdaBodyMustBeBreak);\n"
17893       "    });",
17894       LLVMWithBeforeLambdaBody);
17895 
17896   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17897       FormatStyle::ShortLambdaStyle::SLS_Inline;
17898   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
17899                LLVMWithBeforeLambdaBody);
17900   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
17901                LLVMWithBeforeLambdaBody);
17902   verifyFormat("auto fct_SLS_Inline = []()\n"
17903                "{\n"
17904                "  return 17;\n"
17905                "};",
17906                LLVMWithBeforeLambdaBody);
17907   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
17908                "17; }); });",
17909                LLVMWithBeforeLambdaBody);
17910   verifyFormat(
17911       "FctWithLongLineInLambda_SLS_Inline(\n"
17912       "    []()\n"
17913       "    {\n"
17914       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17915       "                               AndShouldNotBeConsiderAsInline,\n"
17916       "                               LambdaBodyMustBeBreak);\n"
17917       "    });",
17918       LLVMWithBeforeLambdaBody);
17919   verifyFormat("FctWithMultipleParams_SLS_Inline("
17920                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
17921                "                                 []() { return 17; });",
17922                LLVMWithBeforeLambdaBody);
17923   verifyFormat(
17924       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
17925       LLVMWithBeforeLambdaBody);
17926 
17927   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17928       FormatStyle::ShortLambdaStyle::SLS_All;
17929   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
17930                LLVMWithBeforeLambdaBody);
17931   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
17932                LLVMWithBeforeLambdaBody);
17933   verifyFormat("auto fct_SLS_All = []() { return 17; };",
17934                LLVMWithBeforeLambdaBody);
17935   verifyFormat("FctWithOneParam_SLS_All(\n"
17936                "    []()\n"
17937                "    {\n"
17938                "      // A cool function...\n"
17939                "      return 43;\n"
17940                "    });",
17941                LLVMWithBeforeLambdaBody);
17942   verifyFormat("FctWithMultipleParams_SLS_All("
17943                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
17944                "                              []() { return 17; });",
17945                LLVMWithBeforeLambdaBody);
17946   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
17947                LLVMWithBeforeLambdaBody);
17948   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
17949                LLVMWithBeforeLambdaBody);
17950   verifyFormat(
17951       "FctWithLongLineInLambda_SLS_All(\n"
17952       "    []()\n"
17953       "    {\n"
17954       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17955       "                               AndShouldNotBeConsiderAsInline,\n"
17956       "                               LambdaBodyMustBeBreak);\n"
17957       "    });",
17958       LLVMWithBeforeLambdaBody);
17959   verifyFormat(
17960       "auto fct_SLS_All = []()\n"
17961       "{\n"
17962       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17963       "                           AndShouldNotBeConsiderAsInline,\n"
17964       "                           LambdaBodyMustBeBreak);\n"
17965       "};",
17966       LLVMWithBeforeLambdaBody);
17967   LLVMWithBeforeLambdaBody.BinPackParameters = false;
17968   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
17969                LLVMWithBeforeLambdaBody);
17970   verifyFormat(
17971       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
17972       "                                FirstParam,\n"
17973       "                                SecondParam,\n"
17974       "                                ThirdParam,\n"
17975       "                                FourthParam);",
17976       LLVMWithBeforeLambdaBody);
17977   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
17978                "    []() { return "
17979                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
17980                "    FirstParam,\n"
17981                "    SecondParam,\n"
17982                "    ThirdParam,\n"
17983                "    FourthParam);",
17984                LLVMWithBeforeLambdaBody);
17985   verifyFormat(
17986       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
17987       "                                SecondParam,\n"
17988       "                                ThirdParam,\n"
17989       "                                FourthParam,\n"
17990       "                                []() { return SomeValueNotSoLong; });",
17991       LLVMWithBeforeLambdaBody);
17992   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
17993                "    []()\n"
17994                "    {\n"
17995                "      return "
17996                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
17997                "eConsiderAsInline;\n"
17998                "    });",
17999                LLVMWithBeforeLambdaBody);
18000   verifyFormat(
18001       "FctWithLongLineInLambda_SLS_All(\n"
18002       "    []()\n"
18003       "    {\n"
18004       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
18005       "                               AndShouldNotBeConsiderAsInline,\n"
18006       "                               LambdaBodyMustBeBreak);\n"
18007       "    });",
18008       LLVMWithBeforeLambdaBody);
18009   verifyFormat("FctWithTwoParams_SLS_All(\n"
18010                "    []()\n"
18011                "    {\n"
18012                "      // A cool function...\n"
18013                "      return 43;\n"
18014                "    },\n"
18015                "    87);",
18016                LLVMWithBeforeLambdaBody);
18017   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
18018                LLVMWithBeforeLambdaBody);
18019   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
18020                LLVMWithBeforeLambdaBody);
18021   verifyFormat(
18022       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
18023       LLVMWithBeforeLambdaBody);
18024   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
18025                "}); }, x);",
18026                LLVMWithBeforeLambdaBody);
18027   verifyFormat("TwoNestedLambdas_SLS_All(\n"
18028                "    []()\n"
18029                "    {\n"
18030                "      // A cool function...\n"
18031                "      return Call([]() { return 17; });\n"
18032                "    });",
18033                LLVMWithBeforeLambdaBody);
18034   verifyFormat("TwoNestedLambdas_SLS_All(\n"
18035                "    []()\n"
18036                "    {\n"
18037                "      return Call(\n"
18038                "          []()\n"
18039                "          {\n"
18040                "            // A cool function...\n"
18041                "            return 17;\n"
18042                "          });\n"
18043                "    });",
18044                LLVMWithBeforeLambdaBody);
18045 }
18046 
18047 TEST_F(FormatTest, LambdaWithLineComments) {
18048   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
18049   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
18050   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
18051   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
18052       FormatStyle::ShortLambdaStyle::SLS_All;
18053 
18054   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
18055   verifyFormat("auto k = []() // comment\n"
18056                "{ return; }",
18057                LLVMWithBeforeLambdaBody);
18058   verifyFormat("auto k = []() /* comment */ { return; }",
18059                LLVMWithBeforeLambdaBody);
18060   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
18061                LLVMWithBeforeLambdaBody);
18062   verifyFormat("auto k = []() // X\n"
18063                "{ return; }",
18064                LLVMWithBeforeLambdaBody);
18065   verifyFormat(
18066       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
18067       "{ return; }",
18068       LLVMWithBeforeLambdaBody);
18069 }
18070 
18071 TEST_F(FormatTest, EmptyLinesInLambdas) {
18072   verifyFormat("auto lambda = []() {\n"
18073                "  x(); //\n"
18074                "};",
18075                "auto lambda = []() {\n"
18076                "\n"
18077                "  x(); //\n"
18078                "\n"
18079                "};");
18080 }
18081 
18082 TEST_F(FormatTest, FormatsBlocks) {
18083   FormatStyle ShortBlocks = getLLVMStyle();
18084   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
18085   verifyFormat("int (^Block)(int, int);", ShortBlocks);
18086   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
18087   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
18088   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
18089   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
18090   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
18091 
18092   verifyFormat("foo(^{ bar(); });", ShortBlocks);
18093   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
18094   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
18095 
18096   verifyFormat("[operation setCompletionBlock:^{\n"
18097                "  [self onOperationDone];\n"
18098                "}];");
18099   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
18100                "  [self onOperationDone];\n"
18101                "}]};");
18102   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
18103                "  f();\n"
18104                "}];");
18105   verifyFormat("int a = [operation block:^int(int *i) {\n"
18106                "  return 1;\n"
18107                "}];");
18108   verifyFormat("[myObject doSomethingWith:arg1\n"
18109                "                      aaa:^int(int *a) {\n"
18110                "                        return 1;\n"
18111                "                      }\n"
18112                "                      bbb:f(a * bbbbbbbb)];");
18113 
18114   verifyFormat("[operation setCompletionBlock:^{\n"
18115                "  [self.delegate newDataAvailable];\n"
18116                "}];",
18117                getLLVMStyleWithColumns(60));
18118   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
18119                "  NSString *path = [self sessionFilePath];\n"
18120                "  if (path) {\n"
18121                "    // ...\n"
18122                "  }\n"
18123                "});");
18124   verifyFormat("[[SessionService sharedService]\n"
18125                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
18126                "      if (window) {\n"
18127                "        [self windowDidLoad:window];\n"
18128                "      } else {\n"
18129                "        [self errorLoadingWindow];\n"
18130                "      }\n"
18131                "    }];");
18132   verifyFormat("void (^largeBlock)(void) = ^{\n"
18133                "  // ...\n"
18134                "};\n",
18135                getLLVMStyleWithColumns(40));
18136   verifyFormat("[[SessionService sharedService]\n"
18137                "    loadWindowWithCompletionBlock: //\n"
18138                "        ^(SessionWindow *window) {\n"
18139                "          if (window) {\n"
18140                "            [self windowDidLoad:window];\n"
18141                "          } else {\n"
18142                "            [self errorLoadingWindow];\n"
18143                "          }\n"
18144                "        }];",
18145                getLLVMStyleWithColumns(60));
18146   verifyFormat("[myObject doSomethingWith:arg1\n"
18147                "    firstBlock:^(Foo *a) {\n"
18148                "      // ...\n"
18149                "      int i;\n"
18150                "    }\n"
18151                "    secondBlock:^(Bar *b) {\n"
18152                "      // ...\n"
18153                "      int i;\n"
18154                "    }\n"
18155                "    thirdBlock:^Foo(Bar *b) {\n"
18156                "      // ...\n"
18157                "      int i;\n"
18158                "    }];");
18159   verifyFormat("[myObject doSomethingWith:arg1\n"
18160                "               firstBlock:-1\n"
18161                "              secondBlock:^(Bar *b) {\n"
18162                "                // ...\n"
18163                "                int i;\n"
18164                "              }];");
18165 
18166   verifyFormat("f(^{\n"
18167                "  @autoreleasepool {\n"
18168                "    if (a) {\n"
18169                "      g();\n"
18170                "    }\n"
18171                "  }\n"
18172                "});");
18173   verifyFormat("Block b = ^int *(A *a, B *b) {}");
18174   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
18175                "};");
18176 
18177   FormatStyle FourIndent = getLLVMStyle();
18178   FourIndent.ObjCBlockIndentWidth = 4;
18179   verifyFormat("[operation setCompletionBlock:^{\n"
18180                "    [self onOperationDone];\n"
18181                "}];",
18182                FourIndent);
18183 }
18184 
18185 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
18186   FormatStyle ZeroColumn = getLLVMStyle();
18187   ZeroColumn.ColumnLimit = 0;
18188 
18189   verifyFormat("[[SessionService sharedService] "
18190                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
18191                "  if (window) {\n"
18192                "    [self windowDidLoad:window];\n"
18193                "  } else {\n"
18194                "    [self errorLoadingWindow];\n"
18195                "  }\n"
18196                "}];",
18197                ZeroColumn);
18198   EXPECT_EQ("[[SessionService sharedService]\n"
18199             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
18200             "      if (window) {\n"
18201             "        [self windowDidLoad:window];\n"
18202             "      } else {\n"
18203             "        [self errorLoadingWindow];\n"
18204             "      }\n"
18205             "    }];",
18206             format("[[SessionService sharedService]\n"
18207                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
18208                    "                if (window) {\n"
18209                    "    [self windowDidLoad:window];\n"
18210                    "  } else {\n"
18211                    "    [self errorLoadingWindow];\n"
18212                    "  }\n"
18213                    "}];",
18214                    ZeroColumn));
18215   verifyFormat("[myObject doSomethingWith:arg1\n"
18216                "    firstBlock:^(Foo *a) {\n"
18217                "      // ...\n"
18218                "      int i;\n"
18219                "    }\n"
18220                "    secondBlock:^(Bar *b) {\n"
18221                "      // ...\n"
18222                "      int i;\n"
18223                "    }\n"
18224                "    thirdBlock:^Foo(Bar *b) {\n"
18225                "      // ...\n"
18226                "      int i;\n"
18227                "    }];",
18228                ZeroColumn);
18229   verifyFormat("f(^{\n"
18230                "  @autoreleasepool {\n"
18231                "    if (a) {\n"
18232                "      g();\n"
18233                "    }\n"
18234                "  }\n"
18235                "});",
18236                ZeroColumn);
18237   verifyFormat("void (^largeBlock)(void) = ^{\n"
18238                "  // ...\n"
18239                "};",
18240                ZeroColumn);
18241 
18242   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
18243   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
18244             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
18245   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
18246   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
18247             "  int i;\n"
18248             "};",
18249             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
18250 }
18251 
18252 TEST_F(FormatTest, SupportsCRLF) {
18253   EXPECT_EQ("int a;\r\n"
18254             "int b;\r\n"
18255             "int c;\r\n",
18256             format("int a;\r\n"
18257                    "  int b;\r\n"
18258                    "    int c;\r\n",
18259                    getLLVMStyle()));
18260   EXPECT_EQ("int a;\r\n"
18261             "int b;\r\n"
18262             "int c;\r\n",
18263             format("int a;\r\n"
18264                    "  int b;\n"
18265                    "    int c;\r\n",
18266                    getLLVMStyle()));
18267   EXPECT_EQ("int a;\n"
18268             "int b;\n"
18269             "int c;\n",
18270             format("int a;\r\n"
18271                    "  int b;\n"
18272                    "    int c;\n",
18273                    getLLVMStyle()));
18274   EXPECT_EQ("\"aaaaaaa \"\r\n"
18275             "\"bbbbbbb\";\r\n",
18276             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
18277   EXPECT_EQ("#define A \\\r\n"
18278             "  b;      \\\r\n"
18279             "  c;      \\\r\n"
18280             "  d;\r\n",
18281             format("#define A \\\r\n"
18282                    "  b; \\\r\n"
18283                    "  c; d; \r\n",
18284                    getGoogleStyle()));
18285 
18286   EXPECT_EQ("/*\r\n"
18287             "multi line block comments\r\n"
18288             "should not introduce\r\n"
18289             "an extra carriage return\r\n"
18290             "*/\r\n",
18291             format("/*\r\n"
18292                    "multi line block comments\r\n"
18293                    "should not introduce\r\n"
18294                    "an extra carriage return\r\n"
18295                    "*/\r\n"));
18296   EXPECT_EQ("/*\r\n"
18297             "\r\n"
18298             "*/",
18299             format("/*\r\n"
18300                    "    \r\r\r\n"
18301                    "*/"));
18302 
18303   FormatStyle style = getLLVMStyle();
18304 
18305   style.DeriveLineEnding = true;
18306   style.UseCRLF = false;
18307   EXPECT_EQ("union FooBarBazQux {\n"
18308             "  int foo;\n"
18309             "  int bar;\n"
18310             "  int baz;\n"
18311             "};",
18312             format("union FooBarBazQux {\r\n"
18313                    "  int foo;\n"
18314                    "  int bar;\r\n"
18315                    "  int baz;\n"
18316                    "};",
18317                    style));
18318   style.UseCRLF = true;
18319   EXPECT_EQ("union FooBarBazQux {\r\n"
18320             "  int foo;\r\n"
18321             "  int bar;\r\n"
18322             "  int baz;\r\n"
18323             "};",
18324             format("union FooBarBazQux {\r\n"
18325                    "  int foo;\n"
18326                    "  int bar;\r\n"
18327                    "  int baz;\n"
18328                    "};",
18329                    style));
18330 
18331   style.DeriveLineEnding = false;
18332   style.UseCRLF = false;
18333   EXPECT_EQ("union FooBarBazQux {\n"
18334             "  int foo;\n"
18335             "  int bar;\n"
18336             "  int baz;\n"
18337             "  int qux;\n"
18338             "};",
18339             format("union FooBarBazQux {\r\n"
18340                    "  int foo;\n"
18341                    "  int bar;\r\n"
18342                    "  int baz;\n"
18343                    "  int qux;\r\n"
18344                    "};",
18345                    style));
18346   style.UseCRLF = true;
18347   EXPECT_EQ("union FooBarBazQux {\r\n"
18348             "  int foo;\r\n"
18349             "  int bar;\r\n"
18350             "  int baz;\r\n"
18351             "  int qux;\r\n"
18352             "};",
18353             format("union FooBarBazQux {\r\n"
18354                    "  int foo;\n"
18355                    "  int bar;\r\n"
18356                    "  int baz;\n"
18357                    "  int qux;\n"
18358                    "};",
18359                    style));
18360 
18361   style.DeriveLineEnding = true;
18362   style.UseCRLF = false;
18363   EXPECT_EQ("union FooBarBazQux {\r\n"
18364             "  int foo;\r\n"
18365             "  int bar;\r\n"
18366             "  int baz;\r\n"
18367             "  int qux;\r\n"
18368             "};",
18369             format("union FooBarBazQux {\r\n"
18370                    "  int foo;\n"
18371                    "  int bar;\r\n"
18372                    "  int baz;\n"
18373                    "  int qux;\r\n"
18374                    "};",
18375                    style));
18376   style.UseCRLF = true;
18377   EXPECT_EQ("union FooBarBazQux {\n"
18378             "  int foo;\n"
18379             "  int bar;\n"
18380             "  int baz;\n"
18381             "  int qux;\n"
18382             "};",
18383             format("union FooBarBazQux {\r\n"
18384                    "  int foo;\n"
18385                    "  int bar;\r\n"
18386                    "  int baz;\n"
18387                    "  int qux;\n"
18388                    "};",
18389                    style));
18390 }
18391 
18392 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
18393   verifyFormat("MY_CLASS(C) {\n"
18394                "  int i;\n"
18395                "  int j;\n"
18396                "};");
18397 }
18398 
18399 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
18400   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
18401   TwoIndent.ContinuationIndentWidth = 2;
18402 
18403   EXPECT_EQ("int i =\n"
18404             "  longFunction(\n"
18405             "    arg);",
18406             format("int i = longFunction(arg);", TwoIndent));
18407 
18408   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
18409   SixIndent.ContinuationIndentWidth = 6;
18410 
18411   EXPECT_EQ("int i =\n"
18412             "      longFunction(\n"
18413             "            arg);",
18414             format("int i = longFunction(arg);", SixIndent));
18415 }
18416 
18417 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
18418   FormatStyle Style = getLLVMStyle();
18419   verifyFormat("int Foo::getter(\n"
18420                "    //\n"
18421                ") const {\n"
18422                "  return foo;\n"
18423                "}",
18424                Style);
18425   verifyFormat("void Foo::setter(\n"
18426                "    //\n"
18427                ") {\n"
18428                "  foo = 1;\n"
18429                "}",
18430                Style);
18431 }
18432 
18433 TEST_F(FormatTest, SpacesInAngles) {
18434   FormatStyle Spaces = getLLVMStyle();
18435   Spaces.SpacesInAngles = true;
18436 
18437   verifyFormat("static_cast< int >(arg);", Spaces);
18438   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
18439   verifyFormat("f< int, float >();", Spaces);
18440   verifyFormat("template <> g() {}", Spaces);
18441   verifyFormat("template < std::vector< int > > f() {}", Spaces);
18442   verifyFormat("std::function< void(int, int) > fct;", Spaces);
18443   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
18444                Spaces);
18445 
18446   Spaces.Standard = FormatStyle::LS_Cpp03;
18447   Spaces.SpacesInAngles = true;
18448   verifyFormat("A< A< int > >();", Spaces);
18449 
18450   Spaces.SpacesInAngles = false;
18451   verifyFormat("A<A<int> >();", Spaces);
18452 
18453   Spaces.Standard = FormatStyle::LS_Cpp11;
18454   Spaces.SpacesInAngles = true;
18455   verifyFormat("A< A< int > >();", Spaces);
18456 
18457   Spaces.SpacesInAngles = false;
18458   verifyFormat("A<A<int>>();", Spaces);
18459 }
18460 
18461 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
18462   FormatStyle Style = getLLVMStyle();
18463   Style.SpaceAfterTemplateKeyword = false;
18464   verifyFormat("template<int> void foo();", Style);
18465 }
18466 
18467 TEST_F(FormatTest, TripleAngleBrackets) {
18468   verifyFormat("f<<<1, 1>>>();");
18469   verifyFormat("f<<<1, 1, 1, s>>>();");
18470   verifyFormat("f<<<a, b, c, d>>>();");
18471   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
18472   verifyFormat("f<param><<<1, 1>>>();");
18473   verifyFormat("f<1><<<1, 1>>>();");
18474   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
18475   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
18476                "aaaaaaaaaaa<<<\n    1, 1>>>();");
18477   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
18478                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
18479 }
18480 
18481 TEST_F(FormatTest, MergeLessLessAtEnd) {
18482   verifyFormat("<<");
18483   EXPECT_EQ("< < <", format("\\\n<<<"));
18484   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
18485                "aaallvm::outs() <<");
18486   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
18487                "aaaallvm::outs()\n    <<");
18488 }
18489 
18490 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
18491   std::string code = "#if A\n"
18492                      "#if B\n"
18493                      "a.\n"
18494                      "#endif\n"
18495                      "    a = 1;\n"
18496                      "#else\n"
18497                      "#endif\n"
18498                      "#if C\n"
18499                      "#else\n"
18500                      "#endif\n";
18501   EXPECT_EQ(code, format(code));
18502 }
18503 
18504 TEST_F(FormatTest, HandleConflictMarkers) {
18505   // Git/SVN conflict markers.
18506   EXPECT_EQ("int a;\n"
18507             "void f() {\n"
18508             "  callme(some(parameter1,\n"
18509             "<<<<<<< text by the vcs\n"
18510             "              parameter2),\n"
18511             "||||||| text by the vcs\n"
18512             "              parameter2),\n"
18513             "         parameter3,\n"
18514             "======= text by the vcs\n"
18515             "              parameter2, parameter3),\n"
18516             ">>>>>>> text by the vcs\n"
18517             "         otherparameter);\n",
18518             format("int a;\n"
18519                    "void f() {\n"
18520                    "  callme(some(parameter1,\n"
18521                    "<<<<<<< text by the vcs\n"
18522                    "  parameter2),\n"
18523                    "||||||| text by the vcs\n"
18524                    "  parameter2),\n"
18525                    "  parameter3,\n"
18526                    "======= text by the vcs\n"
18527                    "  parameter2,\n"
18528                    "  parameter3),\n"
18529                    ">>>>>>> text by the vcs\n"
18530                    "  otherparameter);\n"));
18531 
18532   // Perforce markers.
18533   EXPECT_EQ("void f() {\n"
18534             "  function(\n"
18535             ">>>> text by the vcs\n"
18536             "      parameter,\n"
18537             "==== text by the vcs\n"
18538             "      parameter,\n"
18539             "==== text by the vcs\n"
18540             "      parameter,\n"
18541             "<<<< text by the vcs\n"
18542             "      parameter);\n",
18543             format("void f() {\n"
18544                    "  function(\n"
18545                    ">>>> text by the vcs\n"
18546                    "  parameter,\n"
18547                    "==== text by the vcs\n"
18548                    "  parameter,\n"
18549                    "==== text by the vcs\n"
18550                    "  parameter,\n"
18551                    "<<<< text by the vcs\n"
18552                    "  parameter);\n"));
18553 
18554   EXPECT_EQ("<<<<<<<\n"
18555             "|||||||\n"
18556             "=======\n"
18557             ">>>>>>>",
18558             format("<<<<<<<\n"
18559                    "|||||||\n"
18560                    "=======\n"
18561                    ">>>>>>>"));
18562 
18563   EXPECT_EQ("<<<<<<<\n"
18564             "|||||||\n"
18565             "int i;\n"
18566             "=======\n"
18567             ">>>>>>>",
18568             format("<<<<<<<\n"
18569                    "|||||||\n"
18570                    "int i;\n"
18571                    "=======\n"
18572                    ">>>>>>>"));
18573 
18574   // FIXME: Handle parsing of macros around conflict markers correctly:
18575   EXPECT_EQ("#define Macro \\\n"
18576             "<<<<<<<\n"
18577             "Something \\\n"
18578             "|||||||\n"
18579             "Else \\\n"
18580             "=======\n"
18581             "Other \\\n"
18582             ">>>>>>>\n"
18583             "    End int i;\n",
18584             format("#define Macro \\\n"
18585                    "<<<<<<<\n"
18586                    "  Something \\\n"
18587                    "|||||||\n"
18588                    "  Else \\\n"
18589                    "=======\n"
18590                    "  Other \\\n"
18591                    ">>>>>>>\n"
18592                    "  End\n"
18593                    "int i;\n"));
18594 }
18595 
18596 TEST_F(FormatTest, DisableRegions) {
18597   EXPECT_EQ("int i;\n"
18598             "// clang-format off\n"
18599             "  int j;\n"
18600             "// clang-format on\n"
18601             "int k;",
18602             format(" int  i;\n"
18603                    "   // clang-format off\n"
18604                    "  int j;\n"
18605                    " // clang-format on\n"
18606                    "   int   k;"));
18607   EXPECT_EQ("int i;\n"
18608             "/* clang-format off */\n"
18609             "  int j;\n"
18610             "/* clang-format on */\n"
18611             "int k;",
18612             format(" int  i;\n"
18613                    "   /* clang-format off */\n"
18614                    "  int j;\n"
18615                    " /* clang-format on */\n"
18616                    "   int   k;"));
18617 
18618   // Don't reflow comments within disabled regions.
18619   EXPECT_EQ("// clang-format off\n"
18620             "// long long long long long long line\n"
18621             "/* clang-format on */\n"
18622             "/* long long long\n"
18623             " * long long long\n"
18624             " * line */\n"
18625             "int i;\n"
18626             "/* clang-format off */\n"
18627             "/* long long long long long long line */\n",
18628             format("// clang-format off\n"
18629                    "// long long long long long long line\n"
18630                    "/* clang-format on */\n"
18631                    "/* long long long long long long line */\n"
18632                    "int i;\n"
18633                    "/* clang-format off */\n"
18634                    "/* long long long long long long line */\n",
18635                    getLLVMStyleWithColumns(20)));
18636 }
18637 
18638 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
18639   format("? ) =");
18640   verifyNoCrash("#define a\\\n /**/}");
18641 }
18642 
18643 TEST_F(FormatTest, FormatsTableGenCode) {
18644   FormatStyle Style = getLLVMStyle();
18645   Style.Language = FormatStyle::LK_TableGen;
18646   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
18647 }
18648 
18649 TEST_F(FormatTest, ArrayOfTemplates) {
18650   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
18651             format("auto a = new unique_ptr<int > [ 10];"));
18652 
18653   FormatStyle Spaces = getLLVMStyle();
18654   Spaces.SpacesInSquareBrackets = true;
18655   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
18656             format("auto a = new unique_ptr<int > [10];", Spaces));
18657 }
18658 
18659 TEST_F(FormatTest, ArrayAsTemplateType) {
18660   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
18661             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
18662 
18663   FormatStyle Spaces = getLLVMStyle();
18664   Spaces.SpacesInSquareBrackets = true;
18665   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
18666             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
18667 }
18668 
18669 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
18670 
18671 TEST(FormatStyle, GetStyleWithEmptyFileName) {
18672   llvm::vfs::InMemoryFileSystem FS;
18673   auto Style1 = getStyle("file", "", "Google", "", &FS);
18674   ASSERT_TRUE((bool)Style1);
18675   ASSERT_EQ(*Style1, getGoogleStyle());
18676 }
18677 
18678 TEST(FormatStyle, GetStyleOfFile) {
18679   llvm::vfs::InMemoryFileSystem FS;
18680   // Test 1: format file in the same directory.
18681   ASSERT_TRUE(
18682       FS.addFile("/a/.clang-format", 0,
18683                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
18684   ASSERT_TRUE(
18685       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
18686   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
18687   ASSERT_TRUE((bool)Style1);
18688   ASSERT_EQ(*Style1, getLLVMStyle());
18689 
18690   // Test 2.1: fallback to default.
18691   ASSERT_TRUE(
18692       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
18693   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
18694   ASSERT_TRUE((bool)Style2);
18695   ASSERT_EQ(*Style2, getMozillaStyle());
18696 
18697   // Test 2.2: no format on 'none' fallback style.
18698   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
18699   ASSERT_TRUE((bool)Style2);
18700   ASSERT_EQ(*Style2, getNoStyle());
18701 
18702   // Test 2.3: format if config is found with no based style while fallback is
18703   // 'none'.
18704   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
18705                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
18706   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
18707   ASSERT_TRUE((bool)Style2);
18708   ASSERT_EQ(*Style2, getLLVMStyle());
18709 
18710   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
18711   Style2 = getStyle("{}", "a.h", "none", "", &FS);
18712   ASSERT_TRUE((bool)Style2);
18713   ASSERT_EQ(*Style2, getLLVMStyle());
18714 
18715   // Test 3: format file in parent directory.
18716   ASSERT_TRUE(
18717       FS.addFile("/c/.clang-format", 0,
18718                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
18719   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
18720                          llvm::MemoryBuffer::getMemBuffer("int i;")));
18721   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
18722   ASSERT_TRUE((bool)Style3);
18723   ASSERT_EQ(*Style3, getGoogleStyle());
18724 
18725   // Test 4: error on invalid fallback style
18726   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
18727   ASSERT_FALSE((bool)Style4);
18728   llvm::consumeError(Style4.takeError());
18729 
18730   // Test 5: error on invalid yaml on command line
18731   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
18732   ASSERT_FALSE((bool)Style5);
18733   llvm::consumeError(Style5.takeError());
18734 
18735   // Test 6: error on invalid style
18736   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
18737   ASSERT_FALSE((bool)Style6);
18738   llvm::consumeError(Style6.takeError());
18739 
18740   // Test 7: found config file, error on parsing it
18741   ASSERT_TRUE(
18742       FS.addFile("/d/.clang-format", 0,
18743                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
18744                                                   "InvalidKey: InvalidValue")));
18745   ASSERT_TRUE(
18746       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
18747   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
18748   ASSERT_FALSE((bool)Style7a);
18749   llvm::consumeError(Style7a.takeError());
18750 
18751   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
18752   ASSERT_TRUE((bool)Style7b);
18753 
18754   // Test 8: inferred per-language defaults apply.
18755   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
18756   ASSERT_TRUE((bool)StyleTd);
18757   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
18758 
18759   // Test 9.1: overwriting a file style, when parent no file exists with no
18760   // fallback style
18761   ASSERT_TRUE(FS.addFile(
18762       "/e/sub/.clang-format", 0,
18763       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
18764                                        "ColumnLimit: 20")));
18765   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
18766                          llvm::MemoryBuffer::getMemBuffer("int i;")));
18767   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
18768   ASSERT_TRUE(static_cast<bool>(Style9));
18769   ASSERT_EQ(*Style9, [] {
18770     auto Style = getNoStyle();
18771     Style.ColumnLimit = 20;
18772     return Style;
18773   }());
18774 
18775   // Test 9.2: with LLVM fallback style
18776   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
18777   ASSERT_TRUE(static_cast<bool>(Style9));
18778   ASSERT_EQ(*Style9, [] {
18779     auto Style = getLLVMStyle();
18780     Style.ColumnLimit = 20;
18781     return Style;
18782   }());
18783 
18784   // Test 9.3: with a parent file
18785   ASSERT_TRUE(
18786       FS.addFile("/e/.clang-format", 0,
18787                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
18788                                                   "UseTab: Always")));
18789   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
18790   ASSERT_TRUE(static_cast<bool>(Style9));
18791   ASSERT_EQ(*Style9, [] {
18792     auto Style = getGoogleStyle();
18793     Style.ColumnLimit = 20;
18794     Style.UseTab = FormatStyle::UT_Always;
18795     return Style;
18796   }());
18797 
18798   // Test 9.4: propagate more than one level
18799   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
18800                          llvm::MemoryBuffer::getMemBuffer("int i;")));
18801   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
18802                          llvm::MemoryBuffer::getMemBuffer(
18803                              "BasedOnStyle: InheritParentConfig\n"
18804                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
18805   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
18806 
18807   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
18808     auto Style = getGoogleStyle();
18809     Style.ColumnLimit = 20;
18810     Style.UseTab = FormatStyle::UT_Always;
18811     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
18812     return Style;
18813   }();
18814 
18815   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
18816   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
18817   ASSERT_TRUE(static_cast<bool>(Style9));
18818   ASSERT_EQ(*Style9, SubSubStyle);
18819 
18820   // Test 9.5: use InheritParentConfig as style name
18821   Style9 =
18822       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
18823   ASSERT_TRUE(static_cast<bool>(Style9));
18824   ASSERT_EQ(*Style9, SubSubStyle);
18825 
18826   // Test 9.6: use command line style with inheritance
18827   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
18828                     "none", "", &FS);
18829   ASSERT_TRUE(static_cast<bool>(Style9));
18830   ASSERT_EQ(*Style9, SubSubStyle);
18831 
18832   // Test 9.7: use command line style with inheritance and own config
18833   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
18834                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
18835                     "/e/sub/code.cpp", "none", "", &FS);
18836   ASSERT_TRUE(static_cast<bool>(Style9));
18837   ASSERT_EQ(*Style9, SubSubStyle);
18838 
18839   // Test 9.8: use inheritance from a file without BasedOnStyle
18840   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
18841                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
18842   ASSERT_TRUE(
18843       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
18844                  llvm::MemoryBuffer::getMemBuffer(
18845                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
18846   // Make sure we do not use the fallback style
18847   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
18848   ASSERT_TRUE(static_cast<bool>(Style9));
18849   ASSERT_EQ(*Style9, [] {
18850     auto Style = getLLVMStyle();
18851     Style.ColumnLimit = 123;
18852     return Style;
18853   }());
18854 
18855   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
18856   ASSERT_TRUE(static_cast<bool>(Style9));
18857   ASSERT_EQ(*Style9, [] {
18858     auto Style = getLLVMStyle();
18859     Style.ColumnLimit = 123;
18860     Style.IndentWidth = 7;
18861     return Style;
18862   }());
18863 }
18864 
18865 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
18866   // Column limit is 20.
18867   std::string Code = "Type *a =\n"
18868                      "    new Type();\n"
18869                      "g(iiiii, 0, jjjjj,\n"
18870                      "  0, kkkkk, 0, mm);\n"
18871                      "int  bad     = format   ;";
18872   std::string Expected = "auto a = new Type();\n"
18873                          "g(iiiii, nullptr,\n"
18874                          "  jjjjj, nullptr,\n"
18875                          "  kkkkk, nullptr,\n"
18876                          "  mm);\n"
18877                          "int  bad     = format   ;";
18878   FileID ID = Context.createInMemoryFile("format.cpp", Code);
18879   tooling::Replacements Replaces = toReplacements(
18880       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
18881                             "auto "),
18882        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
18883                             "nullptr"),
18884        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
18885                             "nullptr"),
18886        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
18887                             "nullptr")});
18888 
18889   format::FormatStyle Style = format::getLLVMStyle();
18890   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
18891   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
18892   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
18893       << llvm::toString(FormattedReplaces.takeError()) << "\n";
18894   auto Result = applyAllReplacements(Code, *FormattedReplaces);
18895   EXPECT_TRUE(static_cast<bool>(Result));
18896   EXPECT_EQ(Expected, *Result);
18897 }
18898 
18899 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
18900   std::string Code = "#include \"a.h\"\n"
18901                      "#include \"c.h\"\n"
18902                      "\n"
18903                      "int main() {\n"
18904                      "  return 0;\n"
18905                      "}";
18906   std::string Expected = "#include \"a.h\"\n"
18907                          "#include \"b.h\"\n"
18908                          "#include \"c.h\"\n"
18909                          "\n"
18910                          "int main() {\n"
18911                          "  return 0;\n"
18912                          "}";
18913   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
18914   tooling::Replacements Replaces = toReplacements(
18915       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
18916                             "#include \"b.h\"\n")});
18917 
18918   format::FormatStyle Style = format::getLLVMStyle();
18919   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
18920   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
18921   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
18922       << llvm::toString(FormattedReplaces.takeError()) << "\n";
18923   auto Result = applyAllReplacements(Code, *FormattedReplaces);
18924   EXPECT_TRUE(static_cast<bool>(Result));
18925   EXPECT_EQ(Expected, *Result);
18926 }
18927 
18928 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
18929   EXPECT_EQ("using std::cin;\n"
18930             "using std::cout;",
18931             format("using std::cout;\n"
18932                    "using std::cin;",
18933                    getGoogleStyle()));
18934 }
18935 
18936 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
18937   format::FormatStyle Style = format::getLLVMStyle();
18938   Style.Standard = FormatStyle::LS_Cpp03;
18939   // cpp03 recognize this string as identifier u8 and literal character 'a'
18940   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
18941 }
18942 
18943 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
18944   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
18945   // all modes, including C++11, C++14 and C++17
18946   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
18947 }
18948 
18949 TEST_F(FormatTest, DoNotFormatLikelyXml) {
18950   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
18951   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
18952 }
18953 
18954 TEST_F(FormatTest, StructuredBindings) {
18955   // Structured bindings is a C++17 feature.
18956   // all modes, including C++11, C++14 and C++17
18957   verifyFormat("auto [a, b] = f();");
18958   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
18959   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
18960   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
18961   EXPECT_EQ("auto const volatile [a, b] = f();",
18962             format("auto  const   volatile[a, b] = f();"));
18963   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
18964   EXPECT_EQ("auto &[a, b, c] = f();",
18965             format("auto   &[  a  ,  b,c   ] = f();"));
18966   EXPECT_EQ("auto &&[a, b, c] = f();",
18967             format("auto   &&[  a  ,  b,c   ] = f();"));
18968   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
18969   EXPECT_EQ("auto const volatile &&[a, b] = f();",
18970             format("auto  const  volatile  &&[a, b] = f();"));
18971   EXPECT_EQ("auto const &&[a, b] = f();",
18972             format("auto  const   &&  [a, b] = f();"));
18973   EXPECT_EQ("const auto &[a, b] = f();",
18974             format("const  auto  &  [a, b] = f();"));
18975   EXPECT_EQ("const auto volatile &&[a, b] = f();",
18976             format("const  auto   volatile  &&[a, b] = f();"));
18977   EXPECT_EQ("volatile const auto &&[a, b] = f();",
18978             format("volatile  const  auto   &&[a, b] = f();"));
18979   EXPECT_EQ("const auto &&[a, b] = f();",
18980             format("const  auto  &&  [a, b] = f();"));
18981 
18982   // Make sure we don't mistake structured bindings for lambdas.
18983   FormatStyle PointerMiddle = getLLVMStyle();
18984   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
18985   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
18986   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
18987   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
18988   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
18989   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
18990   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
18991   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
18992   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
18993   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
18994   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
18995   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
18996   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
18997 
18998   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
18999             format("for (const auto   &&   [a, b] : some_range) {\n}"));
19000   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
19001             format("for (const auto   &   [a, b] : some_range) {\n}"));
19002   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
19003             format("for (const auto[a, b] : some_range) {\n}"));
19004   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
19005   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
19006   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
19007   EXPECT_EQ("auto const &[x, y](expr);",
19008             format("auto  const  &  [x,y]  (expr);"));
19009   EXPECT_EQ("auto const &&[x, y](expr);",
19010             format("auto  const  &&  [x,y]  (expr);"));
19011   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
19012   EXPECT_EQ("auto const &[x, y]{expr};",
19013             format("auto  const  &  [x,y]  {expr};"));
19014   EXPECT_EQ("auto const &&[x, y]{expr};",
19015             format("auto  const  &&  [x,y]  {expr};"));
19016 
19017   format::FormatStyle Spaces = format::getLLVMStyle();
19018   Spaces.SpacesInSquareBrackets = true;
19019   verifyFormat("auto [ a, b ] = f();", Spaces);
19020   verifyFormat("auto &&[ a, b ] = f();", Spaces);
19021   verifyFormat("auto &[ a, b ] = f();", Spaces);
19022   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
19023   verifyFormat("auto const &[ a, b ] = f();", Spaces);
19024 }
19025 
19026 TEST_F(FormatTest, FileAndCode) {
19027   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
19028   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
19029   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
19030   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
19031   EXPECT_EQ(FormatStyle::LK_ObjC,
19032             guessLanguage("foo.h", "@interface Foo\n@end\n"));
19033   EXPECT_EQ(
19034       FormatStyle::LK_ObjC,
19035       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
19036   EXPECT_EQ(FormatStyle::LK_ObjC,
19037             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
19038   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
19039   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
19040   EXPECT_EQ(FormatStyle::LK_ObjC,
19041             guessLanguage("foo", "@interface Foo\n@end\n"));
19042   EXPECT_EQ(FormatStyle::LK_ObjC,
19043             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
19044   EXPECT_EQ(
19045       FormatStyle::LK_ObjC,
19046       guessLanguage("foo.h",
19047                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
19048   EXPECT_EQ(
19049       FormatStyle::LK_Cpp,
19050       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
19051 }
19052 
19053 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
19054   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
19055   EXPECT_EQ(FormatStyle::LK_ObjC,
19056             guessLanguage("foo.h", "array[[calculator getIndex]];"));
19057   EXPECT_EQ(FormatStyle::LK_Cpp,
19058             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
19059   EXPECT_EQ(
19060       FormatStyle::LK_Cpp,
19061       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
19062   EXPECT_EQ(FormatStyle::LK_ObjC,
19063             guessLanguage("foo.h", "[[noreturn foo] bar];"));
19064   EXPECT_EQ(FormatStyle::LK_Cpp,
19065             guessLanguage("foo.h", "[[clang::fallthrough]];"));
19066   EXPECT_EQ(FormatStyle::LK_ObjC,
19067             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
19068   EXPECT_EQ(FormatStyle::LK_Cpp,
19069             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
19070   EXPECT_EQ(FormatStyle::LK_Cpp,
19071             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
19072   EXPECT_EQ(FormatStyle::LK_ObjC,
19073             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
19074   EXPECT_EQ(FormatStyle::LK_Cpp,
19075             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
19076   EXPECT_EQ(
19077       FormatStyle::LK_Cpp,
19078       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
19079   EXPECT_EQ(
19080       FormatStyle::LK_Cpp,
19081       guessLanguage("foo.h",
19082                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
19083   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
19084 }
19085 
19086 TEST_F(FormatTest, GuessLanguageWithCaret) {
19087   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
19088   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
19089   EXPECT_EQ(FormatStyle::LK_ObjC,
19090             guessLanguage("foo.h", "int(^)(char, float);"));
19091   EXPECT_EQ(FormatStyle::LK_ObjC,
19092             guessLanguage("foo.h", "int(^foo)(char, float);"));
19093   EXPECT_EQ(FormatStyle::LK_ObjC,
19094             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
19095   EXPECT_EQ(FormatStyle::LK_ObjC,
19096             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
19097   EXPECT_EQ(
19098       FormatStyle::LK_ObjC,
19099       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
19100 }
19101 
19102 TEST_F(FormatTest, GuessLanguageWithPragmas) {
19103   EXPECT_EQ(FormatStyle::LK_Cpp,
19104             guessLanguage("foo.h", "__pragma(warning(disable:))"));
19105   EXPECT_EQ(FormatStyle::LK_Cpp,
19106             guessLanguage("foo.h", "#pragma(warning(disable:))"));
19107   EXPECT_EQ(FormatStyle::LK_Cpp,
19108             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
19109 }
19110 
19111 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
19112   // ASM symbolic names are identifiers that must be surrounded by [] without
19113   // space in between:
19114   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
19115 
19116   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
19117   verifyFormat(R"(//
19118 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
19119 )");
19120 
19121   // A list of several ASM symbolic names.
19122   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
19123 
19124   // ASM symbolic names in inline ASM with inputs and outputs.
19125   verifyFormat(R"(//
19126 asm("cmoveq %1, %2, %[result]"
19127     : [result] "=r"(result)
19128     : "r"(test), "r"(new), "[result]"(old));
19129 )");
19130 
19131   // ASM symbolic names in inline ASM with no outputs.
19132   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
19133 }
19134 
19135 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
19136   EXPECT_EQ(FormatStyle::LK_Cpp,
19137             guessLanguage("foo.h", "void f() {\n"
19138                                    "  asm (\"mov %[e], %[d]\"\n"
19139                                    "     : [d] \"=rm\" (d)\n"
19140                                    "       [e] \"rm\" (*e));\n"
19141                                    "}"));
19142   EXPECT_EQ(FormatStyle::LK_Cpp,
19143             guessLanguage("foo.h", "void f() {\n"
19144                                    "  _asm (\"mov %[e], %[d]\"\n"
19145                                    "     : [d] \"=rm\" (d)\n"
19146                                    "       [e] \"rm\" (*e));\n"
19147                                    "}"));
19148   EXPECT_EQ(FormatStyle::LK_Cpp,
19149             guessLanguage("foo.h", "void f() {\n"
19150                                    "  __asm (\"mov %[e], %[d]\"\n"
19151                                    "     : [d] \"=rm\" (d)\n"
19152                                    "       [e] \"rm\" (*e));\n"
19153                                    "}"));
19154   EXPECT_EQ(FormatStyle::LK_Cpp,
19155             guessLanguage("foo.h", "void f() {\n"
19156                                    "  __asm__ (\"mov %[e], %[d]\"\n"
19157                                    "     : [d] \"=rm\" (d)\n"
19158                                    "       [e] \"rm\" (*e));\n"
19159                                    "}"));
19160   EXPECT_EQ(FormatStyle::LK_Cpp,
19161             guessLanguage("foo.h", "void f() {\n"
19162                                    "  asm (\"mov %[e], %[d]\"\n"
19163                                    "     : [d] \"=rm\" (d),\n"
19164                                    "       [e] \"rm\" (*e));\n"
19165                                    "}"));
19166   EXPECT_EQ(FormatStyle::LK_Cpp,
19167             guessLanguage("foo.h", "void f() {\n"
19168                                    "  asm volatile (\"mov %[e], %[d]\"\n"
19169                                    "     : [d] \"=rm\" (d)\n"
19170                                    "       [e] \"rm\" (*e));\n"
19171                                    "}"));
19172 }
19173 
19174 TEST_F(FormatTest, GuessLanguageWithChildLines) {
19175   EXPECT_EQ(FormatStyle::LK_Cpp,
19176             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
19177   EXPECT_EQ(FormatStyle::LK_ObjC,
19178             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
19179   EXPECT_EQ(
19180       FormatStyle::LK_Cpp,
19181       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
19182   EXPECT_EQ(
19183       FormatStyle::LK_ObjC,
19184       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
19185 }
19186 
19187 TEST_F(FormatTest, TypenameMacros) {
19188   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
19189 
19190   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
19191   FormatStyle Google = getGoogleStyleWithColumns(0);
19192   Google.TypenameMacros = TypenameMacros;
19193   verifyFormat("struct foo {\n"
19194                "  int bar;\n"
19195                "  TAILQ_ENTRY(a) bleh;\n"
19196                "};",
19197                Google);
19198 
19199   FormatStyle Macros = getLLVMStyle();
19200   Macros.TypenameMacros = TypenameMacros;
19201 
19202   verifyFormat("STACK_OF(int) a;", Macros);
19203   verifyFormat("STACK_OF(int) *a;", Macros);
19204   verifyFormat("STACK_OF(int const *) *a;", Macros);
19205   verifyFormat("STACK_OF(int *const) *a;", Macros);
19206   verifyFormat("STACK_OF(int, string) a;", Macros);
19207   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
19208   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
19209   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
19210   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
19211   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
19212   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
19213 
19214   Macros.PointerAlignment = FormatStyle::PAS_Left;
19215   verifyFormat("STACK_OF(int)* a;", Macros);
19216   verifyFormat("STACK_OF(int*)* a;", Macros);
19217   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
19218   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
19219   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
19220 }
19221 
19222 TEST_F(FormatTest, AtomicQualifier) {
19223   // Check that we treate _Atomic as a type and not a function call
19224   FormatStyle Google = getGoogleStyleWithColumns(0);
19225   verifyFormat("struct foo {\n"
19226                "  int a1;\n"
19227                "  _Atomic(a) a2;\n"
19228                "  _Atomic(_Atomic(int) *const) a3;\n"
19229                "};",
19230                Google);
19231   verifyFormat("_Atomic(uint64_t) a;");
19232   verifyFormat("_Atomic(uint64_t) *a;");
19233   verifyFormat("_Atomic(uint64_t const *) *a;");
19234   verifyFormat("_Atomic(uint64_t *const) *a;");
19235   verifyFormat("_Atomic(const uint64_t *) *a;");
19236   verifyFormat("_Atomic(uint64_t) a;");
19237   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
19238   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
19239   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
19240   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
19241 
19242   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
19243   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
19244   FormatStyle Style = getLLVMStyle();
19245   Style.PointerAlignment = FormatStyle::PAS_Left;
19246   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
19247   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
19248   verifyFormat("_Atomic(int)* a;", Style);
19249   verifyFormat("_Atomic(int*)* a;", Style);
19250   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
19251 
19252   Style.SpacesInCStyleCastParentheses = true;
19253   Style.SpacesInParentheses = false;
19254   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
19255   Style.SpacesInCStyleCastParentheses = false;
19256   Style.SpacesInParentheses = true;
19257   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
19258   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
19259 }
19260 
19261 TEST_F(FormatTest, AmbersandInLamda) {
19262   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
19263   FormatStyle AlignStyle = getLLVMStyle();
19264   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
19265   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
19266   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
19267   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
19268 }
19269 
19270 TEST_F(FormatTest, SpacesInConditionalStatement) {
19271   FormatStyle Spaces = getLLVMStyle();
19272   Spaces.SpacesInConditionalStatement = true;
19273   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
19274   verifyFormat("if ( !a )\n  return;", Spaces);
19275   verifyFormat("if ( a )\n  return;", Spaces);
19276   verifyFormat("if constexpr ( a )\n  return;", Spaces);
19277   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
19278   verifyFormat("while ( a )\n  return;", Spaces);
19279   verifyFormat("while ( (a && b) )\n  return;", Spaces);
19280   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
19281   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
19282   // Check that space on the left of "::" is inserted as expected at beginning
19283   // of condition.
19284   verifyFormat("while ( ::func() )\n  return;", Spaces);
19285 }
19286 
19287 TEST_F(FormatTest, AlternativeOperators) {
19288   // Test case for ensuring alternate operators are not
19289   // combined with their right most neighbour.
19290   verifyFormat("int a and b;");
19291   verifyFormat("int a and_eq b;");
19292   verifyFormat("int a bitand b;");
19293   verifyFormat("int a bitor b;");
19294   verifyFormat("int a compl b;");
19295   verifyFormat("int a not b;");
19296   verifyFormat("int a not_eq b;");
19297   verifyFormat("int a or b;");
19298   verifyFormat("int a xor b;");
19299   verifyFormat("int a xor_eq b;");
19300   verifyFormat("return this not_eq bitand other;");
19301   verifyFormat("bool operator not_eq(const X bitand other)");
19302 
19303   verifyFormat("int a and 5;");
19304   verifyFormat("int a and_eq 5;");
19305   verifyFormat("int a bitand 5;");
19306   verifyFormat("int a bitor 5;");
19307   verifyFormat("int a compl 5;");
19308   verifyFormat("int a not 5;");
19309   verifyFormat("int a not_eq 5;");
19310   verifyFormat("int a or 5;");
19311   verifyFormat("int a xor 5;");
19312   verifyFormat("int a xor_eq 5;");
19313 
19314   verifyFormat("int a compl(5);");
19315   verifyFormat("int a not(5);");
19316 
19317   /* FIXME handle alternate tokens
19318    * https://en.cppreference.com/w/cpp/language/operator_alternative
19319   // alternative tokens
19320   verifyFormat("compl foo();");     //  ~foo();
19321   verifyFormat("foo() <%%>;");      // foo();
19322   verifyFormat("void foo() <%%>;"); // void foo(){}
19323   verifyFormat("int a <:1:>;");     // int a[1];[
19324   verifyFormat("%:define ABC abc"); // #define ABC abc
19325   verifyFormat("%:%:");             // ##
19326   */
19327 }
19328 
19329 TEST_F(FormatTest, STLWhileNotDefineChed) {
19330   verifyFormat("#if defined(while)\n"
19331                "#define while EMIT WARNING C4005\n"
19332                "#endif // while");
19333 }
19334 
19335 TEST_F(FormatTest, OperatorSpacing) {
19336   FormatStyle Style = getLLVMStyle();
19337   Style.PointerAlignment = FormatStyle::PAS_Right;
19338   verifyFormat("Foo::operator*();", Style);
19339   verifyFormat("Foo::operator void *();", Style);
19340   verifyFormat("Foo::operator void **();", Style);
19341   verifyFormat("Foo::operator void *&();", Style);
19342   verifyFormat("Foo::operator void *&&();", Style);
19343   verifyFormat("Foo::operator void const *();", Style);
19344   verifyFormat("Foo::operator void const **();", Style);
19345   verifyFormat("Foo::operator void const *&();", Style);
19346   verifyFormat("Foo::operator void const *&&();", Style);
19347   verifyFormat("Foo::operator()(void *);", Style);
19348   verifyFormat("Foo::operator*(void *);", Style);
19349   verifyFormat("Foo::operator*();", Style);
19350   verifyFormat("Foo::operator**();", Style);
19351   verifyFormat("Foo::operator&();", Style);
19352   verifyFormat("Foo::operator<int> *();", Style);
19353   verifyFormat("Foo::operator<Foo> *();", Style);
19354   verifyFormat("Foo::operator<int> **();", Style);
19355   verifyFormat("Foo::operator<Foo> **();", Style);
19356   verifyFormat("Foo::operator<int> &();", Style);
19357   verifyFormat("Foo::operator<Foo> &();", Style);
19358   verifyFormat("Foo::operator<int> &&();", Style);
19359   verifyFormat("Foo::operator<Foo> &&();", Style);
19360   verifyFormat("Foo::operator<int> *&();", Style);
19361   verifyFormat("Foo::operator<Foo> *&();", Style);
19362   verifyFormat("Foo::operator<int> *&&();", Style);
19363   verifyFormat("Foo::operator<Foo> *&&();", Style);
19364   verifyFormat("operator*(int (*)(), class Foo);", Style);
19365 
19366   verifyFormat("Foo::operator&();", Style);
19367   verifyFormat("Foo::operator void &();", Style);
19368   verifyFormat("Foo::operator void const &();", Style);
19369   verifyFormat("Foo::operator()(void &);", Style);
19370   verifyFormat("Foo::operator&(void &);", Style);
19371   verifyFormat("Foo::operator&();", Style);
19372   verifyFormat("operator&(int (&)(), class Foo);", Style);
19373 
19374   verifyFormat("Foo::operator&&();", Style);
19375   verifyFormat("Foo::operator**();", Style);
19376   verifyFormat("Foo::operator void &&();", Style);
19377   verifyFormat("Foo::operator void const &&();", Style);
19378   verifyFormat("Foo::operator()(void &&);", Style);
19379   verifyFormat("Foo::operator&&(void &&);", Style);
19380   verifyFormat("Foo::operator&&();", Style);
19381   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
19382   verifyFormat("operator const nsTArrayRight<E> &()", Style);
19383   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
19384                Style);
19385   verifyFormat("operator void **()", Style);
19386   verifyFormat("operator const FooRight<Object> &()", Style);
19387   verifyFormat("operator const FooRight<Object> *()", Style);
19388   verifyFormat("operator const FooRight<Object> **()", Style);
19389   verifyFormat("operator const FooRight<Object> *&()", Style);
19390   verifyFormat("operator const FooRight<Object> *&&()", Style);
19391 
19392   Style.PointerAlignment = FormatStyle::PAS_Left;
19393   verifyFormat("Foo::operator*();", Style);
19394   verifyFormat("Foo::operator**();", Style);
19395   verifyFormat("Foo::operator void*();", Style);
19396   verifyFormat("Foo::operator void**();", Style);
19397   verifyFormat("Foo::operator void*&();", Style);
19398   verifyFormat("Foo::operator void*&&();", Style);
19399   verifyFormat("Foo::operator void const*();", Style);
19400   verifyFormat("Foo::operator void const**();", Style);
19401   verifyFormat("Foo::operator void const*&();", Style);
19402   verifyFormat("Foo::operator void const*&&();", Style);
19403   verifyFormat("Foo::operator/*comment*/ void*();", Style);
19404   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
19405   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
19406   verifyFormat("Foo::operator()(void*);", Style);
19407   verifyFormat("Foo::operator*(void*);", Style);
19408   verifyFormat("Foo::operator*();", Style);
19409   verifyFormat("Foo::operator<int>*();", Style);
19410   verifyFormat("Foo::operator<Foo>*();", Style);
19411   verifyFormat("Foo::operator<int>**();", Style);
19412   verifyFormat("Foo::operator<Foo>**();", Style);
19413   verifyFormat("Foo::operator<Foo>*&();", Style);
19414   verifyFormat("Foo::operator<int>&();", Style);
19415   verifyFormat("Foo::operator<Foo>&();", Style);
19416   verifyFormat("Foo::operator<int>&&();", Style);
19417   verifyFormat("Foo::operator<Foo>&&();", Style);
19418   verifyFormat("Foo::operator<int>*&();", Style);
19419   verifyFormat("Foo::operator<Foo>*&();", Style);
19420   verifyFormat("operator*(int (*)(), class Foo);", Style);
19421 
19422   verifyFormat("Foo::operator&();", Style);
19423   verifyFormat("Foo::operator void&();", Style);
19424   verifyFormat("Foo::operator void const&();", Style);
19425   verifyFormat("Foo::operator/*comment*/ void&();", Style);
19426   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
19427   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
19428   verifyFormat("Foo::operator()(void&);", Style);
19429   verifyFormat("Foo::operator&(void&);", Style);
19430   verifyFormat("Foo::operator&();", Style);
19431   verifyFormat("operator&(int (&)(), class Foo);", Style);
19432 
19433   verifyFormat("Foo::operator&&();", Style);
19434   verifyFormat("Foo::operator void&&();", Style);
19435   verifyFormat("Foo::operator void const&&();", Style);
19436   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
19437   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
19438   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
19439   verifyFormat("Foo::operator()(void&&);", Style);
19440   verifyFormat("Foo::operator&&(void&&);", Style);
19441   verifyFormat("Foo::operator&&();", Style);
19442   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
19443   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
19444   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
19445                Style);
19446   verifyFormat("operator void**()", Style);
19447   verifyFormat("operator const FooLeft<Object>&()", Style);
19448   verifyFormat("operator const FooLeft<Object>*()", Style);
19449   verifyFormat("operator const FooLeft<Object>**()", Style);
19450   verifyFormat("operator const FooLeft<Object>*&()", Style);
19451   verifyFormat("operator const FooLeft<Object>*&&()", Style);
19452 
19453   // PR45107
19454   verifyFormat("operator Vector<String>&();", Style);
19455   verifyFormat("operator const Vector<String>&();", Style);
19456   verifyFormat("operator foo::Bar*();", Style);
19457   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
19458   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
19459                Style);
19460 
19461   Style.PointerAlignment = FormatStyle::PAS_Middle;
19462   verifyFormat("Foo::operator*();", Style);
19463   verifyFormat("Foo::operator void *();", Style);
19464   verifyFormat("Foo::operator()(void *);", Style);
19465   verifyFormat("Foo::operator*(void *);", Style);
19466   verifyFormat("Foo::operator*();", Style);
19467   verifyFormat("operator*(int (*)(), class Foo);", Style);
19468 
19469   verifyFormat("Foo::operator&();", Style);
19470   verifyFormat("Foo::operator void &();", Style);
19471   verifyFormat("Foo::operator void const &();", Style);
19472   verifyFormat("Foo::operator()(void &);", Style);
19473   verifyFormat("Foo::operator&(void &);", Style);
19474   verifyFormat("Foo::operator&();", Style);
19475   verifyFormat("operator&(int (&)(), class Foo);", Style);
19476 
19477   verifyFormat("Foo::operator&&();", Style);
19478   verifyFormat("Foo::operator void &&();", Style);
19479   verifyFormat("Foo::operator void const &&();", Style);
19480   verifyFormat("Foo::operator()(void &&);", Style);
19481   verifyFormat("Foo::operator&&(void &&);", Style);
19482   verifyFormat("Foo::operator&&();", Style);
19483   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
19484 }
19485 
19486 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
19487   FormatStyle Style = getLLVMStyle();
19488   // PR46157
19489   verifyFormat("foo(operator+, -42);", Style);
19490   verifyFormat("foo(operator++, -42);", Style);
19491   verifyFormat("foo(operator--, -42);", Style);
19492   verifyFormat("foo(-42, operator--);", Style);
19493   verifyFormat("foo(-42, operator, );", Style);
19494   verifyFormat("foo(operator, , -42);", Style);
19495 }
19496 
19497 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
19498   FormatStyle Style = getLLVMStyle();
19499   Style.WhitespaceSensitiveMacros.push_back("FOO");
19500 
19501   // Don't use the helpers here, since 'mess up' will change the whitespace
19502   // and these are all whitespace sensitive by definition
19503   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
19504             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
19505   EXPECT_EQ(
19506       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
19507       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
19508   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
19509             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
19510   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
19511             "       Still=Intentional);",
19512             format("FOO(String-ized&Messy+But,: :\n"
19513                    "       Still=Intentional);",
19514                    Style));
19515   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
19516   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
19517             "       Still=Intentional);",
19518             format("FOO(String-ized=&Messy+But,: :\n"
19519                    "       Still=Intentional);",
19520                    Style));
19521 
19522   Style.ColumnLimit = 21;
19523   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
19524             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
19525 }
19526 
19527 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
19528   // These tests are not in NamespaceFixer because that doesn't
19529   // test its interaction with line wrapping
19530   FormatStyle Style = getLLVMStyle();
19531   Style.ColumnLimit = 80;
19532   verifyFormat("namespace {\n"
19533                "int i;\n"
19534                "int j;\n"
19535                "} // namespace",
19536                Style);
19537 
19538   verifyFormat("namespace AAA {\n"
19539                "int i;\n"
19540                "int j;\n"
19541                "} // namespace AAA",
19542                Style);
19543 
19544   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
19545             "int i;\n"
19546             "int j;\n"
19547             "} // namespace Averyveryveryverylongnamespace",
19548             format("namespace Averyveryveryverylongnamespace {\n"
19549                    "int i;\n"
19550                    "int j;\n"
19551                    "}",
19552                    Style));
19553 
19554   EXPECT_EQ(
19555       "namespace "
19556       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
19557       "    went::mad::now {\n"
19558       "int i;\n"
19559       "int j;\n"
19560       "} // namespace\n"
19561       "  // "
19562       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
19563       "went::mad::now",
19564       format("namespace "
19565              "would::it::save::you::a::lot::of::time::if_::i::"
19566              "just::gave::up::and_::went::mad::now {\n"
19567              "int i;\n"
19568              "int j;\n"
19569              "}",
19570              Style));
19571 
19572   // This used to duplicate the comment again and again on subsequent runs
19573   EXPECT_EQ(
19574       "namespace "
19575       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
19576       "    went::mad::now {\n"
19577       "int i;\n"
19578       "int j;\n"
19579       "} // namespace\n"
19580       "  // "
19581       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
19582       "went::mad::now",
19583       format("namespace "
19584              "would::it::save::you::a::lot::of::time::if_::i::"
19585              "just::gave::up::and_::went::mad::now {\n"
19586              "int i;\n"
19587              "int j;\n"
19588              "} // namespace\n"
19589              "  // "
19590              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
19591              "and_::went::mad::now",
19592              Style));
19593 }
19594 
19595 TEST_F(FormatTest, LikelyUnlikely) {
19596   FormatStyle Style = getLLVMStyle();
19597 
19598   verifyFormat("if (argc > 5) [[unlikely]] {\n"
19599                "  return 29;\n"
19600                "}",
19601                Style);
19602 
19603   verifyFormat("if (argc > 5) [[likely]] {\n"
19604                "  return 29;\n"
19605                "}",
19606                Style);
19607 
19608   verifyFormat("if (argc > 5) [[unlikely]] {\n"
19609                "  return 29;\n"
19610                "} else [[likely]] {\n"
19611                "  return 42;\n"
19612                "}\n",
19613                Style);
19614 
19615   verifyFormat("if (argc > 5) [[unlikely]] {\n"
19616                "  return 29;\n"
19617                "} else if (argc > 10) [[likely]] {\n"
19618                "  return 99;\n"
19619                "} else {\n"
19620                "  return 42;\n"
19621                "}\n",
19622                Style);
19623 
19624   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
19625                "  return 29;\n"
19626                "}",
19627                Style);
19628 }
19629 
19630 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
19631   verifyFormat("Constructor()\n"
19632                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19633                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
19634                "aaaaaaaaaaaaaaaaaat))");
19635   verifyFormat("Constructor()\n"
19636                "    : aaaaaaaaaaaaa(aaaaaa), "
19637                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
19638 
19639   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
19640   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
19641   verifyFormat("Constructor()\n"
19642                "    : aaaaaa(aaaaaa),\n"
19643                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19644                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
19645                StyleWithWhitespacePenalty);
19646   verifyFormat("Constructor()\n"
19647                "    : aaaaaaaaaaaaa(aaaaaa), "
19648                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
19649                StyleWithWhitespacePenalty);
19650 }
19651 
19652 TEST_F(FormatTest, LLVMDefaultStyle) {
19653   FormatStyle Style = getLLVMStyle();
19654   verifyFormat("extern \"C\" {\n"
19655                "int foo();\n"
19656                "}",
19657                Style);
19658 }
19659 TEST_F(FormatTest, GNUDefaultStyle) {
19660   FormatStyle Style = getGNUStyle();
19661   verifyFormat("extern \"C\"\n"
19662                "{\n"
19663                "  int foo ();\n"
19664                "}",
19665                Style);
19666 }
19667 TEST_F(FormatTest, MozillaDefaultStyle) {
19668   FormatStyle Style = getMozillaStyle();
19669   verifyFormat("extern \"C\"\n"
19670                "{\n"
19671                "  int foo();\n"
19672                "}",
19673                Style);
19674 }
19675 TEST_F(FormatTest, GoogleDefaultStyle) {
19676   FormatStyle Style = getGoogleStyle();
19677   verifyFormat("extern \"C\" {\n"
19678                "int foo();\n"
19679                "}",
19680                Style);
19681 }
19682 TEST_F(FormatTest, ChromiumDefaultStyle) {
19683   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
19684   verifyFormat("extern \"C\" {\n"
19685                "int foo();\n"
19686                "}",
19687                Style);
19688 }
19689 TEST_F(FormatTest, MicrosoftDefaultStyle) {
19690   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
19691   verifyFormat("extern \"C\"\n"
19692                "{\n"
19693                "    int foo();\n"
19694                "}",
19695                Style);
19696 }
19697 TEST_F(FormatTest, WebKitDefaultStyle) {
19698   FormatStyle Style = getWebKitStyle();
19699   verifyFormat("extern \"C\" {\n"
19700                "int foo();\n"
19701                "}",
19702                Style);
19703 }
19704 
19705 TEST_F(FormatTest, ConceptsAndRequires) {
19706   FormatStyle Style = getLLVMStyle();
19707   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
19708 
19709   verifyFormat("template <typename T>\n"
19710                "concept Hashable = requires(T a) {\n"
19711                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
19712                "};",
19713                Style);
19714   verifyFormat("template <typename T>\n"
19715                "concept EqualityComparable = requires(T a, T b) {\n"
19716                "  { a == b } -> bool;\n"
19717                "};",
19718                Style);
19719   verifyFormat("template <typename T>\n"
19720                "concept EqualityComparable = requires(T a, T b) {\n"
19721                "  { a == b } -> bool;\n"
19722                "  { a != b } -> bool;\n"
19723                "};",
19724                Style);
19725   verifyFormat("template <typename T>\n"
19726                "concept EqualityComparable = requires(T a, T b) {\n"
19727                "  { a == b } -> bool;\n"
19728                "  { a != b } -> bool;\n"
19729                "};",
19730                Style);
19731 
19732   verifyFormat("template <typename It>\n"
19733                "requires Iterator<It>\n"
19734                "void sort(It begin, It end) {\n"
19735                "  //....\n"
19736                "}",
19737                Style);
19738 
19739   verifyFormat("template <typename T>\n"
19740                "concept Large = sizeof(T) > 10;",
19741                Style);
19742 
19743   verifyFormat("template <typename T, typename U>\n"
19744                "concept FooableWith = requires(T t, U u) {\n"
19745                "  typename T::foo_type;\n"
19746                "  { t.foo(u) } -> typename T::foo_type;\n"
19747                "  t++;\n"
19748                "};\n"
19749                "void doFoo(FooableWith<int> auto t) {\n"
19750                "  t.foo(3);\n"
19751                "}",
19752                Style);
19753   verifyFormat("template <typename T>\n"
19754                "concept Context = sizeof(T) == 1;",
19755                Style);
19756   verifyFormat("template <typename T>\n"
19757                "concept Context = is_specialization_of_v<context, T>;",
19758                Style);
19759   verifyFormat("template <typename T>\n"
19760                "concept Node = std::is_object_v<T>;",
19761                Style);
19762   verifyFormat("template <typename T>\n"
19763                "concept Tree = true;",
19764                Style);
19765 
19766   verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
19767                "  //...\n"
19768                "}",
19769                Style);
19770 
19771   verifyFormat(
19772       "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
19773       "  //...\n"
19774       "}",
19775       Style);
19776 
19777   verifyFormat(
19778       "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
19779       "  //...\n"
19780       "}",
19781       Style);
19782 
19783   verifyFormat("template <typename T>\n"
19784                "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
19785                "Concept2<I> {\n"
19786                "  //...\n"
19787                "}",
19788                Style);
19789 
19790   verifyFormat("template <typename T>\n"
19791                "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
19792                "Concept2<I> {\n"
19793                "  //...\n"
19794                "}",
19795                Style);
19796 
19797   verifyFormat(
19798       "template <typename T>\n"
19799       "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
19800       "  //...\n"
19801       "}",
19802       Style);
19803 
19804   verifyFormat(
19805       "template <typename T>\n"
19806       "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
19807       "  //...\n"
19808       "}",
19809       Style);
19810 
19811   verifyFormat("template <typename It>\n"
19812                "requires Foo<It>() && Bar<It> {\n"
19813                "  //....\n"
19814                "}",
19815                Style);
19816 
19817   verifyFormat("template <typename It>\n"
19818                "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
19819                "  //....\n"
19820                "}",
19821                Style);
19822 
19823   verifyFormat("template <typename It>\n"
19824                "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
19825                "  //....\n"
19826                "}",
19827                Style);
19828 
19829   verifyFormat(
19830       "template <typename It>\n"
19831       "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
19832       "  //....\n"
19833       "}",
19834       Style);
19835 
19836   Style.IndentRequires = true;
19837   verifyFormat("template <typename It>\n"
19838                "  requires Iterator<It>\n"
19839                "void sort(It begin, It end) {\n"
19840                "  //....\n"
19841                "}",
19842                Style);
19843   verifyFormat("template <std::size index_>\n"
19844                "  requires(index_ < sizeof...(Children_))\n"
19845                "Tree auto &child() {\n"
19846                "  // ...\n"
19847                "}",
19848                Style);
19849 
19850   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
19851   verifyFormat("template <typename T>\n"
19852                "concept Hashable = requires (T a) {\n"
19853                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
19854                "};",
19855                Style);
19856 
19857   verifyFormat("template <class T = void>\n"
19858                "  requires EqualityComparable<T> || Same<T, void>\n"
19859                "struct equal_to;",
19860                Style);
19861 
19862   verifyFormat("template <class T>\n"
19863                "  requires requires {\n"
19864                "    T{};\n"
19865                "    T (int);\n"
19866                "  }\n",
19867                Style);
19868 
19869   Style.ColumnLimit = 78;
19870   verifyFormat("template <typename T>\n"
19871                "concept Context = Traits<typename T::traits_type> and\n"
19872                "    Interface<typename T::interface_type> and\n"
19873                "    Request<typename T::request_type> and\n"
19874                "    Response<typename T::response_type> and\n"
19875                "    ContextExtension<typename T::extension_type> and\n"
19876                "    ::std::is_copy_constructable<T> and "
19877                "::std::is_move_constructable<T> and\n"
19878                "    requires (T c) {\n"
19879                "  { c.response; } -> Response;\n"
19880                "} and requires (T c) {\n"
19881                "  { c.request; } -> Request;\n"
19882                "}\n",
19883                Style);
19884 
19885   verifyFormat("template <typename T>\n"
19886                "concept Context = Traits<typename T::traits_type> or\n"
19887                "    Interface<typename T::interface_type> or\n"
19888                "    Request<typename T::request_type> or\n"
19889                "    Response<typename T::response_type> or\n"
19890                "    ContextExtension<typename T::extension_type> or\n"
19891                "    ::std::is_copy_constructable<T> or "
19892                "::std::is_move_constructable<T> or\n"
19893                "    requires (T c) {\n"
19894                "  { c.response; } -> Response;\n"
19895                "} or requires (T c) {\n"
19896                "  { c.request; } -> Request;\n"
19897                "}\n",
19898                Style);
19899 
19900   verifyFormat("template <typename T>\n"
19901                "concept Context = Traits<typename T::traits_type> &&\n"
19902                "    Interface<typename T::interface_type> &&\n"
19903                "    Request<typename T::request_type> &&\n"
19904                "    Response<typename T::response_type> &&\n"
19905                "    ContextExtension<typename T::extension_type> &&\n"
19906                "    ::std::is_copy_constructable<T> && "
19907                "::std::is_move_constructable<T> &&\n"
19908                "    requires (T c) {\n"
19909                "  { c.response; } -> Response;\n"
19910                "} && requires (T c) {\n"
19911                "  { c.request; } -> Request;\n"
19912                "}\n",
19913                Style);
19914 
19915   verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
19916                "Constraint2<T>;");
19917 
19918   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
19919   Style.BraceWrapping.AfterFunction = true;
19920   Style.BraceWrapping.AfterClass = true;
19921   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
19922   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
19923   verifyFormat("void Foo () requires (std::copyable<T>)\n"
19924                "{\n"
19925                "  return\n"
19926                "}\n",
19927                Style);
19928 
19929   verifyFormat("void Foo () requires std::copyable<T>\n"
19930                "{\n"
19931                "  return\n"
19932                "}\n",
19933                Style);
19934 
19935   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
19936                "  requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
19937                "struct constant;",
19938                Style);
19939 
19940   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
19941                "  requires std::invocable<F, std::invoke_result_t<Args>...>\n"
19942                "struct constant;",
19943                Style);
19944 
19945   verifyFormat("template <class T>\n"
19946                "class plane_with_very_very_very_long_name\n"
19947                "{\n"
19948                "  constexpr plane_with_very_very_very_long_name () requires "
19949                "std::copyable<T>\n"
19950                "      : plane_with_very_very_very_long_name (1)\n"
19951                "  {\n"
19952                "  }\n"
19953                "}\n",
19954                Style);
19955 
19956   verifyFormat("template <class T>\n"
19957                "class plane_with_long_name\n"
19958                "{\n"
19959                "  constexpr plane_with_long_name () requires std::copyable<T>\n"
19960                "      : plane_with_long_name (1)\n"
19961                "  {\n"
19962                "  }\n"
19963                "}\n",
19964                Style);
19965 
19966   Style.BreakBeforeConceptDeclarations = false;
19967   verifyFormat("template <typename T> concept Tree = true;", Style);
19968 
19969   Style.IndentRequires = false;
19970   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
19971                "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
19972                "struct constant;",
19973                Style);
19974 }
19975 
19976 TEST_F(FormatTest, StatementAttributeLikeMacros) {
19977   FormatStyle Style = getLLVMStyle();
19978   StringRef Source = "void Foo::slot() {\n"
19979                      "  unsigned char MyChar = 'x';\n"
19980                      "  emit signal(MyChar);\n"
19981                      "  Q_EMIT signal(MyChar);\n"
19982                      "}";
19983 
19984   EXPECT_EQ(Source, format(Source, Style));
19985 
19986   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
19987   EXPECT_EQ("void Foo::slot() {\n"
19988             "  unsigned char MyChar = 'x';\n"
19989             "  emit          signal(MyChar);\n"
19990             "  Q_EMIT signal(MyChar);\n"
19991             "}",
19992             format(Source, Style));
19993 
19994   Style.StatementAttributeLikeMacros.push_back("emit");
19995   EXPECT_EQ(Source, format(Source, Style));
19996 
19997   Style.StatementAttributeLikeMacros = {};
19998   EXPECT_EQ("void Foo::slot() {\n"
19999             "  unsigned char MyChar = 'x';\n"
20000             "  emit          signal(MyChar);\n"
20001             "  Q_EMIT        signal(MyChar);\n"
20002             "}",
20003             format(Source, Style));
20004 }
20005 
20006 TEST_F(FormatTest, IndentAccessModifiers) {
20007   FormatStyle Style = getLLVMStyle();
20008   Style.IndentAccessModifiers = true;
20009   // Members are *two* levels below the record;
20010   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
20011   verifyFormat("class C {\n"
20012                "    int i;\n"
20013                "};\n",
20014                Style);
20015   verifyFormat("union C {\n"
20016                "    int i;\n"
20017                "    unsigned u;\n"
20018                "};\n",
20019                Style);
20020   // Access modifiers should be indented one level below the record.
20021   verifyFormat("class C {\n"
20022                "  public:\n"
20023                "    int i;\n"
20024                "};\n",
20025                Style);
20026   verifyFormat("struct S {\n"
20027                "  private:\n"
20028                "    class C {\n"
20029                "        int j;\n"
20030                "\n"
20031                "      public:\n"
20032                "        C();\n"
20033                "    };\n"
20034                "\n"
20035                "  public:\n"
20036                "    int i;\n"
20037                "};\n",
20038                Style);
20039   // Enumerations are not records and should be unaffected.
20040   Style.AllowShortEnumsOnASingleLine = false;
20041   verifyFormat("enum class E\n"
20042                "{\n"
20043                "  A,\n"
20044                "  B\n"
20045                "};\n",
20046                Style);
20047   // Test with a different indentation width;
20048   // also proves that the result is Style.AccessModifierOffset agnostic.
20049   Style.IndentWidth = 3;
20050   verifyFormat("class C {\n"
20051                "   public:\n"
20052                "      int i;\n"
20053                "};\n",
20054                Style);
20055 }
20056 
20057 TEST_F(FormatTest, LimitlessStringsAndComments) {
20058   auto Style = getLLVMStyleWithColumns(0);
20059   constexpr StringRef Code =
20060       "/**\n"
20061       " * This is a multiline comment with quite some long lines, at least for "
20062       "the LLVM Style.\n"
20063       " * We will redo this with strings and line comments. Just to  check if "
20064       "everything is working.\n"
20065       " */\n"
20066       "bool foo() {\n"
20067       "  /* Single line multi line comment. */\n"
20068       "  const std::string String = \"This is a multiline string with quite "
20069       "some long lines, at least for the LLVM Style.\"\n"
20070       "                             \"We already did it with multi line "
20071       "comments, and we will do it with line comments. Just to check if "
20072       "everything is working.\";\n"
20073       "  // This is a line comment (block) with quite some long lines, at "
20074       "least for the LLVM Style.\n"
20075       "  // We already did this with multi line comments and strings. Just to "
20076       "check if everything is working.\n"
20077       "  const std::string SmallString = \"Hello World\";\n"
20078       "  // Small line comment\n"
20079       "  return String.size() > SmallString.size();\n"
20080       "}";
20081   EXPECT_EQ(Code, format(Code, Style));
20082 }
20083 } // namespace
20084 } // namespace format
20085 } // namespace clang
20086