1 //===- unittest/Format/FormatTest.cpp - Formatting unit tests -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "clang/Format/Format.h"
10 
11 #include "../Tooling/ReplacementTest.h"
12 #include "FormatTestUtils.h"
13 
14 #include "llvm/Support/Debug.h"
15 #include "llvm/Support/MemoryBuffer.h"
16 #include "gtest/gtest.h"
17 
18 #define DEBUG_TYPE "format-test"
19 
20 using clang::tooling::ReplacementTest;
21 using clang::tooling::toReplacements;
22 using testing::internal::ScopedTrace;
23 
24 namespace clang {
25 namespace format {
26 namespace {
27 
28 FormatStyle getGoogleStyle() { return getGoogleStyle(FormatStyle::LK_Cpp); }
29 
30 class FormatTest : public ::testing::Test {
31 protected:
32   enum StatusCheck { SC_ExpectComplete, SC_ExpectIncomplete, SC_DoNotCheck };
33 
34   std::string format(llvm::StringRef Code,
35                      const FormatStyle &Style = getLLVMStyle(),
36                      StatusCheck CheckComplete = SC_ExpectComplete) {
37     LLVM_DEBUG(llvm::errs() << "---\n");
38     LLVM_DEBUG(llvm::errs() << Code << "\n\n");
39     std::vector<tooling::Range> Ranges(1, tooling::Range(0, Code.size()));
40     FormattingAttemptStatus Status;
41     tooling::Replacements Replaces =
42         reformat(Style, Code, Ranges, "<stdin>", &Status);
43     if (CheckComplete != SC_DoNotCheck) {
44       bool ExpectedCompleteFormat = CheckComplete == SC_ExpectComplete;
45       EXPECT_EQ(ExpectedCompleteFormat, Status.FormatComplete)
46           << Code << "\n\n";
47     }
48     ReplacementCount = Replaces.size();
49     auto Result = applyAllReplacements(Code, Replaces);
50     EXPECT_TRUE(static_cast<bool>(Result));
51     LLVM_DEBUG(llvm::errs() << "\n" << *Result << "\n\n");
52     return *Result;
53   }
54 
55   FormatStyle getStyleWithColumns(FormatStyle Style, unsigned ColumnLimit) {
56     Style.ColumnLimit = ColumnLimit;
57     return Style;
58   }
59 
60   FormatStyle getLLVMStyleWithColumns(unsigned ColumnLimit) {
61     return getStyleWithColumns(getLLVMStyle(), ColumnLimit);
62   }
63 
64   FormatStyle getGoogleStyleWithColumns(unsigned ColumnLimit) {
65     return getStyleWithColumns(getGoogleStyle(), ColumnLimit);
66   }
67 
68   void _verifyFormat(const char *File, int Line, llvm::StringRef Expected,
69                      llvm::StringRef Code,
70                      const FormatStyle &Style = getLLVMStyle()) {
71     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
72     EXPECT_EQ(Expected.str(), format(Expected, Style))
73         << "Expected code is not stable";
74     EXPECT_EQ(Expected.str(), format(Code, Style));
75     if (Style.Language == FormatStyle::LK_Cpp) {
76       // Objective-C++ is a superset of C++, so everything checked for C++
77       // needs to be checked for Objective-C++ as well.
78       FormatStyle ObjCStyle = Style;
79       ObjCStyle.Language = FormatStyle::LK_ObjC;
80       EXPECT_EQ(Expected.str(), format(test::messUp(Code), ObjCStyle));
81     }
82   }
83 
84   void _verifyFormat(const char *File, int Line, llvm::StringRef Code,
85                      const FormatStyle &Style = getLLVMStyle()) {
86     _verifyFormat(File, Line, Code, test::messUp(Code), Style);
87   }
88 
89   void _verifyIncompleteFormat(const char *File, int Line, llvm::StringRef Code,
90                                const FormatStyle &Style = getLLVMStyle()) {
91     ScopedTrace t(File, Line, ::testing::Message() << Code.str());
92     EXPECT_EQ(Code.str(),
93               format(test::messUp(Code), Style, SC_ExpectIncomplete));
94   }
95 
96   void _verifyIndependentOfContext(const char *File, int Line,
97                                    llvm::StringRef Text,
98                                    const FormatStyle &Style = getLLVMStyle()) {
99     _verifyFormat(File, Line, Text, Style);
100     _verifyFormat(File, Line, llvm::Twine("void f() { " + Text + " }").str(),
101                   Style);
102   }
103 
104   /// \brief Verify that clang-format does not crash on the given input.
105   void verifyNoCrash(llvm::StringRef Code,
106                      const FormatStyle &Style = getLLVMStyle()) {
107     format(Code, Style, SC_DoNotCheck);
108   }
109 
110   int ReplacementCount;
111 };
112 
113 #define verifyIndependentOfContext(...)                                        \
114   _verifyIndependentOfContext(__FILE__, __LINE__, __VA_ARGS__)
115 #define verifyIncompleteFormat(...)                                            \
116   _verifyIncompleteFormat(__FILE__, __LINE__, __VA_ARGS__)
117 #define verifyFormat(...) _verifyFormat(__FILE__, __LINE__, __VA_ARGS__)
118 #define verifyGoogleFormat(Code) verifyFormat(Code, getGoogleStyle())
119 
120 TEST_F(FormatTest, MessUp) {
121   EXPECT_EQ("1 2 3", test::messUp("1 2 3"));
122   EXPECT_EQ("1 2 3\n", test::messUp("1\n2\n3\n"));
123   EXPECT_EQ("a\n//b\nc", test::messUp("a\n//b\nc"));
124   EXPECT_EQ("a\n#b\nc", test::messUp("a\n#b\nc"));
125   EXPECT_EQ("a\n#b c d\ne", test::messUp("a\n#b\\\nc\\\nd\ne"));
126 }
127 
128 TEST_F(FormatTest, DefaultLLVMStyleIsCpp) {
129   EXPECT_EQ(FormatStyle::LK_Cpp, getLLVMStyle().Language);
130 }
131 
132 TEST_F(FormatTest, LLVMStyleOverride) {
133   EXPECT_EQ(FormatStyle::LK_Proto,
134             getLLVMStyle(FormatStyle::LK_Proto).Language);
135 }
136 
137 //===----------------------------------------------------------------------===//
138 // Basic function tests.
139 //===----------------------------------------------------------------------===//
140 
141 TEST_F(FormatTest, DoesNotChangeCorrectlyFormattedCode) {
142   EXPECT_EQ(";", format(";"));
143 }
144 
145 TEST_F(FormatTest, FormatsGlobalStatementsAt0) {
146   EXPECT_EQ("int i;", format("  int i;"));
147   EXPECT_EQ("\nint i;", format(" \n\t \v \f  int i;"));
148   EXPECT_EQ("int i;\nint j;", format("    int i; int j;"));
149   EXPECT_EQ("int i;\nint j;", format("    int i;\n  int j;"));
150 }
151 
152 TEST_F(FormatTest, FormatsUnwrappedLinesAtFirstFormat) {
153   EXPECT_EQ("int i;", format("int\ni;"));
154 }
155 
156 TEST_F(FormatTest, FormatsNestedBlockStatements) {
157   EXPECT_EQ("{\n  {\n    {}\n  }\n}", format("{{{}}}"));
158 }
159 
160 TEST_F(FormatTest, FormatsNestedCall) {
161   verifyFormat("Method(f1, f2(f3));");
162   verifyFormat("Method(f1(f2, f3()));");
163   verifyFormat("Method(f1(f2, (f3())));");
164 }
165 
166 TEST_F(FormatTest, NestedNameSpecifiers) {
167   verifyFormat("vector<::Type> v;");
168   verifyFormat("::ns::SomeFunction(::ns::SomeOtherFunction())");
169   verifyFormat("static constexpr bool Bar = decltype(bar())::value;");
170   verifyFormat("static constexpr bool Bar = typeof(bar())::value;");
171   verifyFormat("static constexpr bool Bar = __underlying_type(bar())::value;");
172   verifyFormat("static constexpr bool Bar = _Atomic(bar())::value;");
173   verifyFormat("bool a = 2 < ::SomeFunction();");
174   verifyFormat("ALWAYS_INLINE ::std::string getName();");
175   verifyFormat("some::string getName();");
176 }
177 
178 TEST_F(FormatTest, OnlyGeneratesNecessaryReplacements) {
179   EXPECT_EQ("if (a) {\n"
180             "  f();\n"
181             "}",
182             format("if(a){f();}"));
183   EXPECT_EQ(4, ReplacementCount);
184   EXPECT_EQ("if (a) {\n"
185             "  f();\n"
186             "}",
187             format("if (a) {\n"
188                    "  f();\n"
189                    "}"));
190   EXPECT_EQ(0, ReplacementCount);
191   EXPECT_EQ("/*\r\n"
192             "\r\n"
193             "*/\r\n",
194             format("/*\r\n"
195                    "\r\n"
196                    "*/\r\n"));
197   EXPECT_EQ(0, ReplacementCount);
198 }
199 
200 TEST_F(FormatTest, RemovesEmptyLines) {
201   EXPECT_EQ("class C {\n"
202             "  int i;\n"
203             "};",
204             format("class C {\n"
205                    " int i;\n"
206                    "\n"
207                    "};"));
208 
209   // Don't remove empty lines at the start of namespaces or extern "C" blocks.
210   EXPECT_EQ("namespace N {\n"
211             "\n"
212             "int i;\n"
213             "}",
214             format("namespace N {\n"
215                    "\n"
216                    "int    i;\n"
217                    "}",
218                    getGoogleStyle()));
219   EXPECT_EQ("/* something */ namespace N {\n"
220             "\n"
221             "int i;\n"
222             "}",
223             format("/* something */ namespace N {\n"
224                    "\n"
225                    "int    i;\n"
226                    "}",
227                    getGoogleStyle()));
228   EXPECT_EQ("inline namespace N {\n"
229             "\n"
230             "int i;\n"
231             "}",
232             format("inline namespace N {\n"
233                    "\n"
234                    "int    i;\n"
235                    "}",
236                    getGoogleStyle()));
237   EXPECT_EQ("/* something */ inline namespace N {\n"
238             "\n"
239             "int i;\n"
240             "}",
241             format("/* something */ inline namespace N {\n"
242                    "\n"
243                    "int    i;\n"
244                    "}",
245                    getGoogleStyle()));
246   EXPECT_EQ("export namespace N {\n"
247             "\n"
248             "int i;\n"
249             "}",
250             format("export namespace N {\n"
251                    "\n"
252                    "int    i;\n"
253                    "}",
254                    getGoogleStyle()));
255   EXPECT_EQ("extern /**/ \"C\" /**/ {\n"
256             "\n"
257             "int i;\n"
258             "}",
259             format("extern /**/ \"C\" /**/ {\n"
260                    "\n"
261                    "int    i;\n"
262                    "}",
263                    getGoogleStyle()));
264 
265   // ...but do keep inlining and removing empty lines for non-block extern "C"
266   // functions.
267   verifyFormat("extern \"C\" int f() { return 42; }", getGoogleStyle());
268   EXPECT_EQ("extern \"C\" int f() {\n"
269             "  int i = 42;\n"
270             "  return i;\n"
271             "}",
272             format("extern \"C\" int f() {\n"
273                    "\n"
274                    "  int i = 42;\n"
275                    "  return i;\n"
276                    "}",
277                    getGoogleStyle()));
278 
279   // Remove empty lines at the beginning and end of blocks.
280   EXPECT_EQ("void f() {\n"
281             "\n"
282             "  if (a) {\n"
283             "\n"
284             "    f();\n"
285             "  }\n"
286             "}",
287             format("void f() {\n"
288                    "\n"
289                    "  if (a) {\n"
290                    "\n"
291                    "    f();\n"
292                    "\n"
293                    "  }\n"
294                    "\n"
295                    "}",
296                    getLLVMStyle()));
297   EXPECT_EQ("void f() {\n"
298             "  if (a) {\n"
299             "    f();\n"
300             "  }\n"
301             "}",
302             format("void f() {\n"
303                    "\n"
304                    "  if (a) {\n"
305                    "\n"
306                    "    f();\n"
307                    "\n"
308                    "  }\n"
309                    "\n"
310                    "}",
311                    getGoogleStyle()));
312 
313   // Don't remove empty lines in more complex control statements.
314   EXPECT_EQ("void f() {\n"
315             "  if (a) {\n"
316             "    f();\n"
317             "\n"
318             "  } else if (b) {\n"
319             "    f();\n"
320             "  }\n"
321             "}",
322             format("void f() {\n"
323                    "  if (a) {\n"
324                    "    f();\n"
325                    "\n"
326                    "  } else if (b) {\n"
327                    "    f();\n"
328                    "\n"
329                    "  }\n"
330                    "\n"
331                    "}"));
332 
333   // Don't remove empty lines before namespace endings.
334   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
335   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
336   EXPECT_EQ("namespace {\n"
337             "int i;\n"
338             "\n"
339             "}",
340             format("namespace {\n"
341                    "int i;\n"
342                    "\n"
343                    "}",
344                    LLVMWithNoNamespaceFix));
345   EXPECT_EQ("namespace {\n"
346             "int i;\n"
347             "}",
348             format("namespace {\n"
349                    "int i;\n"
350                    "}",
351                    LLVMWithNoNamespaceFix));
352   EXPECT_EQ("namespace {\n"
353             "int i;\n"
354             "\n"
355             "};",
356             format("namespace {\n"
357                    "int i;\n"
358                    "\n"
359                    "};",
360                    LLVMWithNoNamespaceFix));
361   EXPECT_EQ("namespace {\n"
362             "int i;\n"
363             "};",
364             format("namespace {\n"
365                    "int i;\n"
366                    "};",
367                    LLVMWithNoNamespaceFix));
368   EXPECT_EQ("namespace {\n"
369             "int i;\n"
370             "\n"
371             "}",
372             format("namespace {\n"
373                    "int i;\n"
374                    "\n"
375                    "}"));
376   EXPECT_EQ("namespace {\n"
377             "int i;\n"
378             "\n"
379             "} // namespace",
380             format("namespace {\n"
381                    "int i;\n"
382                    "\n"
383                    "}  // namespace"));
384 
385   FormatStyle Style = getLLVMStyle();
386   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
387   Style.MaxEmptyLinesToKeep = 2;
388   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
389   Style.BraceWrapping.AfterClass = true;
390   Style.BraceWrapping.AfterFunction = true;
391   Style.KeepEmptyLinesAtTheStartOfBlocks = false;
392 
393   EXPECT_EQ("class Foo\n"
394             "{\n"
395             "  Foo() {}\n"
396             "\n"
397             "  void funk() {}\n"
398             "};",
399             format("class Foo\n"
400                    "{\n"
401                    "  Foo()\n"
402                    "  {\n"
403                    "  }\n"
404                    "\n"
405                    "  void funk() {}\n"
406                    "};",
407                    Style));
408 }
409 
410 TEST_F(FormatTest, RecognizesBinaryOperatorKeywords) {
411   verifyFormat("x = (a) and (b);");
412   verifyFormat("x = (a) or (b);");
413   verifyFormat("x = (a) bitand (b);");
414   verifyFormat("x = (a) bitor (b);");
415   verifyFormat("x = (a) not_eq (b);");
416   verifyFormat("x = (a) and_eq (b);");
417   verifyFormat("x = (a) or_eq (b);");
418   verifyFormat("x = (a) xor (b);");
419 }
420 
421 TEST_F(FormatTest, RecognizesUnaryOperatorKeywords) {
422   verifyFormat("x = compl(a);");
423   verifyFormat("x = not(a);");
424   verifyFormat("x = bitand(a);");
425   // Unary operator must not be merged with the next identifier
426   verifyFormat("x = compl a;");
427   verifyFormat("x = not a;");
428   verifyFormat("x = bitand a;");
429 }
430 
431 //===----------------------------------------------------------------------===//
432 // Tests for control statements.
433 //===----------------------------------------------------------------------===//
434 
435 TEST_F(FormatTest, FormatIfWithoutCompoundStatement) {
436   verifyFormat("if (true)\n  f();\ng();");
437   verifyFormat("if (a)\n  if (b)\n    if (c)\n      g();\nh();");
438   verifyFormat("if (a)\n  if (b) {\n    f();\n  }\ng();");
439   verifyFormat("if constexpr (true)\n"
440                "  f();\ng();");
441   verifyFormat("if CONSTEXPR (true)\n"
442                "  f();\ng();");
443   verifyFormat("if constexpr (a)\n"
444                "  if constexpr (b)\n"
445                "    if constexpr (c)\n"
446                "      g();\n"
447                "h();");
448   verifyFormat("if CONSTEXPR (a)\n"
449                "  if CONSTEXPR (b)\n"
450                "    if CONSTEXPR (c)\n"
451                "      g();\n"
452                "h();");
453   verifyFormat("if constexpr (a)\n"
454                "  if constexpr (b) {\n"
455                "    f();\n"
456                "  }\n"
457                "g();");
458   verifyFormat("if CONSTEXPR (a)\n"
459                "  if CONSTEXPR (b) {\n"
460                "    f();\n"
461                "  }\n"
462                "g();");
463 
464   FormatStyle AllowsMergedIf = getLLVMStyle();
465   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
466   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
467       FormatStyle::SIS_WithoutElse;
468   verifyFormat("if (a)\n"
469                "  // comment\n"
470                "  f();",
471                AllowsMergedIf);
472   verifyFormat("{\n"
473                "  if (a)\n"
474                "  label:\n"
475                "    f();\n"
476                "}",
477                AllowsMergedIf);
478   verifyFormat("#define A \\\n"
479                "  if (a)  \\\n"
480                "  label:  \\\n"
481                "    f()",
482                AllowsMergedIf);
483   verifyFormat("if (a)\n"
484                "  ;",
485                AllowsMergedIf);
486   verifyFormat("if (a)\n"
487                "  if (b) return;",
488                AllowsMergedIf);
489 
490   verifyFormat("if (a) // Can't merge this\n"
491                "  f();\n",
492                AllowsMergedIf);
493   verifyFormat("if (a) /* still don't merge */\n"
494                "  f();",
495                AllowsMergedIf);
496   verifyFormat("if (a) { // Never merge this\n"
497                "  f();\n"
498                "}",
499                AllowsMergedIf);
500   verifyFormat("if (a) { /* Never merge this */\n"
501                "  f();\n"
502                "}",
503                AllowsMergedIf);
504 
505   AllowsMergedIf.ColumnLimit = 14;
506   verifyFormat("if (a) return;", AllowsMergedIf);
507   verifyFormat("if (aaaaaaaaa)\n"
508                "  return;",
509                AllowsMergedIf);
510 
511   AllowsMergedIf.ColumnLimit = 13;
512   verifyFormat("if (a)\n  return;", AllowsMergedIf);
513 }
514 
515 TEST_F(FormatTest, FormatIfWithoutCompoundStatementButElseWith) {
516   FormatStyle AllowsMergedIf = getLLVMStyle();
517   AllowsMergedIf.AlignEscapedNewlines = FormatStyle::ENAS_Left;
518   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
519       FormatStyle::SIS_WithoutElse;
520   verifyFormat("if (a)\n"
521                "  f();\n"
522                "else {\n"
523                "  g();\n"
524                "}",
525                AllowsMergedIf);
526   verifyFormat("if (a)\n"
527                "  f();\n"
528                "else\n"
529                "  g();\n",
530                AllowsMergedIf);
531 
532   AllowsMergedIf.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
533 
534   verifyFormat("if (a) f();\n"
535                "else {\n"
536                "  g();\n"
537                "}",
538                AllowsMergedIf);
539   verifyFormat("if (a) f();\n"
540                "else {\n"
541                "  if (a) f();\n"
542                "  else {\n"
543                "    g();\n"
544                "  }\n"
545                "  g();\n"
546                "}",
547                AllowsMergedIf);
548 }
549 
550 TEST_F(FormatTest, FormatLoopsWithoutCompoundStatement) {
551   FormatStyle AllowsMergedLoops = getLLVMStyle();
552   AllowsMergedLoops.AllowShortLoopsOnASingleLine = true;
553   verifyFormat("while (true) continue;", AllowsMergedLoops);
554   verifyFormat("for (;;) continue;", AllowsMergedLoops);
555   verifyFormat("for (int &v : vec) v *= 2;", AllowsMergedLoops);
556   verifyFormat("while (true)\n"
557                "  ;",
558                AllowsMergedLoops);
559   verifyFormat("for (;;)\n"
560                "  ;",
561                AllowsMergedLoops);
562   verifyFormat("for (;;)\n"
563                "  for (;;) continue;",
564                AllowsMergedLoops);
565   verifyFormat("for (;;) // Can't merge this\n"
566                "  continue;",
567                AllowsMergedLoops);
568   verifyFormat("for (;;) /* still don't merge */\n"
569                "  continue;",
570                AllowsMergedLoops);
571   verifyFormat("do a++;\n"
572                "while (true);",
573                AllowsMergedLoops);
574   verifyFormat("do /* Don't merge */\n"
575                "  a++;\n"
576                "while (true);",
577                AllowsMergedLoops);
578   verifyFormat("do // Don't merge\n"
579                "  a++;\n"
580                "while (true);",
581                AllowsMergedLoops);
582   verifyFormat("do\n"
583                "  // Don't merge\n"
584                "  a++;\n"
585                "while (true);",
586                AllowsMergedLoops);
587   // Without braces labels are interpreted differently.
588   verifyFormat("{\n"
589                "  do\n"
590                "  label:\n"
591                "    a++;\n"
592                "  while (true);\n"
593                "}",
594                AllowsMergedLoops);
595 }
596 
597 TEST_F(FormatTest, FormatShortBracedStatements) {
598   FormatStyle AllowSimpleBracedStatements = getLLVMStyle();
599   AllowSimpleBracedStatements.ColumnLimit = 40;
600   AllowSimpleBracedStatements.AllowShortBlocksOnASingleLine =
601       FormatStyle::SBS_Always;
602 
603   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
604       FormatStyle::SIS_WithoutElse;
605   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
606 
607   AllowSimpleBracedStatements.BreakBeforeBraces = FormatStyle::BS_Custom;
608   AllowSimpleBracedStatements.BraceWrapping.AfterFunction = true;
609   AllowSimpleBracedStatements.BraceWrapping.SplitEmptyRecord = false;
610 
611   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
612   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
613   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
614   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
615   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
616   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
617   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
618   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
619   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
620   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
621   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
622                AllowSimpleBracedStatements);
623   verifyFormat("if (true) {\n"
624                "  ffffffffffffffffffffffff();\n"
625                "}",
626                AllowSimpleBracedStatements);
627   verifyFormat("if (true) {\n"
628                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
629                "}",
630                AllowSimpleBracedStatements);
631   verifyFormat("if (true) { //\n"
632                "  f();\n"
633                "}",
634                AllowSimpleBracedStatements);
635   verifyFormat("if (true) {\n"
636                "  f();\n"
637                "  f();\n"
638                "}",
639                AllowSimpleBracedStatements);
640   verifyFormat("if (true) {\n"
641                "  f();\n"
642                "} else {\n"
643                "  f();\n"
644                "}",
645                AllowSimpleBracedStatements);
646 
647   verifyFormat("struct A2 {\n"
648                "  int X;\n"
649                "};",
650                AllowSimpleBracedStatements);
651   verifyFormat("typedef struct A2 {\n"
652                "  int X;\n"
653                "} A2_t;",
654                AllowSimpleBracedStatements);
655   verifyFormat("template <int> struct A2 {\n"
656                "  struct B {};\n"
657                "};",
658                AllowSimpleBracedStatements);
659 
660   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
661       FormatStyle::SIS_Never;
662   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
663   verifyFormat("if (true) {\n"
664                "  f();\n"
665                "}",
666                AllowSimpleBracedStatements);
667   verifyFormat("if (true) {\n"
668                "  f();\n"
669                "} else {\n"
670                "  f();\n"
671                "}",
672                AllowSimpleBracedStatements);
673 
674   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
675   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
676   verifyFormat("while (true) {\n"
677                "  f();\n"
678                "}",
679                AllowSimpleBracedStatements);
680   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
681   verifyFormat("for (;;) {\n"
682                "  f();\n"
683                "}",
684                AllowSimpleBracedStatements);
685 
686   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
687       FormatStyle::SIS_WithoutElse;
688   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = true;
689   AllowSimpleBracedStatements.BraceWrapping.AfterControlStatement =
690       FormatStyle::BWACS_Always;
691 
692   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
693   verifyFormat("if constexpr (true) {}", AllowSimpleBracedStatements);
694   verifyFormat("if CONSTEXPR (true) {}", AllowSimpleBracedStatements);
695   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
696   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
697   verifyFormat("if (true) { f(); }", AllowSimpleBracedStatements);
698   verifyFormat("if constexpr (true) { f(); }", AllowSimpleBracedStatements);
699   verifyFormat("if CONSTEXPR (true) { f(); }", AllowSimpleBracedStatements);
700   verifyFormat("while (true) { f(); }", AllowSimpleBracedStatements);
701   verifyFormat("for (;;) { f(); }", AllowSimpleBracedStatements);
702   verifyFormat("if (true) { fffffffffffffffffffffff(); }",
703                AllowSimpleBracedStatements);
704   verifyFormat("if (true)\n"
705                "{\n"
706                "  ffffffffffffffffffffffff();\n"
707                "}",
708                AllowSimpleBracedStatements);
709   verifyFormat("if (true)\n"
710                "{\n"
711                "  ffffffffffffffffffffffffffffffffffffffffffffffffffffff();\n"
712                "}",
713                AllowSimpleBracedStatements);
714   verifyFormat("if (true)\n"
715                "{ //\n"
716                "  f();\n"
717                "}",
718                AllowSimpleBracedStatements);
719   verifyFormat("if (true)\n"
720                "{\n"
721                "  f();\n"
722                "  f();\n"
723                "}",
724                AllowSimpleBracedStatements);
725   verifyFormat("if (true)\n"
726                "{\n"
727                "  f();\n"
728                "} else\n"
729                "{\n"
730                "  f();\n"
731                "}",
732                AllowSimpleBracedStatements);
733 
734   AllowSimpleBracedStatements.AllowShortIfStatementsOnASingleLine =
735       FormatStyle::SIS_Never;
736   verifyFormat("if (true) {}", AllowSimpleBracedStatements);
737   verifyFormat("if (true)\n"
738                "{\n"
739                "  f();\n"
740                "}",
741                AllowSimpleBracedStatements);
742   verifyFormat("if (true)\n"
743                "{\n"
744                "  f();\n"
745                "} else\n"
746                "{\n"
747                "  f();\n"
748                "}",
749                AllowSimpleBracedStatements);
750 
751   AllowSimpleBracedStatements.AllowShortLoopsOnASingleLine = false;
752   verifyFormat("while (true) {}", AllowSimpleBracedStatements);
753   verifyFormat("while (true)\n"
754                "{\n"
755                "  f();\n"
756                "}",
757                AllowSimpleBracedStatements);
758   verifyFormat("for (;;) {}", AllowSimpleBracedStatements);
759   verifyFormat("for (;;)\n"
760                "{\n"
761                "  f();\n"
762                "}",
763                AllowSimpleBracedStatements);
764 }
765 
766 TEST_F(FormatTest, ShortBlocksInMacrosDontMergeWithCodeAfterMacro) {
767   FormatStyle Style = getLLVMStyleWithColumns(60);
768   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
769   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
770   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
771   EXPECT_EQ("#define A                                                  \\\n"
772             "  if (HANDLEwernufrnuLwrmviferuvnierv)                     \\\n"
773             "  {                                                        \\\n"
774             "    RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier;               \\\n"
775             "  }\n"
776             "X;",
777             format("#define A \\\n"
778                    "   if (HANDLEwernufrnuLwrmviferuvnierv) { \\\n"
779                    "      RET_ERR1_ANUIREUINERUIFNIOAerwfwrvnuier; \\\n"
780                    "   }\n"
781                    "X;",
782                    Style));
783 }
784 
785 TEST_F(FormatTest, ParseIfElse) {
786   verifyFormat("if (true)\n"
787                "  if (true)\n"
788                "    if (true)\n"
789                "      f();\n"
790                "    else\n"
791                "      g();\n"
792                "  else\n"
793                "    h();\n"
794                "else\n"
795                "  i();");
796   verifyFormat("if (true)\n"
797                "  if (true)\n"
798                "    if (true) {\n"
799                "      if (true)\n"
800                "        f();\n"
801                "    } else {\n"
802                "      g();\n"
803                "    }\n"
804                "  else\n"
805                "    h();\n"
806                "else {\n"
807                "  i();\n"
808                "}");
809   verifyFormat("if (true)\n"
810                "  if constexpr (true)\n"
811                "    if (true) {\n"
812                "      if constexpr (true)\n"
813                "        f();\n"
814                "    } else {\n"
815                "      g();\n"
816                "    }\n"
817                "  else\n"
818                "    h();\n"
819                "else {\n"
820                "  i();\n"
821                "}");
822   verifyFormat("if (true)\n"
823                "  if CONSTEXPR (true)\n"
824                "    if (true) {\n"
825                "      if CONSTEXPR (true)\n"
826                "        f();\n"
827                "    } else {\n"
828                "      g();\n"
829                "    }\n"
830                "  else\n"
831                "    h();\n"
832                "else {\n"
833                "  i();\n"
834                "}");
835   verifyFormat("void f() {\n"
836                "  if (a) {\n"
837                "  } else {\n"
838                "  }\n"
839                "}");
840 }
841 
842 TEST_F(FormatTest, ElseIf) {
843   verifyFormat("if (a) {\n} else if (b) {\n}");
844   verifyFormat("if (a)\n"
845                "  f();\n"
846                "else if (b)\n"
847                "  g();\n"
848                "else\n"
849                "  h();");
850   verifyFormat("if constexpr (a)\n"
851                "  f();\n"
852                "else if constexpr (b)\n"
853                "  g();\n"
854                "else\n"
855                "  h();");
856   verifyFormat("if CONSTEXPR (a)\n"
857                "  f();\n"
858                "else if CONSTEXPR (b)\n"
859                "  g();\n"
860                "else\n"
861                "  h();");
862   verifyFormat("if (a) {\n"
863                "  f();\n"
864                "}\n"
865                "// or else ..\n"
866                "else {\n"
867                "  g()\n"
868                "}");
869 
870   verifyFormat("if (a) {\n"
871                "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
872                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
873                "}");
874   verifyFormat("if (a) {\n"
875                "} else if constexpr (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
876                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
877                "}");
878   verifyFormat("if (a) {\n"
879                "} else if CONSTEXPR (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
880                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
881                "}");
882   verifyFormat("if (a) {\n"
883                "} else if (\n"
884                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
885                "}",
886                getLLVMStyleWithColumns(62));
887   verifyFormat("if (a) {\n"
888                "} else if constexpr (\n"
889                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
890                "}",
891                getLLVMStyleWithColumns(62));
892   verifyFormat("if (a) {\n"
893                "} else if CONSTEXPR (\n"
894                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
895                "}",
896                getLLVMStyleWithColumns(62));
897 }
898 
899 TEST_F(FormatTest, FormatsForLoop) {
900   verifyFormat(
901       "for (int VeryVeryLongLoopVariable = 0; VeryVeryLongLoopVariable < 10;\n"
902       "     ++VeryVeryLongLoopVariable)\n"
903       "  ;");
904   verifyFormat("for (;;)\n"
905                "  f();");
906   verifyFormat("for (;;) {\n}");
907   verifyFormat("for (;;) {\n"
908                "  f();\n"
909                "}");
910   verifyFormat("for (int i = 0; (i < 10); ++i) {\n}");
911 
912   verifyFormat(
913       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
914       "                                          E = UnwrappedLines.end();\n"
915       "     I != E; ++I) {\n}");
916 
917   verifyFormat(
918       "for (MachineFun::iterator IIII = PrevIt, EEEE = F.end(); IIII != EEEE;\n"
919       "     ++IIIII) {\n}");
920   verifyFormat("for (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaa =\n"
921                "         aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa;\n"
922                "     aaaaaaaaaaa != aaaaaaaaaaaaaaaaaaa; ++aaaaaaaaaaa) {\n}");
923   verifyFormat("for (llvm::ArrayRef<NamedDecl *>::iterator\n"
924                "         I = FD->getDeclsInPrototypeScope().begin(),\n"
925                "         E = FD->getDeclsInPrototypeScope().end();\n"
926                "     I != E; ++I) {\n}");
927   verifyFormat("for (SmallVectorImpl<TemplateIdAnnotationn *>::iterator\n"
928                "         I = Container.begin(),\n"
929                "         E = Container.end();\n"
930                "     I != E; ++I) {\n}",
931                getLLVMStyleWithColumns(76));
932 
933   verifyFormat(
934       "for (aaaaaaaaaaaaaaaaa aaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
935       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa !=\n"
936       "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
937       "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
938       "     ++aaaaaaaaaaa) {\n}");
939   verifyFormat("for (int i = 0; i < aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
940                "                bbbbbbbbbbbbbbbbbbbb < ccccccccccccccc;\n"
941                "     ++i) {\n}");
942   verifyFormat("for (int aaaaaaaaaaa = 1; aaaaaaaaaaa <= bbbbbbbbbbbbbbb;\n"
943                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
944                "}");
945   verifyFormat("for (some_namespace::SomeIterator iter( // force break\n"
946                "         aaaaaaaaaa);\n"
947                "     iter; ++iter) {\n"
948                "}");
949   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
950                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
951                "     aaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbbbbbbb;\n"
952                "     ++aaaaaaaaaaaaaaaaaaaaaaaaaaa) {");
953 
954   // These should not be formatted as Objective-C for-in loops.
955   verifyFormat("for (Foo *x = 0; x != in; x++) {\n}");
956   verifyFormat("Foo *x;\nfor (x = 0; x != in; x++) {\n}");
957   verifyFormat("Foo *x;\nfor (x in y) {\n}");
958   verifyFormat(
959       "for (const Foo<Bar> &baz = in.value(); !baz.at_end(); ++baz) {\n}");
960 
961   FormatStyle NoBinPacking = getLLVMStyle();
962   NoBinPacking.BinPackParameters = false;
963   verifyFormat("for (int aaaaaaaaaaa = 1;\n"
964                "     aaaaaaaaaaa <= aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa,\n"
965                "                                           aaaaaaaaaaaaaaaa,\n"
966                "                                           aaaaaaaaaaaaaaaa,\n"
967                "                                           aaaaaaaaaaaaaaaa);\n"
968                "     aaaaaaaaaaa++, bbbbbbbbbbbbbbbbb++) {\n"
969                "}",
970                NoBinPacking);
971   verifyFormat(
972       "for (std::vector<UnwrappedLine>::iterator I = UnwrappedLines.begin(),\n"
973       "                                          E = UnwrappedLines.end();\n"
974       "     I != E;\n"
975       "     ++I) {\n}",
976       NoBinPacking);
977 
978   FormatStyle AlignLeft = getLLVMStyle();
979   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
980   verifyFormat("for (A* a = start; a < end; ++a, ++value) {\n}", AlignLeft);
981 }
982 
983 TEST_F(FormatTest, RangeBasedForLoops) {
984   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
985                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
986   verifyFormat("for (auto aaaaaaaaaaaaaaaaaaaaa :\n"
987                "     aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa, aaaaaaaaaaaaa)) {\n}");
988   verifyFormat("for (const aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaa :\n"
989                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
990   verifyFormat("for (aaaaaaaaa aaaaaaaaaaaaaaaaaaaaa :\n"
991                "     aaaaaaaaaaaa.aaaaaaaaaaaa().aaaaaaaaa().a()) {\n}");
992 }
993 
994 TEST_F(FormatTest, ForEachLoops) {
995   verifyFormat("void f() {\n"
996                "  foreach (Item *item, itemlist) {}\n"
997                "  Q_FOREACH (Item *item, itemlist) {}\n"
998                "  BOOST_FOREACH (Item *item, itemlist) {}\n"
999                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
1000                "}");
1001 
1002   FormatStyle Style = getLLVMStyle();
1003   Style.SpaceBeforeParens =
1004       FormatStyle::SBPO_ControlStatementsExceptForEachMacros;
1005   verifyFormat("void f() {\n"
1006                "  foreach(Item *item, itemlist) {}\n"
1007                "  Q_FOREACH(Item *item, itemlist) {}\n"
1008                "  BOOST_FOREACH(Item *item, itemlist) {}\n"
1009                "  UNKNOWN_FORACH(Item * item, itemlist) {}\n"
1010                "}",
1011                Style);
1012 
1013   // As function-like macros.
1014   verifyFormat("#define foreach(x, y)\n"
1015                "#define Q_FOREACH(x, y)\n"
1016                "#define BOOST_FOREACH(x, y)\n"
1017                "#define UNKNOWN_FOREACH(x, y)\n");
1018 
1019   // Not as function-like macros.
1020   verifyFormat("#define foreach (x, y)\n"
1021                "#define Q_FOREACH (x, y)\n"
1022                "#define BOOST_FOREACH (x, y)\n"
1023                "#define UNKNOWN_FOREACH (x, y)\n");
1024 
1025   // handle microsoft non standard extension
1026   verifyFormat("for each (char c in x->MyStringProperty)");
1027 }
1028 
1029 TEST_F(FormatTest, FormatsWhileLoop) {
1030   verifyFormat("while (true) {\n}");
1031   verifyFormat("while (true)\n"
1032                "  f();");
1033   verifyFormat("while () {\n}");
1034   verifyFormat("while () {\n"
1035                "  f();\n"
1036                "}");
1037 }
1038 
1039 TEST_F(FormatTest, FormatsDoWhile) {
1040   verifyFormat("do {\n"
1041                "  do_something();\n"
1042                "} while (something());");
1043   verifyFormat("do\n"
1044                "  do_something();\n"
1045                "while (something());");
1046 }
1047 
1048 TEST_F(FormatTest, FormatsSwitchStatement) {
1049   verifyFormat("switch (x) {\n"
1050                "case 1:\n"
1051                "  f();\n"
1052                "  break;\n"
1053                "case kFoo:\n"
1054                "case ns::kBar:\n"
1055                "case kBaz:\n"
1056                "  break;\n"
1057                "default:\n"
1058                "  g();\n"
1059                "  break;\n"
1060                "}");
1061   verifyFormat("switch (x) {\n"
1062                "case 1: {\n"
1063                "  f();\n"
1064                "  break;\n"
1065                "}\n"
1066                "case 2: {\n"
1067                "  break;\n"
1068                "}\n"
1069                "}");
1070   verifyFormat("switch (x) {\n"
1071                "case 1: {\n"
1072                "  f();\n"
1073                "  {\n"
1074                "    g();\n"
1075                "    h();\n"
1076                "  }\n"
1077                "  break;\n"
1078                "}\n"
1079                "}");
1080   verifyFormat("switch (x) {\n"
1081                "case 1: {\n"
1082                "  f();\n"
1083                "  if (foo) {\n"
1084                "    g();\n"
1085                "    h();\n"
1086                "  }\n"
1087                "  break;\n"
1088                "}\n"
1089                "}");
1090   verifyFormat("switch (x) {\n"
1091                "case 1: {\n"
1092                "  f();\n"
1093                "  g();\n"
1094                "} break;\n"
1095                "}");
1096   verifyFormat("switch (test)\n"
1097                "  ;");
1098   verifyFormat("switch (x) {\n"
1099                "default: {\n"
1100                "  // Do nothing.\n"
1101                "}\n"
1102                "}");
1103   verifyFormat("switch (x) {\n"
1104                "// comment\n"
1105                "// if 1, do f()\n"
1106                "case 1:\n"
1107                "  f();\n"
1108                "}");
1109   verifyFormat("switch (x) {\n"
1110                "case 1:\n"
1111                "  // Do amazing stuff\n"
1112                "  {\n"
1113                "    f();\n"
1114                "    g();\n"
1115                "  }\n"
1116                "  break;\n"
1117                "}");
1118   verifyFormat("#define A          \\\n"
1119                "  switch (x) {     \\\n"
1120                "  case a:          \\\n"
1121                "    foo = b;       \\\n"
1122                "  }",
1123                getLLVMStyleWithColumns(20));
1124   verifyFormat("#define OPERATION_CASE(name)           \\\n"
1125                "  case OP_name:                        \\\n"
1126                "    return operations::Operation##name\n",
1127                getLLVMStyleWithColumns(40));
1128   verifyFormat("switch (x) {\n"
1129                "case 1:;\n"
1130                "default:;\n"
1131                "  int i;\n"
1132                "}");
1133 
1134   verifyGoogleFormat("switch (x) {\n"
1135                      "  case 1:\n"
1136                      "    f();\n"
1137                      "    break;\n"
1138                      "  case kFoo:\n"
1139                      "  case ns::kBar:\n"
1140                      "  case kBaz:\n"
1141                      "    break;\n"
1142                      "  default:\n"
1143                      "    g();\n"
1144                      "    break;\n"
1145                      "}");
1146   verifyGoogleFormat("switch (x) {\n"
1147                      "  case 1: {\n"
1148                      "    f();\n"
1149                      "    break;\n"
1150                      "  }\n"
1151                      "}");
1152   verifyGoogleFormat("switch (test)\n"
1153                      "  ;");
1154 
1155   verifyGoogleFormat("#define OPERATION_CASE(name) \\\n"
1156                      "  case OP_name:              \\\n"
1157                      "    return operations::Operation##name\n");
1158   verifyGoogleFormat("Operation codeToOperation(OperationCode OpCode) {\n"
1159                      "  // Get the correction operation class.\n"
1160                      "  switch (OpCode) {\n"
1161                      "    CASE(Add);\n"
1162                      "    CASE(Subtract);\n"
1163                      "    default:\n"
1164                      "      return operations::Unknown;\n"
1165                      "  }\n"
1166                      "#undef OPERATION_CASE\n"
1167                      "}");
1168   verifyFormat("DEBUG({\n"
1169                "  switch (x) {\n"
1170                "  case A:\n"
1171                "    f();\n"
1172                "    break;\n"
1173                "    // fallthrough\n"
1174                "  case B:\n"
1175                "    g();\n"
1176                "    break;\n"
1177                "  }\n"
1178                "});");
1179   EXPECT_EQ("DEBUG({\n"
1180             "  switch (x) {\n"
1181             "  case A:\n"
1182             "    f();\n"
1183             "    break;\n"
1184             "  // On B:\n"
1185             "  case B:\n"
1186             "    g();\n"
1187             "    break;\n"
1188             "  }\n"
1189             "});",
1190             format("DEBUG({\n"
1191                    "  switch (x) {\n"
1192                    "  case A:\n"
1193                    "    f();\n"
1194                    "    break;\n"
1195                    "  // On B:\n"
1196                    "  case B:\n"
1197                    "    g();\n"
1198                    "    break;\n"
1199                    "  }\n"
1200                    "});",
1201                    getLLVMStyle()));
1202   EXPECT_EQ("switch (n) {\n"
1203             "case 0: {\n"
1204             "  return false;\n"
1205             "}\n"
1206             "default: {\n"
1207             "  return true;\n"
1208             "}\n"
1209             "}",
1210             format("switch (n)\n"
1211                    "{\n"
1212                    "case 0: {\n"
1213                    "  return false;\n"
1214                    "}\n"
1215                    "default: {\n"
1216                    "  return true;\n"
1217                    "}\n"
1218                    "}",
1219                    getLLVMStyle()));
1220   verifyFormat("switch (a) {\n"
1221                "case (b):\n"
1222                "  return;\n"
1223                "}");
1224 
1225   verifyFormat("switch (a) {\n"
1226                "case some_namespace::\n"
1227                "    some_constant:\n"
1228                "  return;\n"
1229                "}",
1230                getLLVMStyleWithColumns(34));
1231 
1232   FormatStyle Style = getLLVMStyle();
1233   Style.IndentCaseLabels = true;
1234   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
1235   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1236   Style.BraceWrapping.AfterCaseLabel = true;
1237   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1238   EXPECT_EQ("switch (n)\n"
1239             "{\n"
1240             "  case 0:\n"
1241             "  {\n"
1242             "    return false;\n"
1243             "  }\n"
1244             "  default:\n"
1245             "  {\n"
1246             "    return true;\n"
1247             "  }\n"
1248             "}",
1249             format("switch (n) {\n"
1250                    "  case 0: {\n"
1251                    "    return false;\n"
1252                    "  }\n"
1253                    "  default: {\n"
1254                    "    return true;\n"
1255                    "  }\n"
1256                    "}",
1257                    Style));
1258   Style.BraceWrapping.AfterCaseLabel = false;
1259   EXPECT_EQ("switch (n)\n"
1260             "{\n"
1261             "  case 0: {\n"
1262             "    return false;\n"
1263             "  }\n"
1264             "  default: {\n"
1265             "    return true;\n"
1266             "  }\n"
1267             "}",
1268             format("switch (n) {\n"
1269                    "  case 0:\n"
1270                    "  {\n"
1271                    "    return false;\n"
1272                    "  }\n"
1273                    "  default:\n"
1274                    "  {\n"
1275                    "    return true;\n"
1276                    "  }\n"
1277                    "}",
1278                    Style));
1279   Style.IndentCaseLabels = false;
1280   Style.IndentCaseBlocks = true;
1281   EXPECT_EQ("switch (n)\n"
1282             "{\n"
1283             "case 0:\n"
1284             "  {\n"
1285             "    return false;\n"
1286             "  }\n"
1287             "case 1:\n"
1288             "  break;\n"
1289             "default:\n"
1290             "  {\n"
1291             "    return true;\n"
1292             "  }\n"
1293             "}",
1294             format("switch (n) {\n"
1295                    "case 0: {\n"
1296                    "  return false;\n"
1297                    "}\n"
1298                    "case 1:\n"
1299                    "  break;\n"
1300                    "default: {\n"
1301                    "  return true;\n"
1302                    "}\n"
1303                    "}",
1304                    Style));
1305   Style.IndentCaseLabels = true;
1306   Style.IndentCaseBlocks = true;
1307   EXPECT_EQ("switch (n)\n"
1308             "{\n"
1309             "  case 0:\n"
1310             "    {\n"
1311             "      return false;\n"
1312             "    }\n"
1313             "  case 1:\n"
1314             "    break;\n"
1315             "  default:\n"
1316             "    {\n"
1317             "      return true;\n"
1318             "    }\n"
1319             "}",
1320             format("switch (n) {\n"
1321                    "case 0: {\n"
1322                    "  return false;\n"
1323                    "}\n"
1324                    "case 1:\n"
1325                    "  break;\n"
1326                    "default: {\n"
1327                    "  return true;\n"
1328                    "}\n"
1329                    "}",
1330                    Style));
1331 }
1332 
1333 TEST_F(FormatTest, CaseRanges) {
1334   verifyFormat("switch (x) {\n"
1335                "case 'A' ... 'Z':\n"
1336                "case 1 ... 5:\n"
1337                "case a ... b:\n"
1338                "  break;\n"
1339                "}");
1340 }
1341 
1342 TEST_F(FormatTest, ShortEnums) {
1343   FormatStyle Style = getLLVMStyle();
1344   Style.AllowShortEnumsOnASingleLine = true;
1345   verifyFormat("enum { A, B, C } ShortEnum1, ShortEnum2;", Style);
1346   Style.AllowShortEnumsOnASingleLine = false;
1347   verifyFormat("enum\n"
1348                "{\n"
1349                "  A,\n"
1350                "  B,\n"
1351                "  C\n"
1352                "} ShortEnum1, ShortEnum2;",
1353                Style);
1354 }
1355 
1356 TEST_F(FormatTest, ShortCaseLabels) {
1357   FormatStyle Style = getLLVMStyle();
1358   Style.AllowShortCaseLabelsOnASingleLine = true;
1359   verifyFormat("switch (a) {\n"
1360                "case 1: x = 1; break;\n"
1361                "case 2: return;\n"
1362                "case 3:\n"
1363                "case 4:\n"
1364                "case 5: return;\n"
1365                "case 6: // comment\n"
1366                "  return;\n"
1367                "case 7:\n"
1368                "  // comment\n"
1369                "  return;\n"
1370                "case 8:\n"
1371                "  x = 8; // comment\n"
1372                "  break;\n"
1373                "default: y = 1; break;\n"
1374                "}",
1375                Style);
1376   verifyFormat("switch (a) {\n"
1377                "case 0: return; // comment\n"
1378                "case 1: break;  // comment\n"
1379                "case 2: return;\n"
1380                "// comment\n"
1381                "case 3: return;\n"
1382                "// comment 1\n"
1383                "// comment 2\n"
1384                "// comment 3\n"
1385                "case 4: break; /* comment */\n"
1386                "case 5:\n"
1387                "  // comment\n"
1388                "  break;\n"
1389                "case 6: /* comment */ x = 1; break;\n"
1390                "case 7: x = /* comment */ 1; break;\n"
1391                "case 8:\n"
1392                "  x = 1; /* comment */\n"
1393                "  break;\n"
1394                "case 9:\n"
1395                "  break; // comment line 1\n"
1396                "         // comment line 2\n"
1397                "}",
1398                Style);
1399   EXPECT_EQ("switch (a) {\n"
1400             "case 1:\n"
1401             "  x = 8;\n"
1402             "  // fall through\n"
1403             "case 2: x = 8;\n"
1404             "// comment\n"
1405             "case 3:\n"
1406             "  return; /* comment line 1\n"
1407             "           * comment line 2 */\n"
1408             "case 4: i = 8;\n"
1409             "// something else\n"
1410             "#if FOO\n"
1411             "case 5: break;\n"
1412             "#endif\n"
1413             "}",
1414             format("switch (a) {\n"
1415                    "case 1: x = 8;\n"
1416                    "  // fall through\n"
1417                    "case 2:\n"
1418                    "  x = 8;\n"
1419                    "// comment\n"
1420                    "case 3:\n"
1421                    "  return; /* comment line 1\n"
1422                    "           * comment line 2 */\n"
1423                    "case 4:\n"
1424                    "  i = 8;\n"
1425                    "// something else\n"
1426                    "#if FOO\n"
1427                    "case 5: break;\n"
1428                    "#endif\n"
1429                    "}",
1430                    Style));
1431   EXPECT_EQ("switch (a) {\n"
1432             "case 0:\n"
1433             "  return; // long long long long long long long long long long "
1434             "long long comment\n"
1435             "          // line\n"
1436             "}",
1437             format("switch (a) {\n"
1438                    "case 0: return; // long long long long long long long long "
1439                    "long long long long comment line\n"
1440                    "}",
1441                    Style));
1442   EXPECT_EQ("switch (a) {\n"
1443             "case 0:\n"
1444             "  return; /* long long long long long long long long long long "
1445             "long long comment\n"
1446             "             line */\n"
1447             "}",
1448             format("switch (a) {\n"
1449                    "case 0: return; /* long long long long long long long long "
1450                    "long long long long comment line */\n"
1451                    "}",
1452                    Style));
1453   verifyFormat("switch (a) {\n"
1454                "#if FOO\n"
1455                "case 0: return 0;\n"
1456                "#endif\n"
1457                "}",
1458                Style);
1459   verifyFormat("switch (a) {\n"
1460                "case 1: {\n"
1461                "}\n"
1462                "case 2: {\n"
1463                "  return;\n"
1464                "}\n"
1465                "case 3: {\n"
1466                "  x = 1;\n"
1467                "  return;\n"
1468                "}\n"
1469                "case 4:\n"
1470                "  if (x)\n"
1471                "    return;\n"
1472                "}",
1473                Style);
1474   Style.ColumnLimit = 21;
1475   verifyFormat("switch (a) {\n"
1476                "case 1: x = 1; break;\n"
1477                "case 2: return;\n"
1478                "case 3:\n"
1479                "case 4:\n"
1480                "case 5: return;\n"
1481                "default:\n"
1482                "  y = 1;\n"
1483                "  break;\n"
1484                "}",
1485                Style);
1486   Style.ColumnLimit = 80;
1487   Style.AllowShortCaseLabelsOnASingleLine = false;
1488   Style.IndentCaseLabels = true;
1489   EXPECT_EQ("switch (n) {\n"
1490             "  default /*comments*/:\n"
1491             "    return true;\n"
1492             "  case 0:\n"
1493             "    return false;\n"
1494             "}",
1495             format("switch (n) {\n"
1496                    "default/*comments*/:\n"
1497                    "  return true;\n"
1498                    "case 0:\n"
1499                    "  return false;\n"
1500                    "}",
1501                    Style));
1502   Style.AllowShortCaseLabelsOnASingleLine = true;
1503   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
1504   Style.BraceWrapping.AfterCaseLabel = true;
1505   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
1506   EXPECT_EQ("switch (n)\n"
1507             "{\n"
1508             "  case 0:\n"
1509             "  {\n"
1510             "    return false;\n"
1511             "  }\n"
1512             "  default:\n"
1513             "  {\n"
1514             "    return true;\n"
1515             "  }\n"
1516             "}",
1517             format("switch (n) {\n"
1518                    "  case 0: {\n"
1519                    "    return false;\n"
1520                    "  }\n"
1521                    "  default:\n"
1522                    "  {\n"
1523                    "    return true;\n"
1524                    "  }\n"
1525                    "}",
1526                    Style));
1527 }
1528 
1529 TEST_F(FormatTest, FormatsLabels) {
1530   verifyFormat("void f() {\n"
1531                "  some_code();\n"
1532                "test_label:\n"
1533                "  some_other_code();\n"
1534                "  {\n"
1535                "    some_more_code();\n"
1536                "  another_label:\n"
1537                "    some_more_code();\n"
1538                "  }\n"
1539                "}");
1540   verifyFormat("{\n"
1541                "  some_code();\n"
1542                "test_label:\n"
1543                "  some_other_code();\n"
1544                "}");
1545   verifyFormat("{\n"
1546                "  some_code();\n"
1547                "test_label:;\n"
1548                "  int i = 0;\n"
1549                "}");
1550   FormatStyle Style = getLLVMStyle();
1551   Style.IndentGotoLabels = false;
1552   verifyFormat("void f() {\n"
1553                "  some_code();\n"
1554                "test_label:\n"
1555                "  some_other_code();\n"
1556                "  {\n"
1557                "    some_more_code();\n"
1558                "another_label:\n"
1559                "    some_more_code();\n"
1560                "  }\n"
1561                "}",
1562                Style);
1563   verifyFormat("{\n"
1564                "  some_code();\n"
1565                "test_label:\n"
1566                "  some_other_code();\n"
1567                "}",
1568                Style);
1569   verifyFormat("{\n"
1570                "  some_code();\n"
1571                "test_label:;\n"
1572                "  int i = 0;\n"
1573                "}");
1574 }
1575 
1576 TEST_F(FormatTest, MultiLineControlStatements) {
1577   FormatStyle Style = getLLVMStyle();
1578   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
1579   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_MultiLine;
1580   Style.ColumnLimit = 20;
1581   // Short lines should keep opening brace on same line.
1582   EXPECT_EQ("if (foo) {\n"
1583             "  bar();\n"
1584             "}",
1585             format("if(foo){bar();}", Style));
1586   EXPECT_EQ("if (foo) {\n"
1587             "  bar();\n"
1588             "} else {\n"
1589             "  baz();\n"
1590             "}",
1591             format("if(foo){bar();}else{baz();}", Style));
1592   EXPECT_EQ("if (foo && bar) {\n"
1593             "  baz();\n"
1594             "}",
1595             format("if(foo&&bar){baz();}", Style));
1596   EXPECT_EQ("if (foo) {\n"
1597             "  bar();\n"
1598             "} else if (baz) {\n"
1599             "  quux();\n"
1600             "}",
1601             format("if(foo){bar();}else if(baz){quux();}", Style));
1602   EXPECT_EQ(
1603       "if (foo) {\n"
1604       "  bar();\n"
1605       "} else if (baz) {\n"
1606       "  quux();\n"
1607       "} else {\n"
1608       "  foobar();\n"
1609       "}",
1610       format("if(foo){bar();}else if(baz){quux();}else{foobar();}", Style));
1611   EXPECT_EQ("for (;;) {\n"
1612             "  foo();\n"
1613             "}",
1614             format("for(;;){foo();}"));
1615   EXPECT_EQ("while (1) {\n"
1616             "  foo();\n"
1617             "}",
1618             format("while(1){foo();}", Style));
1619   EXPECT_EQ("switch (foo) {\n"
1620             "case bar:\n"
1621             "  return;\n"
1622             "}",
1623             format("switch(foo){case bar:return;}", Style));
1624   EXPECT_EQ("try {\n"
1625             "  foo();\n"
1626             "} catch (...) {\n"
1627             "  bar();\n"
1628             "}",
1629             format("try{foo();}catch(...){bar();}", Style));
1630   EXPECT_EQ("do {\n"
1631             "  foo();\n"
1632             "} while (bar &&\n"
1633             "         baz);",
1634             format("do{foo();}while(bar&&baz);", Style));
1635   // Long lines should put opening brace on new line.
1636   EXPECT_EQ("if (foo && bar &&\n"
1637             "    baz)\n"
1638             "{\n"
1639             "  quux();\n"
1640             "}",
1641             format("if(foo&&bar&&baz){quux();}", Style));
1642   EXPECT_EQ("if (foo && bar &&\n"
1643             "    baz)\n"
1644             "{\n"
1645             "  quux();\n"
1646             "}",
1647             format("if (foo && bar &&\n"
1648                    "    baz) {\n"
1649                    "  quux();\n"
1650                    "}",
1651                    Style));
1652   EXPECT_EQ("if (foo) {\n"
1653             "  bar();\n"
1654             "} else if (baz ||\n"
1655             "           quux)\n"
1656             "{\n"
1657             "  foobar();\n"
1658             "}",
1659             format("if(foo){bar();}else if(baz||quux){foobar();}", Style));
1660   EXPECT_EQ(
1661       "if (foo) {\n"
1662       "  bar();\n"
1663       "} else if (baz ||\n"
1664       "           quux)\n"
1665       "{\n"
1666       "  foobar();\n"
1667       "} else {\n"
1668       "  barbaz();\n"
1669       "}",
1670       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
1671              Style));
1672   EXPECT_EQ("for (int i = 0;\n"
1673             "     i < 10; ++i)\n"
1674             "{\n"
1675             "  foo();\n"
1676             "}",
1677             format("for(int i=0;i<10;++i){foo();}", Style));
1678   EXPECT_EQ("foreach (int i,\n"
1679             "         list)\n"
1680             "{\n"
1681             "  foo();\n"
1682             "}",
1683             format("foreach(int i, list){foo();}", Style));
1684   Style.ColumnLimit =
1685       40; // to concentrate at brace wrapping, not line wrap due to column limit
1686   EXPECT_EQ("foreach (int i, list) {\n"
1687             "  foo();\n"
1688             "}",
1689             format("foreach(int i, list){foo();}", Style));
1690   Style.ColumnLimit =
1691       20; // to concentrate at brace wrapping, not line wrap due to column limit
1692   EXPECT_EQ("while (foo || bar ||\n"
1693             "       baz)\n"
1694             "{\n"
1695             "  quux();\n"
1696             "}",
1697             format("while(foo||bar||baz){quux();}", Style));
1698   EXPECT_EQ("switch (\n"
1699             "    foo = barbaz)\n"
1700             "{\n"
1701             "case quux:\n"
1702             "  return;\n"
1703             "}",
1704             format("switch(foo=barbaz){case quux:return;}", Style));
1705   EXPECT_EQ("try {\n"
1706             "  foo();\n"
1707             "} catch (\n"
1708             "    Exception &bar)\n"
1709             "{\n"
1710             "  baz();\n"
1711             "}",
1712             format("try{foo();}catch(Exception&bar){baz();}", Style));
1713   Style.ColumnLimit =
1714       40; // to concentrate at brace wrapping, not line wrap due to column limit
1715   EXPECT_EQ("try {\n"
1716             "  foo();\n"
1717             "} catch (Exception &bar) {\n"
1718             "  baz();\n"
1719             "}",
1720             format("try{foo();}catch(Exception&bar){baz();}", Style));
1721   Style.ColumnLimit =
1722       20; // to concentrate at brace wrapping, not line wrap due to column limit
1723 
1724   Style.BraceWrapping.BeforeElse = true;
1725   EXPECT_EQ(
1726       "if (foo) {\n"
1727       "  bar();\n"
1728       "}\n"
1729       "else if (baz ||\n"
1730       "         quux)\n"
1731       "{\n"
1732       "  foobar();\n"
1733       "}\n"
1734       "else {\n"
1735       "  barbaz();\n"
1736       "}",
1737       format("if(foo){bar();}else if(baz||quux){foobar();}else{barbaz();}",
1738              Style));
1739 
1740   Style.BraceWrapping.BeforeCatch = true;
1741   EXPECT_EQ("try {\n"
1742             "  foo();\n"
1743             "}\n"
1744             "catch (...) {\n"
1745             "  baz();\n"
1746             "}",
1747             format("try{foo();}catch(...){baz();}", Style));
1748 }
1749 
1750 TEST_F(FormatTest, BeforeWhile) {
1751   FormatStyle Style = getLLVMStyle();
1752   Style.BreakBeforeBraces = FormatStyle::BraceBreakingStyle::BS_Custom;
1753 
1754   verifyFormat("do {\n"
1755                "  foo();\n"
1756                "} while (1);",
1757                Style);
1758   Style.BraceWrapping.BeforeWhile = true;
1759   verifyFormat("do {\n"
1760                "  foo();\n"
1761                "}\n"
1762                "while (1);",
1763                Style);
1764 }
1765 
1766 //===----------------------------------------------------------------------===//
1767 // Tests for classes, namespaces, etc.
1768 //===----------------------------------------------------------------------===//
1769 
1770 TEST_F(FormatTest, DoesNotBreakSemiAfterClassDecl) {
1771   verifyFormat("class A {};");
1772 }
1773 
1774 TEST_F(FormatTest, UnderstandsAccessSpecifiers) {
1775   verifyFormat("class A {\n"
1776                "public:\n"
1777                "public: // comment\n"
1778                "protected:\n"
1779                "private:\n"
1780                "  void f() {}\n"
1781                "};");
1782   verifyFormat("export class A {\n"
1783                "public:\n"
1784                "public: // comment\n"
1785                "protected:\n"
1786                "private:\n"
1787                "  void f() {}\n"
1788                "};");
1789   verifyGoogleFormat("class A {\n"
1790                      " public:\n"
1791                      " protected:\n"
1792                      " private:\n"
1793                      "  void f() {}\n"
1794                      "};");
1795   verifyGoogleFormat("export class A {\n"
1796                      " public:\n"
1797                      " protected:\n"
1798                      " private:\n"
1799                      "  void f() {}\n"
1800                      "};");
1801   verifyFormat("class A {\n"
1802                "public slots:\n"
1803                "  void f1() {}\n"
1804                "public Q_SLOTS:\n"
1805                "  void f2() {}\n"
1806                "protected slots:\n"
1807                "  void f3() {}\n"
1808                "protected Q_SLOTS:\n"
1809                "  void f4() {}\n"
1810                "private slots:\n"
1811                "  void f5() {}\n"
1812                "private Q_SLOTS:\n"
1813                "  void f6() {}\n"
1814                "signals:\n"
1815                "  void g1();\n"
1816                "Q_SIGNALS:\n"
1817                "  void g2();\n"
1818                "};");
1819 
1820   // Don't interpret 'signals' the wrong way.
1821   verifyFormat("signals.set();");
1822   verifyFormat("for (Signals signals : f()) {\n}");
1823   verifyFormat("{\n"
1824                "  signals.set(); // This needs indentation.\n"
1825                "}");
1826   verifyFormat("void f() {\n"
1827                "label:\n"
1828                "  signals.baz();\n"
1829                "}");
1830 }
1831 
1832 TEST_F(FormatTest, SeparatesLogicalBlocks) {
1833   EXPECT_EQ("class A {\n"
1834             "public:\n"
1835             "  void f();\n"
1836             "\n"
1837             "private:\n"
1838             "  void g() {}\n"
1839             "  // test\n"
1840             "protected:\n"
1841             "  int h;\n"
1842             "};",
1843             format("class A {\n"
1844                    "public:\n"
1845                    "void f();\n"
1846                    "private:\n"
1847                    "void g() {}\n"
1848                    "// test\n"
1849                    "protected:\n"
1850                    "int h;\n"
1851                    "};"));
1852   EXPECT_EQ("class A {\n"
1853             "protected:\n"
1854             "public:\n"
1855             "  void f();\n"
1856             "};",
1857             format("class A {\n"
1858                    "protected:\n"
1859                    "\n"
1860                    "public:\n"
1861                    "\n"
1862                    "  void f();\n"
1863                    "};"));
1864 
1865   // Even ensure proper spacing inside macros.
1866   EXPECT_EQ("#define B     \\\n"
1867             "  class A {   \\\n"
1868             "   protected: \\\n"
1869             "   public:    \\\n"
1870             "    void f(); \\\n"
1871             "  };",
1872             format("#define B     \\\n"
1873                    "  class A {   \\\n"
1874                    "   protected: \\\n"
1875                    "              \\\n"
1876                    "   public:    \\\n"
1877                    "              \\\n"
1878                    "    void f(); \\\n"
1879                    "  };",
1880                    getGoogleStyle()));
1881   // But don't remove empty lines after macros ending in access specifiers.
1882   EXPECT_EQ("#define A private:\n"
1883             "\n"
1884             "int i;",
1885             format("#define A         private:\n"
1886                    "\n"
1887                    "int              i;"));
1888 }
1889 
1890 TEST_F(FormatTest, FormatsClasses) {
1891   verifyFormat("class A : public B {};");
1892   verifyFormat("class A : public ::B {};");
1893 
1894   verifyFormat(
1895       "class AAAAAAAAAAAAAAAAAAAA : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1896       "                             public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1897   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\n"
1898                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1899                "      public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};");
1900   verifyFormat(
1901       "class A : public B, public C, public D, public E, public F {};");
1902   verifyFormat("class AAAAAAAAAAAA : public B,\n"
1903                "                     public C,\n"
1904                "                     public D,\n"
1905                "                     public E,\n"
1906                "                     public F,\n"
1907                "                     public G {};");
1908 
1909   verifyFormat("class\n"
1910                "    ReallyReallyLongClassName {\n"
1911                "  int i;\n"
1912                "};",
1913                getLLVMStyleWithColumns(32));
1914   verifyFormat("struct aaaaaaaaaaaaa : public aaaaaaaaaaaaaaaaaaa< // break\n"
1915                "                           aaaaaaaaaaaaaaaa> {};");
1916   verifyFormat("struct aaaaaaaaaaaaaaaaaaaa\n"
1917                "    : public aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaa,\n"
1918                "                                 aaaaaaaaaaaaaaaaaaaaaa> {};");
1919   verifyFormat("template <class R, class C>\n"
1920                "struct Aaaaaaaaaaaaaaaaa<R (C::*)(int) const>\n"
1921                "    : Aaaaaaaaaaaaaaaaa<R (C::*)(int)> {};");
1922   verifyFormat("class ::A::B {};");
1923 }
1924 
1925 TEST_F(FormatTest, BreakInheritanceStyle) {
1926   FormatStyle StyleWithInheritanceBreakBeforeComma = getLLVMStyle();
1927   StyleWithInheritanceBreakBeforeComma.BreakInheritanceList =
1928       FormatStyle::BILS_BeforeComma;
1929   verifyFormat("class MyClass : public X {};",
1930                StyleWithInheritanceBreakBeforeComma);
1931   verifyFormat("class MyClass\n"
1932                "    : public X\n"
1933                "    , public Y {};",
1934                StyleWithInheritanceBreakBeforeComma);
1935   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA\n"
1936                "    : public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB\n"
1937                "    , public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
1938                StyleWithInheritanceBreakBeforeComma);
1939   verifyFormat("struct aaaaaaaaaaaaa\n"
1940                "    : public aaaaaaaaaaaaaaaaaaa< // break\n"
1941                "          aaaaaaaaaaaaaaaa> {};",
1942                StyleWithInheritanceBreakBeforeComma);
1943 
1944   FormatStyle StyleWithInheritanceBreakAfterColon = getLLVMStyle();
1945   StyleWithInheritanceBreakAfterColon.BreakInheritanceList =
1946       FormatStyle::BILS_AfterColon;
1947   verifyFormat("class MyClass : public X {};",
1948                StyleWithInheritanceBreakAfterColon);
1949   verifyFormat("class MyClass : public X, public Y {};",
1950                StyleWithInheritanceBreakAfterColon);
1951   verifyFormat("class AAAAAAAAAAAAAAAAAAAAAA :\n"
1952                "    public BBBBBBBBBBBBBBBBBBBBBBBBBBBBBB,\n"
1953                "    public CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC {};",
1954                StyleWithInheritanceBreakAfterColon);
1955   verifyFormat("struct aaaaaaaaaaaaa :\n"
1956                "    public aaaaaaaaaaaaaaaaaaa< // break\n"
1957                "        aaaaaaaaaaaaaaaa> {};",
1958                StyleWithInheritanceBreakAfterColon);
1959 }
1960 
1961 TEST_F(FormatTest, FormatsVariableDeclarationsAfterStructOrClass) {
1962   verifyFormat("class A {\n} a, b;");
1963   verifyFormat("struct A {\n} a, b;");
1964   verifyFormat("union A {\n} a;");
1965 }
1966 
1967 TEST_F(FormatTest, FormatsEnum) {
1968   verifyFormat("enum {\n"
1969                "  Zero,\n"
1970                "  One = 1,\n"
1971                "  Two = One + 1,\n"
1972                "  Three = (One + Two),\n"
1973                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1974                "  Five = (One, Two, Three, Four, 5)\n"
1975                "};");
1976   verifyGoogleFormat("enum {\n"
1977                      "  Zero,\n"
1978                      "  One = 1,\n"
1979                      "  Two = One + 1,\n"
1980                      "  Three = (One + Two),\n"
1981                      "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
1982                      "  Five = (One, Two, Three, Four, 5)\n"
1983                      "};");
1984   verifyFormat("enum Enum {};");
1985   verifyFormat("enum {};");
1986   verifyFormat("enum X E {} d;");
1987   verifyFormat("enum __attribute__((...)) E {} d;");
1988   verifyFormat("enum __declspec__((...)) E {} d;");
1989   verifyFormat("enum {\n"
1990                "  Bar = Foo<int, int>::value\n"
1991                "};",
1992                getLLVMStyleWithColumns(30));
1993 
1994   verifyFormat("enum ShortEnum { A, B, C };");
1995   verifyGoogleFormat("enum ShortEnum { A, B, C };");
1996 
1997   EXPECT_EQ("enum KeepEmptyLines {\n"
1998             "  ONE,\n"
1999             "\n"
2000             "  TWO,\n"
2001             "\n"
2002             "  THREE\n"
2003             "}",
2004             format("enum KeepEmptyLines {\n"
2005                    "  ONE,\n"
2006                    "\n"
2007                    "  TWO,\n"
2008                    "\n"
2009                    "\n"
2010                    "  THREE\n"
2011                    "}"));
2012   verifyFormat("enum E { // comment\n"
2013                "  ONE,\n"
2014                "  TWO\n"
2015                "};\n"
2016                "int i;");
2017 
2018   FormatStyle EightIndent = getLLVMStyle();
2019   EightIndent.IndentWidth = 8;
2020   verifyFormat("enum {\n"
2021                "        VOID,\n"
2022                "        CHAR,\n"
2023                "        SHORT,\n"
2024                "        INT,\n"
2025                "        LONG,\n"
2026                "        SIGNED,\n"
2027                "        UNSIGNED,\n"
2028                "        BOOL,\n"
2029                "        FLOAT,\n"
2030                "        DOUBLE,\n"
2031                "        COMPLEX\n"
2032                "};",
2033                EightIndent);
2034 
2035   // Not enums.
2036   verifyFormat("enum X f() {\n"
2037                "  a();\n"
2038                "  return 42;\n"
2039                "}");
2040   verifyFormat("enum X Type::f() {\n"
2041                "  a();\n"
2042                "  return 42;\n"
2043                "}");
2044   verifyFormat("enum ::X f() {\n"
2045                "  a();\n"
2046                "  return 42;\n"
2047                "}");
2048   verifyFormat("enum ns::X f() {\n"
2049                "  a();\n"
2050                "  return 42;\n"
2051                "}");
2052 }
2053 
2054 TEST_F(FormatTest, FormatsEnumsWithErrors) {
2055   verifyFormat("enum Type {\n"
2056                "  One = 0; // These semicolons should be commas.\n"
2057                "  Two = 1;\n"
2058                "};");
2059   verifyFormat("namespace n {\n"
2060                "enum Type {\n"
2061                "  One,\n"
2062                "  Two, // missing };\n"
2063                "  int i;\n"
2064                "}\n"
2065                "void g() {}");
2066 }
2067 
2068 TEST_F(FormatTest, FormatsEnumStruct) {
2069   verifyFormat("enum struct {\n"
2070                "  Zero,\n"
2071                "  One = 1,\n"
2072                "  Two = One + 1,\n"
2073                "  Three = (One + Two),\n"
2074                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2075                "  Five = (One, Two, Three, Four, 5)\n"
2076                "};");
2077   verifyFormat("enum struct Enum {};");
2078   verifyFormat("enum struct {};");
2079   verifyFormat("enum struct X E {} d;");
2080   verifyFormat("enum struct __attribute__((...)) E {} d;");
2081   verifyFormat("enum struct __declspec__((...)) E {} d;");
2082   verifyFormat("enum struct X f() {\n  a();\n  return 42;\n}");
2083 }
2084 
2085 TEST_F(FormatTest, FormatsEnumClass) {
2086   verifyFormat("enum class {\n"
2087                "  Zero,\n"
2088                "  One = 1,\n"
2089                "  Two = One + 1,\n"
2090                "  Three = (One + Two),\n"
2091                "  Four = (Zero && (One ^ Two)) | (One << Two),\n"
2092                "  Five = (One, Two, Three, Four, 5)\n"
2093                "};");
2094   verifyFormat("enum class Enum {};");
2095   verifyFormat("enum class {};");
2096   verifyFormat("enum class X E {} d;");
2097   verifyFormat("enum class __attribute__((...)) E {} d;");
2098   verifyFormat("enum class __declspec__((...)) E {} d;");
2099   verifyFormat("enum class X f() {\n  a();\n  return 42;\n}");
2100 }
2101 
2102 TEST_F(FormatTest, FormatsEnumTypes) {
2103   verifyFormat("enum X : int {\n"
2104                "  A, // Force multiple lines.\n"
2105                "  B\n"
2106                "};");
2107   verifyFormat("enum X : int { A, B };");
2108   verifyFormat("enum X : std::uint32_t { A, B };");
2109 }
2110 
2111 TEST_F(FormatTest, FormatsTypedefEnum) {
2112   FormatStyle Style = getLLVMStyle();
2113   Style.ColumnLimit = 40;
2114   verifyFormat("typedef enum {} EmptyEnum;");
2115   verifyFormat("typedef enum { A, B, C } ShortEnum;");
2116   verifyFormat("typedef enum {\n"
2117                "  ZERO = 0,\n"
2118                "  ONE = 1,\n"
2119                "  TWO = 2,\n"
2120                "  THREE = 3\n"
2121                "} LongEnum;",
2122                Style);
2123   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2124   Style.BraceWrapping.AfterEnum = true;
2125   verifyFormat("typedef enum {} EmptyEnum;");
2126   verifyFormat("typedef enum { A, B, C } ShortEnum;");
2127   verifyFormat("typedef enum\n"
2128                "{\n"
2129                "  ZERO = 0,\n"
2130                "  ONE = 1,\n"
2131                "  TWO = 2,\n"
2132                "  THREE = 3\n"
2133                "} LongEnum;",
2134                Style);
2135 }
2136 
2137 TEST_F(FormatTest, FormatsNSEnums) {
2138   verifyGoogleFormat("typedef NS_ENUM(NSInteger, SomeName) { AAA, BBB }");
2139   verifyGoogleFormat(
2140       "typedef NS_CLOSED_ENUM(NSInteger, SomeName) { AAA, BBB }");
2141   verifyGoogleFormat("typedef NS_ENUM(NSInteger, MyType) {\n"
2142                      "  // Information about someDecentlyLongValue.\n"
2143                      "  someDecentlyLongValue,\n"
2144                      "  // Information about anotherDecentlyLongValue.\n"
2145                      "  anotherDecentlyLongValue,\n"
2146                      "  // Information about aThirdDecentlyLongValue.\n"
2147                      "  aThirdDecentlyLongValue\n"
2148                      "};");
2149   verifyGoogleFormat("typedef NS_CLOSED_ENUM(NSInteger, MyType) {\n"
2150                      "  // Information about someDecentlyLongValue.\n"
2151                      "  someDecentlyLongValue,\n"
2152                      "  // Information about anotherDecentlyLongValue.\n"
2153                      "  anotherDecentlyLongValue,\n"
2154                      "  // Information about aThirdDecentlyLongValue.\n"
2155                      "  aThirdDecentlyLongValue\n"
2156                      "};");
2157   verifyGoogleFormat("typedef NS_OPTIONS(NSInteger, MyType) {\n"
2158                      "  a = 1,\n"
2159                      "  b = 2,\n"
2160                      "  c = 3,\n"
2161                      "};");
2162   verifyGoogleFormat("typedef CF_ENUM(NSInteger, MyType) {\n"
2163                      "  a = 1,\n"
2164                      "  b = 2,\n"
2165                      "  c = 3,\n"
2166                      "};");
2167   verifyGoogleFormat("typedef CF_CLOSED_ENUM(NSInteger, MyType) {\n"
2168                      "  a = 1,\n"
2169                      "  b = 2,\n"
2170                      "  c = 3,\n"
2171                      "};");
2172   verifyGoogleFormat("typedef CF_OPTIONS(NSInteger, MyType) {\n"
2173                      "  a = 1,\n"
2174                      "  b = 2,\n"
2175                      "  c = 3,\n"
2176                      "};");
2177 }
2178 
2179 TEST_F(FormatTest, FormatsBitfields) {
2180   verifyFormat("struct Bitfields {\n"
2181                "  unsigned sClass : 8;\n"
2182                "  unsigned ValueKind : 2;\n"
2183                "};");
2184   verifyFormat("struct A {\n"
2185                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa : 1,\n"
2186                "      bbbbbbbbbbbbbbbbbbbbbbbbb;\n"
2187                "};");
2188   verifyFormat("struct MyStruct {\n"
2189                "  uchar data;\n"
2190                "  uchar : 8;\n"
2191                "  uchar : 8;\n"
2192                "  uchar other;\n"
2193                "};");
2194   FormatStyle Style = getLLVMStyle();
2195   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
2196   verifyFormat("struct Bitfields {\n"
2197                "  unsigned sClass:8;\n"
2198                "  unsigned ValueKind:2;\n"
2199                "  uchar other;\n"
2200                "};",
2201                Style);
2202   verifyFormat("struct A {\n"
2203                "  int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:1,\n"
2204                "      bbbbbbbbbbbbbbbbbbbbbbbbb:2;\n"
2205                "};",
2206                Style);
2207   Style.BitFieldColonSpacing = FormatStyle::BFCS_Before;
2208   verifyFormat("struct Bitfields {\n"
2209                "  unsigned sClass :8;\n"
2210                "  unsigned ValueKind :2;\n"
2211                "  uchar other;\n"
2212                "};",
2213                Style);
2214   Style.BitFieldColonSpacing = FormatStyle::BFCS_After;
2215   verifyFormat("struct Bitfields {\n"
2216                "  unsigned sClass: 8;\n"
2217                "  unsigned ValueKind: 2;\n"
2218                "  uchar other;\n"
2219                "};",
2220                Style);
2221 }
2222 
2223 TEST_F(FormatTest, FormatsNamespaces) {
2224   FormatStyle LLVMWithNoNamespaceFix = getLLVMStyle();
2225   LLVMWithNoNamespaceFix.FixNamespaceComments = false;
2226 
2227   verifyFormat("namespace some_namespace {\n"
2228                "class A {};\n"
2229                "void f() { f(); }\n"
2230                "}",
2231                LLVMWithNoNamespaceFix);
2232   verifyFormat("namespace N::inline D {\n"
2233                "class A {};\n"
2234                "void f() { f(); }\n"
2235                "}",
2236                LLVMWithNoNamespaceFix);
2237   verifyFormat("namespace N::inline D::E {\n"
2238                "class A {};\n"
2239                "void f() { f(); }\n"
2240                "}",
2241                LLVMWithNoNamespaceFix);
2242   verifyFormat("namespace [[deprecated(\"foo[bar\")]] some_namespace {\n"
2243                "class A {};\n"
2244                "void f() { f(); }\n"
2245                "}",
2246                LLVMWithNoNamespaceFix);
2247   verifyFormat("/* something */ namespace some_namespace {\n"
2248                "class A {};\n"
2249                "void f() { f(); }\n"
2250                "}",
2251                LLVMWithNoNamespaceFix);
2252   verifyFormat("namespace {\n"
2253                "class A {};\n"
2254                "void f() { f(); }\n"
2255                "}",
2256                LLVMWithNoNamespaceFix);
2257   verifyFormat("/* something */ namespace {\n"
2258                "class A {};\n"
2259                "void f() { f(); }\n"
2260                "}",
2261                LLVMWithNoNamespaceFix);
2262   verifyFormat("inline namespace X {\n"
2263                "class A {};\n"
2264                "void f() { f(); }\n"
2265                "}",
2266                LLVMWithNoNamespaceFix);
2267   verifyFormat("/* something */ inline namespace X {\n"
2268                "class A {};\n"
2269                "void f() { f(); }\n"
2270                "}",
2271                LLVMWithNoNamespaceFix);
2272   verifyFormat("export namespace X {\n"
2273                "class A {};\n"
2274                "void f() { f(); }\n"
2275                "}",
2276                LLVMWithNoNamespaceFix);
2277   verifyFormat("using namespace some_namespace;\n"
2278                "class A {};\n"
2279                "void f() { f(); }",
2280                LLVMWithNoNamespaceFix);
2281 
2282   // This code is more common than we thought; if we
2283   // layout this correctly the semicolon will go into
2284   // its own line, which is undesirable.
2285   verifyFormat("namespace {};", LLVMWithNoNamespaceFix);
2286   verifyFormat("namespace {\n"
2287                "class A {};\n"
2288                "};",
2289                LLVMWithNoNamespaceFix);
2290 
2291   verifyFormat("namespace {\n"
2292                "int SomeVariable = 0; // comment\n"
2293                "} // namespace",
2294                LLVMWithNoNamespaceFix);
2295   EXPECT_EQ("#ifndef HEADER_GUARD\n"
2296             "#define HEADER_GUARD\n"
2297             "namespace my_namespace {\n"
2298             "int i;\n"
2299             "} // my_namespace\n"
2300             "#endif // HEADER_GUARD",
2301             format("#ifndef HEADER_GUARD\n"
2302                    " #define HEADER_GUARD\n"
2303                    "   namespace my_namespace {\n"
2304                    "int i;\n"
2305                    "}    // my_namespace\n"
2306                    "#endif    // HEADER_GUARD",
2307                    LLVMWithNoNamespaceFix));
2308 
2309   EXPECT_EQ("namespace A::B {\n"
2310             "class C {};\n"
2311             "}",
2312             format("namespace A::B {\n"
2313                    "class C {};\n"
2314                    "}",
2315                    LLVMWithNoNamespaceFix));
2316 
2317   FormatStyle Style = getLLVMStyle();
2318   Style.NamespaceIndentation = FormatStyle::NI_All;
2319   EXPECT_EQ("namespace out {\n"
2320             "  int i;\n"
2321             "  namespace in {\n"
2322             "    int i;\n"
2323             "  } // namespace in\n"
2324             "} // namespace out",
2325             format("namespace out {\n"
2326                    "int i;\n"
2327                    "namespace in {\n"
2328                    "int i;\n"
2329                    "} // namespace in\n"
2330                    "} // namespace out",
2331                    Style));
2332 
2333   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2334   EXPECT_EQ("namespace out {\n"
2335             "int i;\n"
2336             "namespace in {\n"
2337             "  int i;\n"
2338             "} // namespace in\n"
2339             "} // namespace out",
2340             format("namespace out {\n"
2341                    "int i;\n"
2342                    "namespace in {\n"
2343                    "int i;\n"
2344                    "} // namespace in\n"
2345                    "} // namespace out",
2346                    Style));
2347 }
2348 
2349 TEST_F(FormatTest, NamespaceMacros) {
2350   FormatStyle Style = getLLVMStyle();
2351   Style.NamespaceMacros.push_back("TESTSUITE");
2352 
2353   verifyFormat("TESTSUITE(A) {\n"
2354                "int foo();\n"
2355                "} // TESTSUITE(A)",
2356                Style);
2357 
2358   verifyFormat("TESTSUITE(A, B) {\n"
2359                "int foo();\n"
2360                "} // TESTSUITE(A)",
2361                Style);
2362 
2363   // Properly indent according to NamespaceIndentation style
2364   Style.NamespaceIndentation = FormatStyle::NI_All;
2365   verifyFormat("TESTSUITE(A) {\n"
2366                "  int foo();\n"
2367                "} // TESTSUITE(A)",
2368                Style);
2369   verifyFormat("TESTSUITE(A) {\n"
2370                "  namespace B {\n"
2371                "    int foo();\n"
2372                "  } // namespace B\n"
2373                "} // TESTSUITE(A)",
2374                Style);
2375   verifyFormat("namespace A {\n"
2376                "  TESTSUITE(B) {\n"
2377                "    int foo();\n"
2378                "  } // TESTSUITE(B)\n"
2379                "} // namespace A",
2380                Style);
2381 
2382   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2383   verifyFormat("TESTSUITE(A) {\n"
2384                "TESTSUITE(B) {\n"
2385                "  int foo();\n"
2386                "} // TESTSUITE(B)\n"
2387                "} // TESTSUITE(A)",
2388                Style);
2389   verifyFormat("TESTSUITE(A) {\n"
2390                "namespace B {\n"
2391                "  int foo();\n"
2392                "} // namespace B\n"
2393                "} // TESTSUITE(A)",
2394                Style);
2395   verifyFormat("namespace A {\n"
2396                "TESTSUITE(B) {\n"
2397                "  int foo();\n"
2398                "} // TESTSUITE(B)\n"
2399                "} // namespace A",
2400                Style);
2401 
2402   // Properly merge namespace-macros blocks in CompactNamespaces mode
2403   Style.NamespaceIndentation = FormatStyle::NI_None;
2404   Style.CompactNamespaces = true;
2405   verifyFormat("TESTSUITE(A) { TESTSUITE(B) {\n"
2406                "}} // TESTSUITE(A::B)",
2407                Style);
2408 
2409   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2410             "}} // TESTSUITE(out::in)",
2411             format("TESTSUITE(out) {\n"
2412                    "TESTSUITE(in) {\n"
2413                    "} // TESTSUITE(in)\n"
2414                    "} // TESTSUITE(out)",
2415                    Style));
2416 
2417   EXPECT_EQ("TESTSUITE(out) { TESTSUITE(in) {\n"
2418             "}} // TESTSUITE(out::in)",
2419             format("TESTSUITE(out) {\n"
2420                    "TESTSUITE(in) {\n"
2421                    "} // TESTSUITE(in)\n"
2422                    "} // TESTSUITE(out)",
2423                    Style));
2424 
2425   // Do not merge different namespaces/macros
2426   EXPECT_EQ("namespace out {\n"
2427             "TESTSUITE(in) {\n"
2428             "} // TESTSUITE(in)\n"
2429             "} // namespace out",
2430             format("namespace out {\n"
2431                    "TESTSUITE(in) {\n"
2432                    "} // TESTSUITE(in)\n"
2433                    "} // namespace out",
2434                    Style));
2435   EXPECT_EQ("TESTSUITE(out) {\n"
2436             "namespace in {\n"
2437             "} // namespace in\n"
2438             "} // TESTSUITE(out)",
2439             format("TESTSUITE(out) {\n"
2440                    "namespace in {\n"
2441                    "} // namespace in\n"
2442                    "} // TESTSUITE(out)",
2443                    Style));
2444   Style.NamespaceMacros.push_back("FOOBAR");
2445   EXPECT_EQ("TESTSUITE(out) {\n"
2446             "FOOBAR(in) {\n"
2447             "} // FOOBAR(in)\n"
2448             "} // TESTSUITE(out)",
2449             format("TESTSUITE(out) {\n"
2450                    "FOOBAR(in) {\n"
2451                    "} // FOOBAR(in)\n"
2452                    "} // TESTSUITE(out)",
2453                    Style));
2454 }
2455 
2456 TEST_F(FormatTest, FormatsCompactNamespaces) {
2457   FormatStyle Style = getLLVMStyle();
2458   Style.CompactNamespaces = true;
2459   Style.NamespaceMacros.push_back("TESTSUITE");
2460 
2461   verifyFormat("namespace A { namespace B {\n"
2462                "}} // namespace A::B",
2463                Style);
2464 
2465   EXPECT_EQ("namespace out { namespace in {\n"
2466             "}} // namespace out::in",
2467             format("namespace out {\n"
2468                    "namespace in {\n"
2469                    "} // namespace in\n"
2470                    "} // namespace out",
2471                    Style));
2472 
2473   // Only namespaces which have both consecutive opening and end get compacted
2474   EXPECT_EQ("namespace out {\n"
2475             "namespace in1 {\n"
2476             "} // namespace in1\n"
2477             "namespace in2 {\n"
2478             "} // namespace in2\n"
2479             "} // namespace out",
2480             format("namespace out {\n"
2481                    "namespace in1 {\n"
2482                    "} // namespace in1\n"
2483                    "namespace in2 {\n"
2484                    "} // namespace in2\n"
2485                    "} // namespace out",
2486                    Style));
2487 
2488   EXPECT_EQ("namespace out {\n"
2489             "int i;\n"
2490             "namespace in {\n"
2491             "int j;\n"
2492             "} // namespace in\n"
2493             "int k;\n"
2494             "} // namespace out",
2495             format("namespace out { int i;\n"
2496                    "namespace in { int j; } // namespace in\n"
2497                    "int k; } // namespace out",
2498                    Style));
2499 
2500   EXPECT_EQ("namespace A { namespace B { namespace C {\n"
2501             "}}} // namespace A::B::C\n",
2502             format("namespace A { namespace B {\n"
2503                    "namespace C {\n"
2504                    "}} // namespace B::C\n"
2505                    "} // namespace A\n",
2506                    Style));
2507 
2508   Style.ColumnLimit = 40;
2509   EXPECT_EQ("namespace aaaaaaaaaa {\n"
2510             "namespace bbbbbbbbbb {\n"
2511             "}} // namespace aaaaaaaaaa::bbbbbbbbbb",
2512             format("namespace aaaaaaaaaa {\n"
2513                    "namespace bbbbbbbbbb {\n"
2514                    "} // namespace bbbbbbbbbb\n"
2515                    "} // namespace aaaaaaaaaa",
2516                    Style));
2517 
2518   EXPECT_EQ("namespace aaaaaa { namespace bbbbbb {\n"
2519             "namespace cccccc {\n"
2520             "}}} // namespace aaaaaa::bbbbbb::cccccc",
2521             format("namespace aaaaaa {\n"
2522                    "namespace bbbbbb {\n"
2523                    "namespace cccccc {\n"
2524                    "} // namespace cccccc\n"
2525                    "} // namespace bbbbbb\n"
2526                    "} // namespace aaaaaa",
2527                    Style));
2528   Style.ColumnLimit = 80;
2529 
2530   // Extra semicolon after 'inner' closing brace prevents merging
2531   EXPECT_EQ("namespace out { namespace in {\n"
2532             "}; } // namespace out::in",
2533             format("namespace out {\n"
2534                    "namespace in {\n"
2535                    "}; // namespace in\n"
2536                    "} // namespace out",
2537                    Style));
2538 
2539   // Extra semicolon after 'outer' closing brace is conserved
2540   EXPECT_EQ("namespace out { namespace in {\n"
2541             "}}; // namespace out::in",
2542             format("namespace out {\n"
2543                    "namespace in {\n"
2544                    "} // namespace in\n"
2545                    "}; // namespace out",
2546                    Style));
2547 
2548   Style.NamespaceIndentation = FormatStyle::NI_All;
2549   EXPECT_EQ("namespace out { namespace in {\n"
2550             "  int i;\n"
2551             "}} // namespace out::in",
2552             format("namespace out {\n"
2553                    "namespace in {\n"
2554                    "int i;\n"
2555                    "} // namespace in\n"
2556                    "} // namespace out",
2557                    Style));
2558   EXPECT_EQ("namespace out { namespace mid {\n"
2559             "  namespace in {\n"
2560             "    int j;\n"
2561             "  } // namespace in\n"
2562             "  int k;\n"
2563             "}} // namespace out::mid",
2564             format("namespace out { namespace mid {\n"
2565                    "namespace in { int j; } // namespace in\n"
2566                    "int k; }} // namespace out::mid",
2567                    Style));
2568 
2569   Style.NamespaceIndentation = FormatStyle::NI_Inner;
2570   EXPECT_EQ("namespace out { namespace in {\n"
2571             "  int i;\n"
2572             "}} // namespace out::in",
2573             format("namespace out {\n"
2574                    "namespace in {\n"
2575                    "int i;\n"
2576                    "} // namespace in\n"
2577                    "} // namespace out",
2578                    Style));
2579   EXPECT_EQ("namespace out { namespace mid { namespace in {\n"
2580             "  int i;\n"
2581             "}}} // namespace out::mid::in",
2582             format("namespace out {\n"
2583                    "namespace mid {\n"
2584                    "namespace in {\n"
2585                    "int i;\n"
2586                    "} // namespace in\n"
2587                    "} // namespace mid\n"
2588                    "} // namespace out",
2589                    Style));
2590 }
2591 
2592 TEST_F(FormatTest, FormatsExternC) {
2593   verifyFormat("extern \"C\" {\nint a;");
2594   verifyFormat("extern \"C\" {}");
2595   verifyFormat("extern \"C\" {\n"
2596                "int foo();\n"
2597                "}");
2598   verifyFormat("extern \"C\" int foo() {}");
2599   verifyFormat("extern \"C\" int foo();");
2600   verifyFormat("extern \"C\" int foo() {\n"
2601                "  int i = 42;\n"
2602                "  return i;\n"
2603                "}");
2604 
2605   FormatStyle Style = getLLVMStyle();
2606   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2607   Style.BraceWrapping.AfterFunction = true;
2608   verifyFormat("extern \"C\" int foo() {}", Style);
2609   verifyFormat("extern \"C\" int foo();", Style);
2610   verifyFormat("extern \"C\" int foo()\n"
2611                "{\n"
2612                "  int i = 42;\n"
2613                "  return i;\n"
2614                "}",
2615                Style);
2616 
2617   Style.BraceWrapping.AfterExternBlock = true;
2618   Style.BraceWrapping.SplitEmptyRecord = false;
2619   verifyFormat("extern \"C\"\n"
2620                "{}",
2621                Style);
2622   verifyFormat("extern \"C\"\n"
2623                "{\n"
2624                "  int foo();\n"
2625                "}",
2626                Style);
2627 }
2628 
2629 TEST_F(FormatTest, IndentExternBlockStyle) {
2630   FormatStyle Style = getLLVMStyle();
2631   Style.IndentWidth = 2;
2632 
2633   Style.IndentExternBlock = FormatStyle::IEBS_Indent;
2634   verifyFormat("extern \"C\" { /*9*/\n}", Style);
2635   verifyFormat("extern \"C\" {\n"
2636                "  int foo10();\n"
2637                "}",
2638                Style);
2639 
2640   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
2641   verifyFormat("extern \"C\" { /*11*/\n}", Style);
2642   verifyFormat("extern \"C\" {\n"
2643                "int foo12();\n"
2644                "}",
2645                Style);
2646 
2647   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
2648   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2649   Style.BraceWrapping.AfterExternBlock = true;
2650   verifyFormat("extern \"C\"\n{ /*13*/\n}", Style);
2651   verifyFormat("extern \"C\"\n{\n"
2652                "  int foo14();\n"
2653                "}",
2654                Style);
2655 
2656   Style.IndentExternBlock = FormatStyle::IEBS_AfterExternBlock;
2657   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2658   Style.BraceWrapping.AfterExternBlock = false;
2659   verifyFormat("extern \"C\" { /*15*/\n}", Style);
2660   verifyFormat("extern \"C\" {\n"
2661                "int foo16();\n"
2662                "}",
2663                Style);
2664 }
2665 
2666 TEST_F(FormatTest, FormatsInlineASM) {
2667   verifyFormat("asm(\"xyz\" : \"=a\"(a), \"=d\"(b) : \"a\"(data));");
2668   verifyFormat("asm(\"nop\" ::: \"memory\");");
2669   verifyFormat(
2670       "asm(\"movq\\t%%rbx, %%rsi\\n\\t\"\n"
2671       "    \"cpuid\\n\\t\"\n"
2672       "    \"xchgq\\t%%rbx, %%rsi\\n\\t\"\n"
2673       "    : \"=a\"(*rEAX), \"=S\"(*rEBX), \"=c\"(*rECX), \"=d\"(*rEDX)\n"
2674       "    : \"a\"(value));");
2675   EXPECT_EQ(
2676       "void NS_InvokeByIndex(void *that, unsigned int methodIndex) {\n"
2677       "  __asm {\n"
2678       "        mov     edx,[that] // vtable in edx\n"
2679       "        mov     eax,methodIndex\n"
2680       "        call    [edx][eax*4] // stdcall\n"
2681       "  }\n"
2682       "}",
2683       format("void NS_InvokeByIndex(void *that,   unsigned int methodIndex) {\n"
2684              "    __asm {\n"
2685              "        mov     edx,[that] // vtable in edx\n"
2686              "        mov     eax,methodIndex\n"
2687              "        call    [edx][eax*4] // stdcall\n"
2688              "    }\n"
2689              "}"));
2690   EXPECT_EQ("_asm {\n"
2691             "  xor eax, eax;\n"
2692             "  cpuid;\n"
2693             "}",
2694             format("_asm {\n"
2695                    "  xor eax, eax;\n"
2696                    "  cpuid;\n"
2697                    "}"));
2698   verifyFormat("void function() {\n"
2699                "  // comment\n"
2700                "  asm(\"\");\n"
2701                "}");
2702   EXPECT_EQ("__asm {\n"
2703             "}\n"
2704             "int i;",
2705             format("__asm   {\n"
2706                    "}\n"
2707                    "int   i;"));
2708 }
2709 
2710 TEST_F(FormatTest, FormatTryCatch) {
2711   verifyFormat("try {\n"
2712                "  throw a * b;\n"
2713                "} catch (int a) {\n"
2714                "  // Do nothing.\n"
2715                "} catch (...) {\n"
2716                "  exit(42);\n"
2717                "}");
2718 
2719   // Function-level try statements.
2720   verifyFormat("int f() try { return 4; } catch (...) {\n"
2721                "  return 5;\n"
2722                "}");
2723   verifyFormat("class A {\n"
2724                "  int a;\n"
2725                "  A() try : a(0) {\n"
2726                "  } catch (...) {\n"
2727                "    throw;\n"
2728                "  }\n"
2729                "};\n");
2730   verifyFormat("class A {\n"
2731                "  int a;\n"
2732                "  A() try : a(0), b{1} {\n"
2733                "  } catch (...) {\n"
2734                "    throw;\n"
2735                "  }\n"
2736                "};\n");
2737   verifyFormat("class A {\n"
2738                "  int a;\n"
2739                "  A() try : a(0), b{1}, c{2} {\n"
2740                "  } catch (...) {\n"
2741                "    throw;\n"
2742                "  }\n"
2743                "};\n");
2744   verifyFormat("class A {\n"
2745                "  int a;\n"
2746                "  A() try : a(0), b{1}, c{2} {\n"
2747                "    { // New scope.\n"
2748                "    }\n"
2749                "  } catch (...) {\n"
2750                "    throw;\n"
2751                "  }\n"
2752                "};\n");
2753 
2754   // Incomplete try-catch blocks.
2755   verifyIncompleteFormat("try {} catch (");
2756 }
2757 
2758 TEST_F(FormatTest, FormatTryAsAVariable) {
2759   verifyFormat("int try;");
2760   verifyFormat("int try, size;");
2761   verifyFormat("try = foo();");
2762   verifyFormat("if (try < size) {\n  return true;\n}");
2763 
2764   verifyFormat("int catch;");
2765   verifyFormat("int catch, size;");
2766   verifyFormat("catch = foo();");
2767   verifyFormat("if (catch < size) {\n  return true;\n}");
2768 
2769   FormatStyle Style = getLLVMStyle();
2770   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2771   Style.BraceWrapping.AfterFunction = true;
2772   Style.BraceWrapping.BeforeCatch = true;
2773   verifyFormat("try {\n"
2774                "  int bar = 1;\n"
2775                "}\n"
2776                "catch (...) {\n"
2777                "  int bar = 1;\n"
2778                "}",
2779                Style);
2780   verifyFormat("#if NO_EX\n"
2781                "try\n"
2782                "#endif\n"
2783                "{\n"
2784                "}\n"
2785                "#if NO_EX\n"
2786                "catch (...) {\n"
2787                "}",
2788                Style);
2789   verifyFormat("try /* abc */ {\n"
2790                "  int bar = 1;\n"
2791                "}\n"
2792                "catch (...) {\n"
2793                "  int bar = 1;\n"
2794                "}",
2795                Style);
2796   verifyFormat("try\n"
2797                "// abc\n"
2798                "{\n"
2799                "  int bar = 1;\n"
2800                "}\n"
2801                "catch (...) {\n"
2802                "  int bar = 1;\n"
2803                "}",
2804                Style);
2805 }
2806 
2807 TEST_F(FormatTest, FormatSEHTryCatch) {
2808   verifyFormat("__try {\n"
2809                "  int a = b * c;\n"
2810                "} __except (EXCEPTION_EXECUTE_HANDLER) {\n"
2811                "  // Do nothing.\n"
2812                "}");
2813 
2814   verifyFormat("__try {\n"
2815                "  int a = b * c;\n"
2816                "} __finally {\n"
2817                "  // Do nothing.\n"
2818                "}");
2819 
2820   verifyFormat("DEBUG({\n"
2821                "  __try {\n"
2822                "  } __finally {\n"
2823                "  }\n"
2824                "});\n");
2825 }
2826 
2827 TEST_F(FormatTest, IncompleteTryCatchBlocks) {
2828   verifyFormat("try {\n"
2829                "  f();\n"
2830                "} catch {\n"
2831                "  g();\n"
2832                "}");
2833   verifyFormat("try {\n"
2834                "  f();\n"
2835                "} catch (A a) MACRO(x) {\n"
2836                "  g();\n"
2837                "} catch (B b) MACRO(x) {\n"
2838                "  g();\n"
2839                "}");
2840 }
2841 
2842 TEST_F(FormatTest, FormatTryCatchBraceStyles) {
2843   FormatStyle Style = getLLVMStyle();
2844   for (auto BraceStyle : {FormatStyle::BS_Attach, FormatStyle::BS_Mozilla,
2845                           FormatStyle::BS_WebKit}) {
2846     Style.BreakBeforeBraces = BraceStyle;
2847     verifyFormat("try {\n"
2848                  "  // something\n"
2849                  "} catch (...) {\n"
2850                  "  // something\n"
2851                  "}",
2852                  Style);
2853   }
2854   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
2855   verifyFormat("try {\n"
2856                "  // something\n"
2857                "}\n"
2858                "catch (...) {\n"
2859                "  // something\n"
2860                "}",
2861                Style);
2862   verifyFormat("__try {\n"
2863                "  // something\n"
2864                "}\n"
2865                "__finally {\n"
2866                "  // something\n"
2867                "}",
2868                Style);
2869   verifyFormat("@try {\n"
2870                "  // something\n"
2871                "}\n"
2872                "@finally {\n"
2873                "  // something\n"
2874                "}",
2875                Style);
2876   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
2877   verifyFormat("try\n"
2878                "{\n"
2879                "  // something\n"
2880                "}\n"
2881                "catch (...)\n"
2882                "{\n"
2883                "  // something\n"
2884                "}",
2885                Style);
2886   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
2887   verifyFormat("try\n"
2888                "  {\n"
2889                "  // something white\n"
2890                "  }\n"
2891                "catch (...)\n"
2892                "  {\n"
2893                "  // something white\n"
2894                "  }",
2895                Style);
2896   Style.BreakBeforeBraces = FormatStyle::BS_GNU;
2897   verifyFormat("try\n"
2898                "  {\n"
2899                "    // something\n"
2900                "  }\n"
2901                "catch (...)\n"
2902                "  {\n"
2903                "    // something\n"
2904                "  }",
2905                Style);
2906   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
2907   Style.BraceWrapping.BeforeCatch = true;
2908   verifyFormat("try {\n"
2909                "  // something\n"
2910                "}\n"
2911                "catch (...) {\n"
2912                "  // something\n"
2913                "}",
2914                Style);
2915 }
2916 
2917 TEST_F(FormatTest, StaticInitializers) {
2918   verifyFormat("static SomeClass SC = {1, 'a'};");
2919 
2920   verifyFormat("static SomeClass WithALoooooooooooooooooooongName = {\n"
2921                "    100000000, "
2922                "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"};");
2923 
2924   // Here, everything other than the "}" would fit on a line.
2925   verifyFormat("static int LooooooooooooooooooooooooongVariable[1] = {\n"
2926                "    10000000000000000000000000};");
2927   EXPECT_EQ("S s = {a,\n"
2928             "\n"
2929             "       b};",
2930             format("S s = {\n"
2931                    "  a,\n"
2932                    "\n"
2933                    "  b\n"
2934                    "};"));
2935 
2936   // FIXME: This would fit into the column limit if we'd fit "{ {" on the first
2937   // line. However, the formatting looks a bit off and this probably doesn't
2938   // happen often in practice.
2939   verifyFormat("static int Variable[1] = {\n"
2940                "    {1000000000000000000000000000000000000}};",
2941                getLLVMStyleWithColumns(40));
2942 }
2943 
2944 TEST_F(FormatTest, DesignatedInitializers) {
2945   verifyFormat("const struct A a = {.a = 1, .b = 2};");
2946   verifyFormat("const struct A a = {.aaaaaaaaaa = 1,\n"
2947                "                    .bbbbbbbbbb = 2,\n"
2948                "                    .cccccccccc = 3,\n"
2949                "                    .dddddddddd = 4,\n"
2950                "                    .eeeeeeeeee = 5};");
2951   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2952                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaa = 1,\n"
2953                "    .bbbbbbbbbbbbbbbbbbbbbbbbbbb = 2,\n"
2954                "    .ccccccccccccccccccccccccccc = 3,\n"
2955                "    .ddddddddddddddddddddddddddd = 4,\n"
2956                "    .eeeeeeeeeeeeeeeeeeeeeeeeeee = 5};");
2957 
2958   verifyGoogleFormat("const struct A a = {.a = 1, .b = 2};");
2959 
2960   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
2961   verifyFormat("const struct A a = {[1] = aaaaaaaaaa,\n"
2962                "                    [2] = bbbbbbbbbb,\n"
2963                "                    [3] = cccccccccc,\n"
2964                "                    [4] = dddddddddd,\n"
2965                "                    [5] = eeeeeeeeee};");
2966   verifyFormat("const struct Aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa = {\n"
2967                "    [1] = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
2968                "    [2] = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
2969                "    [3] = cccccccccccccccccccccccccccccccccccccc,\n"
2970                "    [4] = dddddddddddddddddddddddddddddddddddddd,\n"
2971                "    [5] = eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee};");
2972 }
2973 
2974 TEST_F(FormatTest, NestedStaticInitializers) {
2975   verifyFormat("static A x = {{{}}};\n");
2976   verifyFormat("static A x = {{{init1, init2, init3, init4},\n"
2977                "               {init1, init2, init3, init4}}};",
2978                getLLVMStyleWithColumns(50));
2979 
2980   verifyFormat("somes Status::global_reps[3] = {\n"
2981                "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2982                "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2983                "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};",
2984                getLLVMStyleWithColumns(60));
2985   verifyGoogleFormat("SomeType Status::global_reps[3] = {\n"
2986                      "    {kGlobalRef, OK_CODE, NULL, NULL, NULL},\n"
2987                      "    {kGlobalRef, CANCELLED_CODE, NULL, NULL, NULL},\n"
2988                      "    {kGlobalRef, UNKNOWN_CODE, NULL, NULL, NULL}};");
2989   verifyFormat("CGRect cg_rect = {{rect.fLeft, rect.fTop},\n"
2990                "                  {rect.fRight - rect.fLeft, rect.fBottom - "
2991                "rect.fTop}};");
2992 
2993   verifyFormat(
2994       "SomeArrayOfSomeType a = {\n"
2995       "    {{1, 2, 3},\n"
2996       "     {1, 2, 3},\n"
2997       "     {111111111111111111111111111111, 222222222222222222222222222222,\n"
2998       "      333333333333333333333333333333},\n"
2999       "     {1, 2, 3},\n"
3000       "     {1, 2, 3}}};");
3001   verifyFormat(
3002       "SomeArrayOfSomeType a = {\n"
3003       "    {{1, 2, 3}},\n"
3004       "    {{1, 2, 3}},\n"
3005       "    {{111111111111111111111111111111, 222222222222222222222222222222,\n"
3006       "      333333333333333333333333333333}},\n"
3007       "    {{1, 2, 3}},\n"
3008       "    {{1, 2, 3}}};");
3009 
3010   verifyFormat("struct {\n"
3011                "  unsigned bit;\n"
3012                "  const char *const name;\n"
3013                "} kBitsToOs[] = {{kOsMac, \"Mac\"},\n"
3014                "                 {kOsWin, \"Windows\"},\n"
3015                "                 {kOsLinux, \"Linux\"},\n"
3016                "                 {kOsCrOS, \"Chrome OS\"}};");
3017   verifyFormat("struct {\n"
3018                "  unsigned bit;\n"
3019                "  const char *const name;\n"
3020                "} kBitsToOs[] = {\n"
3021                "    {kOsMac, \"Mac\"},\n"
3022                "    {kOsWin, \"Windows\"},\n"
3023                "    {kOsLinux, \"Linux\"},\n"
3024                "    {kOsCrOS, \"Chrome OS\"},\n"
3025                "};");
3026 }
3027 
3028 TEST_F(FormatTest, FormatsSmallMacroDefinitionsInSingleLine) {
3029   verifyFormat("#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3030                "                      \\\n"
3031                "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)");
3032 }
3033 
3034 TEST_F(FormatTest, DoesNotBreakPureVirtualFunctionDefinition) {
3035   verifyFormat("virtual void write(ELFWriter *writerrr,\n"
3036                "                   OwningPtr<FileOutputBuffer> &buffer) = 0;");
3037 
3038   // Do break defaulted and deleted functions.
3039   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
3040                "    default;",
3041                getLLVMStyleWithColumns(40));
3042   verifyFormat("virtual void ~Deeeeeeeestructor() =\n"
3043                "    delete;",
3044                getLLVMStyleWithColumns(40));
3045 }
3046 
3047 TEST_F(FormatTest, BreaksStringLiteralsOnlyInDefine) {
3048   verifyFormat("# 1111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\" 2 3",
3049                getLLVMStyleWithColumns(40));
3050   verifyFormat("#line 11111 \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
3051                getLLVMStyleWithColumns(40));
3052   EXPECT_EQ("#define Q                              \\\n"
3053             "  \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/\"    \\\n"
3054             "  \"aaaaaaaa.cpp\"",
3055             format("#define Q \"/aaaaaaaaa/aaaaaaaaaaaaaaaaaaa/aaaaaaaa.cpp\"",
3056                    getLLVMStyleWithColumns(40)));
3057 }
3058 
3059 TEST_F(FormatTest, UnderstandsLinePPDirective) {
3060   EXPECT_EQ("# 123 \"A string literal\"",
3061             format("   #     123    \"A string literal\""));
3062 }
3063 
3064 TEST_F(FormatTest, LayoutUnknownPPDirective) {
3065   EXPECT_EQ("#;", format("#;"));
3066   verifyFormat("#\n;\n;\n;");
3067 }
3068 
3069 TEST_F(FormatTest, UnescapedEndOfLineEndsPPDirective) {
3070   EXPECT_EQ("#line 42 \"test\"\n",
3071             format("#  \\\n  line  \\\n  42  \\\n  \"test\"\n"));
3072   EXPECT_EQ("#define A B\n", format("#  \\\n define  \\\n    A  \\\n       B\n",
3073                                     getLLVMStyleWithColumns(12)));
3074 }
3075 
3076 TEST_F(FormatTest, EndOfFileEndsPPDirective) {
3077   EXPECT_EQ("#line 42 \"test\"",
3078             format("#  \\\n  line  \\\n  42  \\\n  \"test\""));
3079   EXPECT_EQ("#define A B", format("#  \\\n define  \\\n    A  \\\n       B"));
3080 }
3081 
3082 TEST_F(FormatTest, DoesntRemoveUnknownTokens) {
3083   verifyFormat("#define A \\x20");
3084   verifyFormat("#define A \\ x20");
3085   EXPECT_EQ("#define A \\ x20", format("#define A \\   x20"));
3086   verifyFormat("#define A ''");
3087   verifyFormat("#define A ''qqq");
3088   verifyFormat("#define A `qqq");
3089   verifyFormat("f(\"aaaa, bbbb, \"\\\"ccccc\\\"\");");
3090   EXPECT_EQ("const char *c = STRINGIFY(\n"
3091             "\\na : b);",
3092             format("const char * c = STRINGIFY(\n"
3093                    "\\na : b);"));
3094 
3095   verifyFormat("a\r\\");
3096   verifyFormat("a\v\\");
3097   verifyFormat("a\f\\");
3098 }
3099 
3100 TEST_F(FormatTest, IndentsPPDirectiveInReducedSpace) {
3101   verifyFormat("#define A(BB)", getLLVMStyleWithColumns(13));
3102   verifyFormat("#define A( \\\n    BB)", getLLVMStyleWithColumns(12));
3103   verifyFormat("#define A( \\\n    A, B)", getLLVMStyleWithColumns(12));
3104   // FIXME: We never break before the macro name.
3105   verifyFormat("#define AA( \\\n    B)", getLLVMStyleWithColumns(12));
3106 
3107   verifyFormat("#define A A\n#define A A");
3108   verifyFormat("#define A(X) A\n#define A A");
3109 
3110   verifyFormat("#define Something Other", getLLVMStyleWithColumns(23));
3111   verifyFormat("#define Something    \\\n  Other", getLLVMStyleWithColumns(22));
3112 }
3113 
3114 TEST_F(FormatTest, HandlePreprocessorDirectiveContext) {
3115   EXPECT_EQ("// somecomment\n"
3116             "#include \"a.h\"\n"
3117             "#define A(  \\\n"
3118             "    A, B)\n"
3119             "#include \"b.h\"\n"
3120             "// somecomment\n",
3121             format("  // somecomment\n"
3122                    "  #include \"a.h\"\n"
3123                    "#define A(A,\\\n"
3124                    "    B)\n"
3125                    "    #include \"b.h\"\n"
3126                    " // somecomment\n",
3127                    getLLVMStyleWithColumns(13)));
3128 }
3129 
3130 TEST_F(FormatTest, LayoutSingleHash) { EXPECT_EQ("#\na;", format("#\na;")); }
3131 
3132 TEST_F(FormatTest, LayoutCodeInMacroDefinitions) {
3133   EXPECT_EQ("#define A    \\\n"
3134             "  c;         \\\n"
3135             "  e;\n"
3136             "f;",
3137             format("#define A c; e;\n"
3138                    "f;",
3139                    getLLVMStyleWithColumns(14)));
3140 }
3141 
3142 TEST_F(FormatTest, LayoutRemainingTokens) { EXPECT_EQ("{}", format("{}")); }
3143 
3144 TEST_F(FormatTest, MacroDefinitionInsideStatement) {
3145   EXPECT_EQ("int x,\n"
3146             "#define A\n"
3147             "    y;",
3148             format("int x,\n#define A\ny;"));
3149 }
3150 
3151 TEST_F(FormatTest, HashInMacroDefinition) {
3152   EXPECT_EQ("#define A(c) L#c", format("#define A(c) L#c", getLLVMStyle()));
3153   verifyFormat("#define A \\\n  b #c;", getLLVMStyleWithColumns(11));
3154   verifyFormat("#define A  \\\n"
3155                "  {        \\\n"
3156                "    f(#c); \\\n"
3157                "  }",
3158                getLLVMStyleWithColumns(11));
3159 
3160   verifyFormat("#define A(X)         \\\n"
3161                "  void function##X()",
3162                getLLVMStyleWithColumns(22));
3163 
3164   verifyFormat("#define A(a, b, c)   \\\n"
3165                "  void a##b##c()",
3166                getLLVMStyleWithColumns(22));
3167 
3168   verifyFormat("#define A void # ## #", getLLVMStyleWithColumns(22));
3169 }
3170 
3171 TEST_F(FormatTest, RespectWhitespaceInMacroDefinitions) {
3172   EXPECT_EQ("#define A (x)", format("#define A (x)"));
3173   EXPECT_EQ("#define A(x)", format("#define A(x)"));
3174 
3175   FormatStyle Style = getLLVMStyle();
3176   Style.SpaceBeforeParens = FormatStyle::SBPO_Never;
3177   verifyFormat("#define true ((foo)1)", Style);
3178   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
3179   verifyFormat("#define false((foo)0)", Style);
3180 }
3181 
3182 TEST_F(FormatTest, EmptyLinesInMacroDefinitions) {
3183   EXPECT_EQ("#define A b;", format("#define A \\\n"
3184                                    "          \\\n"
3185                                    "  b;",
3186                                    getLLVMStyleWithColumns(25)));
3187   EXPECT_EQ("#define A \\\n"
3188             "          \\\n"
3189             "  a;      \\\n"
3190             "  b;",
3191             format("#define A \\\n"
3192                    "          \\\n"
3193                    "  a;      \\\n"
3194                    "  b;",
3195                    getLLVMStyleWithColumns(11)));
3196   EXPECT_EQ("#define A \\\n"
3197             "  a;      \\\n"
3198             "          \\\n"
3199             "  b;",
3200             format("#define A \\\n"
3201                    "  a;      \\\n"
3202                    "          \\\n"
3203                    "  b;",
3204                    getLLVMStyleWithColumns(11)));
3205 }
3206 
3207 TEST_F(FormatTest, MacroDefinitionsWithIncompleteCode) {
3208   verifyIncompleteFormat("#define A :");
3209   verifyFormat("#define SOMECASES  \\\n"
3210                "  case 1:          \\\n"
3211                "  case 2\n",
3212                getLLVMStyleWithColumns(20));
3213   verifyFormat("#define MACRO(a) \\\n"
3214                "  if (a)         \\\n"
3215                "    f();         \\\n"
3216                "  else           \\\n"
3217                "    g()",
3218                getLLVMStyleWithColumns(18));
3219   verifyFormat("#define A template <typename T>");
3220   verifyIncompleteFormat("#define STR(x) #x\n"
3221                          "f(STR(this_is_a_string_literal{));");
3222   verifyFormat("#pragma omp threadprivate( \\\n"
3223                "    y)), // expected-warning",
3224                getLLVMStyleWithColumns(28));
3225   verifyFormat("#d, = };");
3226   verifyFormat("#if \"a");
3227   verifyIncompleteFormat("({\n"
3228                          "#define b     \\\n"
3229                          "  }           \\\n"
3230                          "  a\n"
3231                          "a",
3232                          getLLVMStyleWithColumns(15));
3233   verifyFormat("#define A     \\\n"
3234                "  {           \\\n"
3235                "    {\n"
3236                "#define B     \\\n"
3237                "  }           \\\n"
3238                "  }",
3239                getLLVMStyleWithColumns(15));
3240   verifyNoCrash("#if a\na(\n#else\n#endif\n{a");
3241   verifyNoCrash("a={0,1\n#if a\n#else\n;\n#endif\n}");
3242   verifyNoCrash("#if a\na(\n#else\n#endif\n) a {a,b,c,d,f,g};");
3243   verifyNoCrash("#ifdef A\n a(\n #else\n #endif\n) = []() {      \n)}");
3244 }
3245 
3246 TEST_F(FormatTest, MacrosWithoutTrailingSemicolon) {
3247   verifyFormat("SOME_TYPE_NAME abc;"); // Gated on the newline.
3248   EXPECT_EQ("class A : public QObject {\n"
3249             "  Q_OBJECT\n"
3250             "\n"
3251             "  A() {}\n"
3252             "};",
3253             format("class A  :  public QObject {\n"
3254                    "     Q_OBJECT\n"
3255                    "\n"
3256                    "  A() {\n}\n"
3257                    "}  ;"));
3258   EXPECT_EQ("MACRO\n"
3259             "/*static*/ int i;",
3260             format("MACRO\n"
3261                    " /*static*/ int   i;"));
3262   EXPECT_EQ("SOME_MACRO\n"
3263             "namespace {\n"
3264             "void f();\n"
3265             "} // namespace",
3266             format("SOME_MACRO\n"
3267                    "  namespace    {\n"
3268                    "void   f(  );\n"
3269                    "} // namespace"));
3270   // Only if the identifier contains at least 5 characters.
3271   EXPECT_EQ("HTTP f();", format("HTTP\nf();"));
3272   EXPECT_EQ("MACRO\nf();", format("MACRO\nf();"));
3273   // Only if everything is upper case.
3274   EXPECT_EQ("class A : public QObject {\n"
3275             "  Q_Object A() {}\n"
3276             "};",
3277             format("class A  :  public QObject {\n"
3278                    "     Q_Object\n"
3279                    "  A() {\n}\n"
3280                    "}  ;"));
3281 
3282   // Only if the next line can actually start an unwrapped line.
3283   EXPECT_EQ("SOME_WEIRD_LOG_MACRO << SomeThing;",
3284             format("SOME_WEIRD_LOG_MACRO\n"
3285                    "<< SomeThing;"));
3286 
3287   verifyFormat("VISIT_GL_CALL(GenBuffers, void, (GLsizei n, GLuint* buffers), "
3288                "(n, buffers))\n",
3289                getChromiumStyle(FormatStyle::LK_Cpp));
3290 
3291   // See PR41483
3292   EXPECT_EQ("/**/ FOO(a)\n"
3293             "FOO(b)",
3294             format("/**/ FOO(a)\n"
3295                    "FOO(b)"));
3296 }
3297 
3298 TEST_F(FormatTest, MacroCallsWithoutTrailingSemicolon) {
3299   EXPECT_EQ("INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
3300             "INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
3301             "INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
3302             "class X {};\n"
3303             "INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
3304             "int *createScopDetectionPass() { return 0; }",
3305             format("  INITIALIZE_PASS_BEGIN(ScopDetection, \"polly-detect\")\n"
3306                    "  INITIALIZE_AG_DEPENDENCY(AliasAnalysis)\n"
3307                    "  INITIALIZE_PASS_DEPENDENCY(DominatorTree)\n"
3308                    "  class X {};\n"
3309                    "  INITIALIZE_PASS_END(ScopDetection, \"polly-detect\")\n"
3310                    "  int *createScopDetectionPass() { return 0; }"));
3311   // FIXME: We could probably treat IPC_BEGIN_MESSAGE_MAP/IPC_END_MESSAGE_MAP as
3312   // braces, so that inner block is indented one level more.
3313   EXPECT_EQ("int q() {\n"
3314             "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3315             "  IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3316             "  IPC_END_MESSAGE_MAP()\n"
3317             "}",
3318             format("int q() {\n"
3319                    "  IPC_BEGIN_MESSAGE_MAP(WebKitTestController, message)\n"
3320                    "    IPC_MESSAGE_HANDLER(xxx, qqq)\n"
3321                    "  IPC_END_MESSAGE_MAP()\n"
3322                    "}"));
3323 
3324   // Same inside macros.
3325   EXPECT_EQ("#define LIST(L) \\\n"
3326             "  L(A)          \\\n"
3327             "  L(B)          \\\n"
3328             "  L(C)",
3329             format("#define LIST(L) \\\n"
3330                    "  L(A) \\\n"
3331                    "  L(B) \\\n"
3332                    "  L(C)",
3333                    getGoogleStyle()));
3334 
3335   // These must not be recognized as macros.
3336   EXPECT_EQ("int q() {\n"
3337             "  f(x);\n"
3338             "  f(x) {}\n"
3339             "  f(x)->g();\n"
3340             "  f(x)->*g();\n"
3341             "  f(x).g();\n"
3342             "  f(x) = x;\n"
3343             "  f(x) += x;\n"
3344             "  f(x) -= x;\n"
3345             "  f(x) *= x;\n"
3346             "  f(x) /= x;\n"
3347             "  f(x) %= x;\n"
3348             "  f(x) &= x;\n"
3349             "  f(x) |= x;\n"
3350             "  f(x) ^= x;\n"
3351             "  f(x) >>= x;\n"
3352             "  f(x) <<= x;\n"
3353             "  f(x)[y].z();\n"
3354             "  LOG(INFO) << x;\n"
3355             "  ifstream(x) >> x;\n"
3356             "}\n",
3357             format("int q() {\n"
3358                    "  f(x)\n;\n"
3359                    "  f(x)\n {}\n"
3360                    "  f(x)\n->g();\n"
3361                    "  f(x)\n->*g();\n"
3362                    "  f(x)\n.g();\n"
3363                    "  f(x)\n = x;\n"
3364                    "  f(x)\n += x;\n"
3365                    "  f(x)\n -= x;\n"
3366                    "  f(x)\n *= x;\n"
3367                    "  f(x)\n /= x;\n"
3368                    "  f(x)\n %= x;\n"
3369                    "  f(x)\n &= x;\n"
3370                    "  f(x)\n |= x;\n"
3371                    "  f(x)\n ^= x;\n"
3372                    "  f(x)\n >>= x;\n"
3373                    "  f(x)\n <<= x;\n"
3374                    "  f(x)\n[y].z();\n"
3375                    "  LOG(INFO)\n << x;\n"
3376                    "  ifstream(x)\n >> x;\n"
3377                    "}\n"));
3378   EXPECT_EQ("int q() {\n"
3379             "  F(x)\n"
3380             "  if (1) {\n"
3381             "  }\n"
3382             "  F(x)\n"
3383             "  while (1) {\n"
3384             "  }\n"
3385             "  F(x)\n"
3386             "  G(x);\n"
3387             "  F(x)\n"
3388             "  try {\n"
3389             "    Q();\n"
3390             "  } catch (...) {\n"
3391             "  }\n"
3392             "}\n",
3393             format("int q() {\n"
3394                    "F(x)\n"
3395                    "if (1) {}\n"
3396                    "F(x)\n"
3397                    "while (1) {}\n"
3398                    "F(x)\n"
3399                    "G(x);\n"
3400                    "F(x)\n"
3401                    "try { Q(); } catch (...) {}\n"
3402                    "}\n"));
3403   EXPECT_EQ("class A {\n"
3404             "  A() : t(0) {}\n"
3405             "  A(int i) noexcept() : {}\n"
3406             "  A(X x)\n" // FIXME: function-level try blocks are broken.
3407             "  try : t(0) {\n"
3408             "  } catch (...) {\n"
3409             "  }\n"
3410             "};",
3411             format("class A {\n"
3412                    "  A()\n : t(0) {}\n"
3413                    "  A(int i)\n noexcept() : {}\n"
3414                    "  A(X x)\n"
3415                    "  try : t(0) {} catch (...) {}\n"
3416                    "};"));
3417   FormatStyle Style = getLLVMStyle();
3418   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
3419   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Always;
3420   Style.BraceWrapping.AfterFunction = true;
3421   EXPECT_EQ("void f()\n"
3422             "try\n"
3423             "{\n"
3424             "}",
3425             format("void f() try {\n"
3426                    "}",
3427                    Style));
3428   EXPECT_EQ("class SomeClass {\n"
3429             "public:\n"
3430             "  SomeClass() EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3431             "};",
3432             format("class SomeClass {\n"
3433                    "public:\n"
3434                    "  SomeClass()\n"
3435                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3436                    "};"));
3437   EXPECT_EQ("class SomeClass {\n"
3438             "public:\n"
3439             "  SomeClass()\n"
3440             "      EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3441             "};",
3442             format("class SomeClass {\n"
3443                    "public:\n"
3444                    "  SomeClass()\n"
3445                    "  EXCLUSIVE_LOCK_FUNCTION(mu_);\n"
3446                    "};",
3447                    getLLVMStyleWithColumns(40)));
3448 
3449   verifyFormat("MACRO(>)");
3450 
3451   // Some macros contain an implicit semicolon.
3452   Style = getLLVMStyle();
3453   Style.StatementMacros.push_back("FOO");
3454   verifyFormat("FOO(a) int b = 0;");
3455   verifyFormat("FOO(a)\n"
3456                "int b = 0;",
3457                Style);
3458   verifyFormat("FOO(a);\n"
3459                "int b = 0;",
3460                Style);
3461   verifyFormat("FOO(argc, argv, \"4.0.2\")\n"
3462                "int b = 0;",
3463                Style);
3464   verifyFormat("FOO()\n"
3465                "int b = 0;",
3466                Style);
3467   verifyFormat("FOO\n"
3468                "int b = 0;",
3469                Style);
3470   verifyFormat("void f() {\n"
3471                "  FOO(a)\n"
3472                "  return a;\n"
3473                "}",
3474                Style);
3475   verifyFormat("FOO(a)\n"
3476                "FOO(b)",
3477                Style);
3478   verifyFormat("int a = 0;\n"
3479                "FOO(b)\n"
3480                "int c = 0;",
3481                Style);
3482   verifyFormat("int a = 0;\n"
3483                "int x = FOO(a)\n"
3484                "int b = 0;",
3485                Style);
3486   verifyFormat("void foo(int a) { FOO(a) }\n"
3487                "uint32_t bar() {}",
3488                Style);
3489 }
3490 
3491 TEST_F(FormatTest, LayoutMacroDefinitionsStatementsSpanningBlocks) {
3492   verifyFormat("#define A \\\n"
3493                "  f({     \\\n"
3494                "    g();  \\\n"
3495                "  });",
3496                getLLVMStyleWithColumns(11));
3497 }
3498 
3499 TEST_F(FormatTest, IndentPreprocessorDirectives) {
3500   FormatStyle Style = getLLVMStyle();
3501   Style.IndentPPDirectives = FormatStyle::PPDIS_None;
3502   Style.ColumnLimit = 40;
3503   verifyFormat("#ifdef _WIN32\n"
3504                "#define A 0\n"
3505                "#ifdef VAR2\n"
3506                "#define B 1\n"
3507                "#include <someheader.h>\n"
3508                "#define MACRO                          \\\n"
3509                "  some_very_long_func_aaaaaaaaaa();\n"
3510                "#endif\n"
3511                "#else\n"
3512                "#define A 1\n"
3513                "#endif",
3514                Style);
3515   Style.IndentPPDirectives = FormatStyle::PPDIS_AfterHash;
3516   verifyFormat("#ifdef _WIN32\n"
3517                "#  define A 0\n"
3518                "#  ifdef VAR2\n"
3519                "#    define B 1\n"
3520                "#    include <someheader.h>\n"
3521                "#    define MACRO                      \\\n"
3522                "      some_very_long_func_aaaaaaaaaa();\n"
3523                "#  endif\n"
3524                "#else\n"
3525                "#  define A 1\n"
3526                "#endif",
3527                Style);
3528   verifyFormat("#if A\n"
3529                "#  define MACRO                        \\\n"
3530                "    void a(int x) {                    \\\n"
3531                "      b();                             \\\n"
3532                "      c();                             \\\n"
3533                "      d();                             \\\n"
3534                "      e();                             \\\n"
3535                "      f();                             \\\n"
3536                "    }\n"
3537                "#endif",
3538                Style);
3539   // Comments before include guard.
3540   verifyFormat("// file comment\n"
3541                "// file comment\n"
3542                "#ifndef HEADER_H\n"
3543                "#define HEADER_H\n"
3544                "code();\n"
3545                "#endif",
3546                Style);
3547   // Test with include guards.
3548   verifyFormat("#ifndef HEADER_H\n"
3549                "#define HEADER_H\n"
3550                "code();\n"
3551                "#endif",
3552                Style);
3553   // Include guards must have a #define with the same variable immediately
3554   // after #ifndef.
3555   verifyFormat("#ifndef NOT_GUARD\n"
3556                "#  define FOO\n"
3557                "code();\n"
3558                "#endif",
3559                Style);
3560 
3561   // Include guards must cover the entire file.
3562   verifyFormat("code();\n"
3563                "code();\n"
3564                "#ifndef NOT_GUARD\n"
3565                "#  define NOT_GUARD\n"
3566                "code();\n"
3567                "#endif",
3568                Style);
3569   verifyFormat("#ifndef NOT_GUARD\n"
3570                "#  define NOT_GUARD\n"
3571                "code();\n"
3572                "#endif\n"
3573                "code();",
3574                Style);
3575   // Test with trailing blank lines.
3576   verifyFormat("#ifndef HEADER_H\n"
3577                "#define HEADER_H\n"
3578                "code();\n"
3579                "#endif\n",
3580                Style);
3581   // Include guards don't have #else.
3582   verifyFormat("#ifndef NOT_GUARD\n"
3583                "#  define NOT_GUARD\n"
3584                "code();\n"
3585                "#else\n"
3586                "#endif",
3587                Style);
3588   verifyFormat("#ifndef NOT_GUARD\n"
3589                "#  define NOT_GUARD\n"
3590                "code();\n"
3591                "#elif FOO\n"
3592                "#endif",
3593                Style);
3594   // Non-identifier #define after potential include guard.
3595   verifyFormat("#ifndef FOO\n"
3596                "#  define 1\n"
3597                "#endif\n",
3598                Style);
3599   // #if closes past last non-preprocessor line.
3600   verifyFormat("#ifndef FOO\n"
3601                "#define FOO\n"
3602                "#if 1\n"
3603                "int i;\n"
3604                "#  define A 0\n"
3605                "#endif\n"
3606                "#endif\n",
3607                Style);
3608   // Don't crash if there is an #elif directive without a condition.
3609   verifyFormat("#if 1\n"
3610                "int x;\n"
3611                "#elif\n"
3612                "int y;\n"
3613                "#else\n"
3614                "int z;\n"
3615                "#endif",
3616                Style);
3617   // FIXME: This doesn't handle the case where there's code between the
3618   // #ifndef and #define but all other conditions hold. This is because when
3619   // the #define line is parsed, UnwrappedLineParser::Lines doesn't hold the
3620   // previous code line yet, so we can't detect it.
3621   EXPECT_EQ("#ifndef NOT_GUARD\n"
3622             "code();\n"
3623             "#define NOT_GUARD\n"
3624             "code();\n"
3625             "#endif",
3626             format("#ifndef NOT_GUARD\n"
3627                    "code();\n"
3628                    "#  define NOT_GUARD\n"
3629                    "code();\n"
3630                    "#endif",
3631                    Style));
3632   // FIXME: This doesn't handle cases where legitimate preprocessor lines may
3633   // be outside an include guard. Examples are #pragma once and
3634   // #pragma GCC diagnostic, or anything else that does not change the meaning
3635   // of the file if it's included multiple times.
3636   EXPECT_EQ("#ifdef WIN32\n"
3637             "#  pragma once\n"
3638             "#endif\n"
3639             "#ifndef HEADER_H\n"
3640             "#  define HEADER_H\n"
3641             "code();\n"
3642             "#endif",
3643             format("#ifdef WIN32\n"
3644                    "#  pragma once\n"
3645                    "#endif\n"
3646                    "#ifndef HEADER_H\n"
3647                    "#define HEADER_H\n"
3648                    "code();\n"
3649                    "#endif",
3650                    Style));
3651   // FIXME: This does not detect when there is a single non-preprocessor line
3652   // in front of an include-guard-like structure where other conditions hold
3653   // because ScopedLineState hides the line.
3654   EXPECT_EQ("code();\n"
3655             "#ifndef HEADER_H\n"
3656             "#define HEADER_H\n"
3657             "code();\n"
3658             "#endif",
3659             format("code();\n"
3660                    "#ifndef HEADER_H\n"
3661                    "#  define HEADER_H\n"
3662                    "code();\n"
3663                    "#endif",
3664                    Style));
3665   // Keep comments aligned with #, otherwise indent comments normally. These
3666   // tests cannot use verifyFormat because messUp manipulates leading
3667   // whitespace.
3668   {
3669     const char *Expected = ""
3670                            "void f() {\n"
3671                            "#if 1\n"
3672                            "// Preprocessor aligned.\n"
3673                            "#  define A 0\n"
3674                            "  // Code. Separated by blank line.\n"
3675                            "\n"
3676                            "#  define B 0\n"
3677                            "  // Code. Not aligned with #\n"
3678                            "#  define C 0\n"
3679                            "#endif";
3680     const char *ToFormat = ""
3681                            "void f() {\n"
3682                            "#if 1\n"
3683                            "// Preprocessor aligned.\n"
3684                            "#  define A 0\n"
3685                            "// Code. Separated by blank line.\n"
3686                            "\n"
3687                            "#  define B 0\n"
3688                            "   // Code. Not aligned with #\n"
3689                            "#  define C 0\n"
3690                            "#endif";
3691     EXPECT_EQ(Expected, format(ToFormat, Style));
3692     EXPECT_EQ(Expected, format(Expected, Style));
3693   }
3694   // Keep block quotes aligned.
3695   {
3696     const char *Expected = ""
3697                            "void f() {\n"
3698                            "#if 1\n"
3699                            "/* Preprocessor aligned. */\n"
3700                            "#  define A 0\n"
3701                            "  /* Code. Separated by blank line. */\n"
3702                            "\n"
3703                            "#  define B 0\n"
3704                            "  /* Code. Not aligned with # */\n"
3705                            "#  define C 0\n"
3706                            "#endif";
3707     const char *ToFormat = ""
3708                            "void f() {\n"
3709                            "#if 1\n"
3710                            "/* Preprocessor aligned. */\n"
3711                            "#  define A 0\n"
3712                            "/* Code. Separated by blank line. */\n"
3713                            "\n"
3714                            "#  define B 0\n"
3715                            "   /* Code. Not aligned with # */\n"
3716                            "#  define C 0\n"
3717                            "#endif";
3718     EXPECT_EQ(Expected, format(ToFormat, Style));
3719     EXPECT_EQ(Expected, format(Expected, Style));
3720   }
3721   // Keep comments aligned with un-indented directives.
3722   {
3723     const char *Expected = ""
3724                            "void f() {\n"
3725                            "// Preprocessor aligned.\n"
3726                            "#define A 0\n"
3727                            "  // Code. Separated by blank line.\n"
3728                            "\n"
3729                            "#define B 0\n"
3730                            "  // Code. Not aligned with #\n"
3731                            "#define C 0\n";
3732     const char *ToFormat = ""
3733                            "void f() {\n"
3734                            "// Preprocessor aligned.\n"
3735                            "#define A 0\n"
3736                            "// Code. Separated by blank line.\n"
3737                            "\n"
3738                            "#define B 0\n"
3739                            "   // Code. Not aligned with #\n"
3740                            "#define C 0\n";
3741     EXPECT_EQ(Expected, format(ToFormat, Style));
3742     EXPECT_EQ(Expected, format(Expected, Style));
3743   }
3744   // Test AfterHash with tabs.
3745   {
3746     FormatStyle Tabbed = Style;
3747     Tabbed.UseTab = FormatStyle::UT_Always;
3748     Tabbed.IndentWidth = 8;
3749     Tabbed.TabWidth = 8;
3750     verifyFormat("#ifdef _WIN32\n"
3751                  "#\tdefine A 0\n"
3752                  "#\tifdef VAR2\n"
3753                  "#\t\tdefine B 1\n"
3754                  "#\t\tinclude <someheader.h>\n"
3755                  "#\t\tdefine MACRO          \\\n"
3756                  "\t\t\tsome_very_long_func_aaaaaaaaaa();\n"
3757                  "#\tendif\n"
3758                  "#else\n"
3759                  "#\tdefine A 1\n"
3760                  "#endif",
3761                  Tabbed);
3762   }
3763 
3764   // Regression test: Multiline-macro inside include guards.
3765   verifyFormat("#ifndef HEADER_H\n"
3766                "#define HEADER_H\n"
3767                "#define A()        \\\n"
3768                "  int i;           \\\n"
3769                "  int j;\n"
3770                "#endif // HEADER_H",
3771                getLLVMStyleWithColumns(20));
3772 
3773   Style.IndentPPDirectives = FormatStyle::PPDIS_BeforeHash;
3774   // Basic before hash indent tests
3775   verifyFormat("#ifdef _WIN32\n"
3776                "  #define A 0\n"
3777                "  #ifdef VAR2\n"
3778                "    #define B 1\n"
3779                "    #include <someheader.h>\n"
3780                "    #define MACRO                      \\\n"
3781                "      some_very_long_func_aaaaaaaaaa();\n"
3782                "  #endif\n"
3783                "#else\n"
3784                "  #define A 1\n"
3785                "#endif",
3786                Style);
3787   verifyFormat("#if A\n"
3788                "  #define MACRO                        \\\n"
3789                "    void a(int x) {                    \\\n"
3790                "      b();                             \\\n"
3791                "      c();                             \\\n"
3792                "      d();                             \\\n"
3793                "      e();                             \\\n"
3794                "      f();                             \\\n"
3795                "    }\n"
3796                "#endif",
3797                Style);
3798   // Keep comments aligned with indented directives. These
3799   // tests cannot use verifyFormat because messUp manipulates leading
3800   // whitespace.
3801   {
3802     const char *Expected = "void f() {\n"
3803                            "// Aligned to preprocessor.\n"
3804                            "#if 1\n"
3805                            "  // Aligned to code.\n"
3806                            "  int a;\n"
3807                            "  #if 1\n"
3808                            "    // Aligned to preprocessor.\n"
3809                            "    #define A 0\n"
3810                            "  // Aligned to code.\n"
3811                            "  int b;\n"
3812                            "  #endif\n"
3813                            "#endif\n"
3814                            "}";
3815     const char *ToFormat = "void f() {\n"
3816                            "// Aligned to preprocessor.\n"
3817                            "#if 1\n"
3818                            "// Aligned to code.\n"
3819                            "int a;\n"
3820                            "#if 1\n"
3821                            "// Aligned to preprocessor.\n"
3822                            "#define A 0\n"
3823                            "// Aligned to code.\n"
3824                            "int b;\n"
3825                            "#endif\n"
3826                            "#endif\n"
3827                            "}";
3828     EXPECT_EQ(Expected, format(ToFormat, Style));
3829     EXPECT_EQ(Expected, format(Expected, Style));
3830   }
3831   {
3832     const char *Expected = "void f() {\n"
3833                            "/* Aligned to preprocessor. */\n"
3834                            "#if 1\n"
3835                            "  /* Aligned to code. */\n"
3836                            "  int a;\n"
3837                            "  #if 1\n"
3838                            "    /* Aligned to preprocessor. */\n"
3839                            "    #define A 0\n"
3840                            "  /* Aligned to code. */\n"
3841                            "  int b;\n"
3842                            "  #endif\n"
3843                            "#endif\n"
3844                            "}";
3845     const char *ToFormat = "void f() {\n"
3846                            "/* Aligned to preprocessor. */\n"
3847                            "#if 1\n"
3848                            "/* Aligned to code. */\n"
3849                            "int a;\n"
3850                            "#if 1\n"
3851                            "/* Aligned to preprocessor. */\n"
3852                            "#define A 0\n"
3853                            "/* Aligned to code. */\n"
3854                            "int b;\n"
3855                            "#endif\n"
3856                            "#endif\n"
3857                            "}";
3858     EXPECT_EQ(Expected, format(ToFormat, Style));
3859     EXPECT_EQ(Expected, format(Expected, Style));
3860   }
3861 
3862   // Test single comment before preprocessor
3863   verifyFormat("// Comment\n"
3864                "\n"
3865                "#if 1\n"
3866                "#endif",
3867                Style);
3868 }
3869 
3870 TEST_F(FormatTest, FormatHashIfNotAtStartOfLine) {
3871   verifyFormat("{\n  { a #c; }\n}");
3872 }
3873 
3874 TEST_F(FormatTest, FormatUnbalancedStructuralElements) {
3875   EXPECT_EQ("#define A \\\n  {       \\\n    {\nint i;",
3876             format("#define A { {\nint i;", getLLVMStyleWithColumns(11)));
3877   EXPECT_EQ("#define A \\\n  }       \\\n  }\nint i;",
3878             format("#define A } }\nint i;", getLLVMStyleWithColumns(11)));
3879 }
3880 
3881 TEST_F(FormatTest, EscapedNewlines) {
3882   FormatStyle Narrow = getLLVMStyleWithColumns(11);
3883   EXPECT_EQ("#define A \\\n  int i;  \\\n  int j;",
3884             format("#define A \\\nint i;\\\n  int j;", Narrow));
3885   EXPECT_EQ("#define A\n\nint i;", format("#define A \\\n\n int i;"));
3886   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3887   EXPECT_EQ("/* \\  \\  \\\n */", format("\\\n/* \\  \\  \\\n */"));
3888   EXPECT_EQ("<a\n\\\\\n>", format("<a\n\\\\\n>"));
3889 
3890   FormatStyle AlignLeft = getLLVMStyle();
3891   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
3892   EXPECT_EQ("#define MACRO(x) \\\n"
3893             "private:         \\\n"
3894             "  int x(int a);\n",
3895             format("#define MACRO(x) \\\n"
3896                    "private:         \\\n"
3897                    "  int x(int a);\n",
3898                    AlignLeft));
3899 
3900   // CRLF line endings
3901   EXPECT_EQ("#define A \\\r\n  int i;  \\\r\n  int j;",
3902             format("#define A \\\r\nint i;\\\r\n  int j;", Narrow));
3903   EXPECT_EQ("#define A\r\n\r\nint i;", format("#define A \\\r\n\r\n int i;"));
3904   EXPECT_EQ("template <class T> f();", format("\\\ntemplate <class T> f();"));
3905   EXPECT_EQ("/* \\  \\  \\\r\n */", format("\\\r\n/* \\  \\  \\\r\n */"));
3906   EXPECT_EQ("<a\r\n\\\\\r\n>", format("<a\r\n\\\\\r\n>"));
3907   EXPECT_EQ("#define MACRO(x) \\\r\n"
3908             "private:         \\\r\n"
3909             "  int x(int a);\r\n",
3910             format("#define MACRO(x) \\\r\n"
3911                    "private:         \\\r\n"
3912                    "  int x(int a);\r\n",
3913                    AlignLeft));
3914 
3915   FormatStyle DontAlign = getLLVMStyle();
3916   DontAlign.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
3917   DontAlign.MaxEmptyLinesToKeep = 3;
3918   // FIXME: can't use verifyFormat here because the newline before
3919   // "public:" is not inserted the first time it's reformatted
3920   EXPECT_EQ("#define A \\\n"
3921             "  class Foo { \\\n"
3922             "    void bar(); \\\n"
3923             "\\\n"
3924             "\\\n"
3925             "\\\n"
3926             "  public: \\\n"
3927             "    void baz(); \\\n"
3928             "  };",
3929             format("#define A \\\n"
3930                    "  class Foo { \\\n"
3931                    "    void bar(); \\\n"
3932                    "\\\n"
3933                    "\\\n"
3934                    "\\\n"
3935                    "  public: \\\n"
3936                    "    void baz(); \\\n"
3937                    "  };",
3938                    DontAlign));
3939 }
3940 
3941 TEST_F(FormatTest, CalculateSpaceOnConsecutiveLinesInMacro) {
3942   verifyFormat("#define A \\\n"
3943                "  int v(  \\\n"
3944                "      a); \\\n"
3945                "  int i;",
3946                getLLVMStyleWithColumns(11));
3947 }
3948 
3949 TEST_F(FormatTest, MixingPreprocessorDirectivesAndNormalCode) {
3950   EXPECT_EQ(
3951       "#define ALooooooooooooooooooooooooooooooooooooooongMacro("
3952       "                      \\\n"
3953       "    aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3954       "\n"
3955       "AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3956       "    aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n",
3957       format("  #define   ALooooooooooooooooooooooooooooooooooooooongMacro("
3958              "\\\n"
3959              "aLoooooooooooooooooooooooongFuuuuuuuuuuuuuunctiooooooooo)\n"
3960              "  \n"
3961              "   AlooooooooooooooooooooooooooooooooooooooongCaaaaaaaaaal(\n"
3962              "  aLooooooooooooooooooooooonPaaaaaaaaaaaaaaaaaaaaarmmmm);\n"));
3963 }
3964 
3965 TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) {
3966   EXPECT_EQ("int\n"
3967             "#define A\n"
3968             "    a;",
3969             format("int\n#define A\na;"));
3970   verifyFormat("functionCallTo(\n"
3971                "    someOtherFunction(\n"
3972                "        withSomeParameters, whichInSequence,\n"
3973                "        areLongerThanALine(andAnotherCall,\n"
3974                "#define A B\n"
3975                "                           withMoreParamters,\n"
3976                "                           whichStronglyInfluenceTheLayout),\n"
3977                "        andMoreParameters),\n"
3978                "    trailing);",
3979                getLLVMStyleWithColumns(69));
3980   verifyFormat("Foo::Foo()\n"
3981                "#ifdef BAR\n"
3982                "    : baz(0)\n"
3983                "#endif\n"
3984                "{\n"
3985                "}");
3986   verifyFormat("void f() {\n"
3987                "  if (true)\n"
3988                "#ifdef A\n"
3989                "    f(42);\n"
3990                "  x();\n"
3991                "#else\n"
3992                "    g();\n"
3993                "  x();\n"
3994                "#endif\n"
3995                "}");
3996   verifyFormat("void f(param1, param2,\n"
3997                "       param3,\n"
3998                "#ifdef A\n"
3999                "       param4(param5,\n"
4000                "#ifdef A1\n"
4001                "              param6,\n"
4002                "#ifdef A2\n"
4003                "              param7),\n"
4004                "#else\n"
4005                "              param8),\n"
4006                "       param9,\n"
4007                "#endif\n"
4008                "       param10,\n"
4009                "#endif\n"
4010                "       param11)\n"
4011                "#else\n"
4012                "       param12)\n"
4013                "#endif\n"
4014                "{\n"
4015                "  x();\n"
4016                "}",
4017                getLLVMStyleWithColumns(28));
4018   verifyFormat("#if 1\n"
4019                "int i;");
4020   verifyFormat("#if 1\n"
4021                "#endif\n"
4022                "#if 1\n"
4023                "#else\n"
4024                "#endif\n");
4025   verifyFormat("DEBUG({\n"
4026                "  return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4027                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;\n"
4028                "});\n"
4029                "#if a\n"
4030                "#else\n"
4031                "#endif");
4032 
4033   verifyIncompleteFormat("void f(\n"
4034                          "#if A\n"
4035                          ");\n"
4036                          "#else\n"
4037                          "#endif");
4038 }
4039 
4040 TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) {
4041   verifyFormat("#endif\n"
4042                "#if B");
4043 }
4044 
4045 TEST_F(FormatTest, FormatsJoinedLinesOnSubsequentRuns) {
4046   FormatStyle SingleLine = getLLVMStyle();
4047   SingleLine.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_WithoutElse;
4048   verifyFormat("#if 0\n"
4049                "#elif 1\n"
4050                "#endif\n"
4051                "void foo() {\n"
4052                "  if (test) foo2();\n"
4053                "}",
4054                SingleLine);
4055 }
4056 
4057 TEST_F(FormatTest, LayoutBlockInsideParens) {
4058   verifyFormat("functionCall({ int i; });");
4059   verifyFormat("functionCall({\n"
4060                "  int i;\n"
4061                "  int j;\n"
4062                "});");
4063   verifyFormat("functionCall(\n"
4064                "    {\n"
4065                "      int i;\n"
4066                "      int j;\n"
4067                "    },\n"
4068                "    aaaa, bbbb, cccc);");
4069   verifyFormat("functionA(functionB({\n"
4070                "            int i;\n"
4071                "            int j;\n"
4072                "          }),\n"
4073                "          aaaa, bbbb, cccc);");
4074   verifyFormat("functionCall(\n"
4075                "    {\n"
4076                "      int i;\n"
4077                "      int j;\n"
4078                "    },\n"
4079                "    aaaa, bbbb, // comment\n"
4080                "    cccc);");
4081   verifyFormat("functionA(functionB({\n"
4082                "            int i;\n"
4083                "            int j;\n"
4084                "          }),\n"
4085                "          aaaa, bbbb, // comment\n"
4086                "          cccc);");
4087   verifyFormat("functionCall(aaaa, bbbb, { int i; });");
4088   verifyFormat("functionCall(aaaa, bbbb, {\n"
4089                "  int i;\n"
4090                "  int j;\n"
4091                "});");
4092   verifyFormat(
4093       "Aaa(\n" // FIXME: There shouldn't be a linebreak here.
4094       "    {\n"
4095       "      int i; // break\n"
4096       "    },\n"
4097       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
4098       "                                     ccccccccccccccccc));");
4099   verifyFormat("DEBUG({\n"
4100                "  if (a)\n"
4101                "    f();\n"
4102                "});");
4103 }
4104 
4105 TEST_F(FormatTest, LayoutBlockInsideStatement) {
4106   EXPECT_EQ("SOME_MACRO { int i; }\n"
4107             "int i;",
4108             format("  SOME_MACRO  {int i;}  int i;"));
4109 }
4110 
4111 TEST_F(FormatTest, LayoutNestedBlocks) {
4112   verifyFormat("void AddOsStrings(unsigned bitmask) {\n"
4113                "  struct s {\n"
4114                "    int i;\n"
4115                "  };\n"
4116                "  s kBitsToOs[] = {{10}};\n"
4117                "  for (int i = 0; i < 10; ++i)\n"
4118                "    return;\n"
4119                "}");
4120   verifyFormat("call(parameter, {\n"
4121                "  something();\n"
4122                "  // Comment using all columns.\n"
4123                "  somethingelse();\n"
4124                "});",
4125                getLLVMStyleWithColumns(40));
4126   verifyFormat("DEBUG( //\n"
4127                "    { f(); }, a);");
4128   verifyFormat("DEBUG( //\n"
4129                "    {\n"
4130                "      f(); //\n"
4131                "    },\n"
4132                "    a);");
4133 
4134   EXPECT_EQ("call(parameter, {\n"
4135             "  something();\n"
4136             "  // Comment too\n"
4137             "  // looooooooooong.\n"
4138             "  somethingElse();\n"
4139             "});",
4140             format("call(parameter, {\n"
4141                    "  something();\n"
4142                    "  // Comment too looooooooooong.\n"
4143                    "  somethingElse();\n"
4144                    "});",
4145                    getLLVMStyleWithColumns(29)));
4146   EXPECT_EQ("DEBUG({ int i; });", format("DEBUG({ int   i; });"));
4147   EXPECT_EQ("DEBUG({ // comment\n"
4148             "  int i;\n"
4149             "});",
4150             format("DEBUG({ // comment\n"
4151                    "int  i;\n"
4152                    "});"));
4153   EXPECT_EQ("DEBUG({\n"
4154             "  int i;\n"
4155             "\n"
4156             "  // comment\n"
4157             "  int j;\n"
4158             "});",
4159             format("DEBUG({\n"
4160                    "  int  i;\n"
4161                    "\n"
4162                    "  // comment\n"
4163                    "  int  j;\n"
4164                    "});"));
4165 
4166   verifyFormat("DEBUG({\n"
4167                "  if (a)\n"
4168                "    return;\n"
4169                "});");
4170   verifyGoogleFormat("DEBUG({\n"
4171                      "  if (a) return;\n"
4172                      "});");
4173   FormatStyle Style = getGoogleStyle();
4174   Style.ColumnLimit = 45;
4175   verifyFormat("Debug(\n"
4176                "    aaaaa,\n"
4177                "    {\n"
4178                "      if (aaaaaaaaaaaaaaaaaaaaaaaa) return;\n"
4179                "    },\n"
4180                "    a);",
4181                Style);
4182 
4183   verifyFormat("SomeFunction({MACRO({ return output; }), b});");
4184 
4185   verifyNoCrash("^{v^{a}}");
4186 }
4187 
4188 TEST_F(FormatTest, FormatNestedBlocksInMacros) {
4189   EXPECT_EQ("#define MACRO()                     \\\n"
4190             "  Debug(aaa, /* force line break */ \\\n"
4191             "        {                           \\\n"
4192             "          int i;                    \\\n"
4193             "          int j;                    \\\n"
4194             "        })",
4195             format("#define   MACRO()   Debug(aaa,  /* force line break */ \\\n"
4196                    "          {  int   i;  int  j;   })",
4197                    getGoogleStyle()));
4198 
4199   EXPECT_EQ("#define A                                       \\\n"
4200             "  [] {                                          \\\n"
4201             "    xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx(        \\\n"
4202             "        xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); \\\n"
4203             "  }",
4204             format("#define A [] { xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx( \\\n"
4205                    "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx); }",
4206                    getGoogleStyle()));
4207 }
4208 
4209 TEST_F(FormatTest, PutEmptyBlocksIntoOneLine) {
4210   EXPECT_EQ("{}", format("{}"));
4211   verifyFormat("enum E {};");
4212   verifyFormat("enum E {}");
4213   FormatStyle Style = getLLVMStyle();
4214   Style.SpaceInEmptyBlock = true;
4215   EXPECT_EQ("void f() { }", format("void f() {}", Style));
4216   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
4217   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
4218 }
4219 
4220 TEST_F(FormatTest, FormatBeginBlockEndMacros) {
4221   FormatStyle Style = getLLVMStyle();
4222   Style.MacroBlockBegin = "^[A-Z_]+_BEGIN$";
4223   Style.MacroBlockEnd = "^[A-Z_]+_END$";
4224   verifyFormat("FOO_BEGIN\n"
4225                "  FOO_ENTRY\n"
4226                "FOO_END",
4227                Style);
4228   verifyFormat("FOO_BEGIN\n"
4229                "  NESTED_FOO_BEGIN\n"
4230                "    NESTED_FOO_ENTRY\n"
4231                "  NESTED_FOO_END\n"
4232                "FOO_END",
4233                Style);
4234   verifyFormat("FOO_BEGIN(Foo, Bar)\n"
4235                "  int x;\n"
4236                "  x = 1;\n"
4237                "FOO_END(Baz)",
4238                Style);
4239 }
4240 
4241 //===----------------------------------------------------------------------===//
4242 // Line break tests.
4243 //===----------------------------------------------------------------------===//
4244 
4245 TEST_F(FormatTest, PreventConfusingIndents) {
4246   verifyFormat(
4247       "void f() {\n"
4248       "  SomeLongMethodName(SomeReallyLongMethod(CallOtherReallyLongMethod(\n"
4249       "                         parameter, parameter, parameter)),\n"
4250       "                     SecondLongCall(parameter));\n"
4251       "}");
4252   verifyFormat(
4253       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4254       "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4255       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4256       "    aaaaaaaaaaaaaaaaaaaaaaaa);");
4257   verifyFormat(
4258       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4259       "    [aaaaaaaaaaaaaaaaaaaaaaaa\n"
4260       "         [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
4261       "         [aaaaaaaaaaaaaaaaaaaaaaaa]];");
4262   verifyFormat(
4263       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
4264       "    aaaaaaaaaaaaaaaaaaaaaaaa<\n"
4265       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>,\n"
4266       "    aaaaaaaaaaaaaaaaaaaaaaaa>;");
4267   verifyFormat("int a = bbbb && ccc &&\n"
4268                "        fffff(\n"
4269                "#define A Just forcing a new line\n"
4270                "            ddd);");
4271 }
4272 
4273 TEST_F(FormatTest, LineBreakingInBinaryExpressions) {
4274   verifyFormat(
4275       "bool aaaaaaa =\n"
4276       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() ||\n"
4277       "    bbbbbbbb();");
4278   verifyFormat(
4279       "bool aaaaaaa =\n"
4280       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaa).aaaaaaaaaaaaaaaaaaa() or\n"
4281       "    bbbbbbbb();");
4282 
4283   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
4284                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb &&\n"
4285                "    ccccccccc == ddddddddddd;");
4286   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaa =\n"
4287                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa != bbbbbbbbbbbbbbbbbb and\n"
4288                "    ccccccccc == ddddddddddd;");
4289   verifyFormat(
4290       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
4291       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa not_eq bbbbbbbbbbbbbbbbbb and\n"
4292       "    ccccccccc == ddddddddddd;");
4293 
4294   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
4295                "                 aaaaaa) &&\n"
4296                "         bbbbbb && cccccc;");
4297   verifyFormat("aaaaaa = aaaaaaa(aaaaaaa, // break\n"
4298                "                 aaaaaa) >>\n"
4299                "         bbbbbb;");
4300   verifyFormat("aa = Whitespaces.addUntouchableComment(\n"
4301                "    SourceMgr.getSpellingColumnNumber(\n"
4302                "        TheLine.Last->FormatTok.Tok.getLocation()) -\n"
4303                "    1);");
4304 
4305   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4306                "     bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaaaaaaa\n"
4307                "    cccccc) {\n}");
4308   verifyFormat("if constexpr ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4309                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
4310                "              cccccc) {\n}");
4311   verifyFormat("if CONSTEXPR ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4312                "               bbbbbbbbbbbbbbbbbb) && // aaaaaaaaaaa\n"
4313                "              cccccc) {\n}");
4314   verifyFormat("b = a &&\n"
4315                "    // Comment\n"
4316                "    b.c && d;");
4317 
4318   // If the LHS of a comparison is not a binary expression itself, the
4319   // additional linebreak confuses many people.
4320   verifyFormat(
4321       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4322       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) > 5) {\n"
4323       "}");
4324   verifyFormat(
4325       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4326       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4327       "}");
4328   verifyFormat(
4329       "if (aaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa(\n"
4330       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4331       "}");
4332   verifyFormat(
4333       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4334       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) <=> 5) {\n"
4335       "}");
4336   // Even explicit parentheses stress the precedence enough to make the
4337   // additional break unnecessary.
4338   verifyFormat("if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4339                "     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) == 5) {\n"
4340                "}");
4341   // This cases is borderline, but with the indentation it is still readable.
4342   verifyFormat(
4343       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4344       "        aaaaaaaaaaaaaaa) > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4345       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
4346       "}",
4347       getLLVMStyleWithColumns(75));
4348 
4349   // If the LHS is a binary expression, we should still use the additional break
4350   // as otherwise the formatting hides the operator precedence.
4351   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4352                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4353                "    5) {\n"
4354                "}");
4355   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4356                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa <=>\n"
4357                "    5) {\n"
4358                "}");
4359 
4360   FormatStyle OnePerLine = getLLVMStyle();
4361   OnePerLine.BinPackParameters = false;
4362   verifyFormat(
4363       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4364       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
4365       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}",
4366       OnePerLine);
4367 
4368   verifyFormat("int i = someFunction(aaaaaaa, 0)\n"
4369                "                .aaa(aaaaaaaaaaaaa) *\n"
4370                "            aaaaaaa +\n"
4371                "        aaaaaaa;",
4372                getLLVMStyleWithColumns(40));
4373 }
4374 
4375 TEST_F(FormatTest, ExpressionIndentation) {
4376   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4377                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4378                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4379                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4380                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
4381                "                     bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb &&\n"
4382                "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4383                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >\n"
4384                "                 ccccccccccccccccccccccccccccccccccccccccc;");
4385   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4386                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4387                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4388                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4389   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4390                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4391                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4392                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4393   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ==\n"
4394                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *\n"
4395                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4396                "        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}");
4397   verifyFormat("if () {\n"
4398                "} else if (aaaaa && bbbbb > // break\n"
4399                "                        ccccc) {\n"
4400                "}");
4401   verifyFormat("if () {\n"
4402                "} else if constexpr (aaaaa && bbbbb > // break\n"
4403                "                                  ccccc) {\n"
4404                "}");
4405   verifyFormat("if () {\n"
4406                "} else if CONSTEXPR (aaaaa && bbbbb > // break\n"
4407                "                                  ccccc) {\n"
4408                "}");
4409   verifyFormat("if () {\n"
4410                "} else if (aaaaa &&\n"
4411                "           bbbbb > // break\n"
4412                "               ccccc &&\n"
4413                "           ddddd) {\n"
4414                "}");
4415 
4416   // Presence of a trailing comment used to change indentation of b.
4417   verifyFormat("return aaaaaaaaaaaaaaaaaaa +\n"
4418                "       b;\n"
4419                "return aaaaaaaaaaaaaaaaaaa +\n"
4420                "       b; //",
4421                getLLVMStyleWithColumns(30));
4422 }
4423 
4424 TEST_F(FormatTest, ExpressionIndentationBreakingBeforeOperators) {
4425   // Not sure what the best system is here. Like this, the LHS can be found
4426   // immediately above an operator (everything with the same or a higher
4427   // indent). The RHS is aligned right of the operator and so compasses
4428   // everything until something with the same indent as the operator is found.
4429   // FIXME: Is this a good system?
4430   FormatStyle Style = getLLVMStyle();
4431   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
4432   verifyFormat(
4433       "bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4434       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4435       "                     + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4436       "                 == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4437       "                            * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4438       "                        + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4439       "             && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4440       "                        * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4441       "                    > ccccccccccccccccccccccccccccccccccccccccc;",
4442       Style);
4443   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4444                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4445                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4446                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4447                Style);
4448   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4449                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4450                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4451                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4452                Style);
4453   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4454                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4455                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4456                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4457                Style);
4458   verifyFormat("if () {\n"
4459                "} else if (aaaaa\n"
4460                "           && bbbbb // break\n"
4461                "                  > ccccc) {\n"
4462                "}",
4463                Style);
4464   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4465                "       && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4466                Style);
4467   verifyFormat("return (a)\n"
4468                "       // comment\n"
4469                "       + b;",
4470                Style);
4471   verifyFormat(
4472       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4473       "                 * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4474       "             + cc;",
4475       Style);
4476 
4477   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4478                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4479                Style);
4480 
4481   // Forced by comments.
4482   verifyFormat(
4483       "unsigned ContentSize =\n"
4484       "    sizeof(int16_t)   // DWARF ARange version number\n"
4485       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4486       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4487       "    + sizeof(int8_t); // Segment Size (in bytes)");
4488 
4489   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
4490                "       == boost::fusion::at_c<1>(iiii).second;",
4491                Style);
4492 
4493   Style.ColumnLimit = 60;
4494   verifyFormat("zzzzzzzzzz\n"
4495                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4496                "      >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
4497                Style);
4498 
4499   Style.ColumnLimit = 80;
4500   Style.IndentWidth = 4;
4501   Style.TabWidth = 4;
4502   Style.UseTab = FormatStyle::UT_Always;
4503   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4504   Style.AlignOperands = FormatStyle::OAS_DontAlign;
4505   EXPECT_EQ("return someVeryVeryLongConditionThatBarelyFitsOnALine\n"
4506             "\t&& (someOtherLongishConditionPart1\n"
4507             "\t\t|| someOtherEvenLongerNestedConditionPart2);",
4508             format("return someVeryVeryLongConditionThatBarelyFitsOnALine && "
4509                    "(someOtherLongishConditionPart1 || "
4510                    "someOtherEvenLongerNestedConditionPart2);",
4511                    Style));
4512 }
4513 
4514 TEST_F(FormatTest, ExpressionIndentationStrictAlign) {
4515   FormatStyle Style = getLLVMStyle();
4516   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
4517   Style.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
4518 
4519   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4520                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4521                "                   + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4522                "              == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4523                "                         * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4524                "                     + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4525                "          && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4526                "                     * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4527                "                 > ccccccccccccccccccccccccccccccccccccccccc;",
4528                Style);
4529   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4530                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4531                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4532                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4533                Style);
4534   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4535                "        + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4536                "              * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4537                "    == bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4538                Style);
4539   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4540                "    == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4541                "               * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4542                "           + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb) {\n}",
4543                Style);
4544   verifyFormat("if () {\n"
4545                "} else if (aaaaa\n"
4546                "           && bbbbb // break\n"
4547                "                  > ccccc) {\n"
4548                "}",
4549                Style);
4550   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4551                "    && bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4552                Style);
4553   verifyFormat("return (a)\n"
4554                "     // comment\n"
4555                "     + b;",
4556                Style);
4557   verifyFormat(
4558       "int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4559       "               * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4560       "           + cc;",
4561       Style);
4562   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
4563                "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
4564                "                        : 3333333333333333;",
4565                Style);
4566   verifyFormat(
4567       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
4568       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
4569       "                                             : eeeeeeeeeeeeeeeeee)\n"
4570       "     : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
4571       "                        : 3333333333333333;",
4572       Style);
4573   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4574                "    = aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
4575                Style);
4576 
4577   verifyFormat("return boost::fusion::at_c<0>(iiii).second\n"
4578                "    == boost::fusion::at_c<1>(iiii).second;",
4579                Style);
4580 
4581   Style.ColumnLimit = 60;
4582   verifyFormat("zzzzzzzzzzzzz\n"
4583                "    = bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4584                "   >> aaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa);",
4585                Style);
4586 
4587   // Forced by comments.
4588   Style.ColumnLimit = 80;
4589   verifyFormat(
4590       "unsigned ContentSize\n"
4591       "    = sizeof(int16_t) // DWARF ARange version number\n"
4592       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4593       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4594       "    + sizeof(int8_t); // Segment Size (in bytes)",
4595       Style);
4596 
4597   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4598   verifyFormat(
4599       "unsigned ContentSize =\n"
4600       "    sizeof(int16_t)   // DWARF ARange version number\n"
4601       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4602       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4603       "    + sizeof(int8_t); // Segment Size (in bytes)",
4604       Style);
4605 
4606   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
4607   verifyFormat(
4608       "unsigned ContentSize =\n"
4609       "    sizeof(int16_t)   // DWARF ARange version number\n"
4610       "    + sizeof(int32_t) // Offset of CU in the .debug_info section\n"
4611       "    + sizeof(int8_t)  // Pointer Size (in bytes)\n"
4612       "    + sizeof(int8_t); // Segment Size (in bytes)",
4613       Style);
4614 }
4615 
4616 TEST_F(FormatTest, EnforcedOperatorWraps) {
4617   // Here we'd like to wrap after the || operators, but a comment is forcing an
4618   // earlier wrap.
4619   verifyFormat("bool x = aaaaa //\n"
4620                "         || bbbbb\n"
4621                "         //\n"
4622                "         || cccc;");
4623 }
4624 
4625 TEST_F(FormatTest, NoOperandAlignment) {
4626   FormatStyle Style = getLLVMStyle();
4627   Style.AlignOperands = FormatStyle::OAS_DontAlign;
4628   verifyFormat("aaaaaaaaaaaaaa(aaaaaaaaaaaa,\n"
4629                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
4630                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
4631                Style);
4632   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4633   verifyFormat("bool value = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4634                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4635                "            + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4636                "        == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4637                "                * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4638                "            + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4639                "    && aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4640                "            * aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4641                "        > ccccccccccccccccccccccccccccccccccccccccc;",
4642                Style);
4643 
4644   verifyFormat("int aaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4645                "        * bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4646                "    + cc;",
4647                Style);
4648   verifyFormat("int a = aa\n"
4649                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
4650                "        * cccccccccccccccccccccccccccccccccccc;\n",
4651                Style);
4652 
4653   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
4654   verifyFormat("return (a > b\n"
4655                "    // comment1\n"
4656                "    // comment2\n"
4657                "    || c);",
4658                Style);
4659 }
4660 
4661 TEST_F(FormatTest, BreakingBeforeNonAssigmentOperators) {
4662   FormatStyle Style = getLLVMStyle();
4663   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4664   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
4665                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
4666                "    + bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
4667                Style);
4668 }
4669 
4670 TEST_F(FormatTest, AllowBinPackingInsideArguments) {
4671   FormatStyle Style = getLLVMStyle();
4672   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_NonAssignment;
4673   Style.BinPackArguments = false;
4674   Style.ColumnLimit = 40;
4675   verifyFormat("void test() {\n"
4676                "  someFunction(\n"
4677                "      this + argument + is + quite\n"
4678                "      + long + so + it + gets + wrapped\n"
4679                "      + but + remains + bin - packed);\n"
4680                "}",
4681                Style);
4682   verifyFormat("void test() {\n"
4683                "  someFunction(arg1,\n"
4684                "               this + argument + is\n"
4685                "                   + quite + long + so\n"
4686                "                   + it + gets + wrapped\n"
4687                "                   + but + remains + bin\n"
4688                "                   - packed,\n"
4689                "               arg3);\n"
4690                "}",
4691                Style);
4692   verifyFormat("void test() {\n"
4693                "  someFunction(\n"
4694                "      arg1,\n"
4695                "      this + argument + has\n"
4696                "          + anotherFunc(nested,\n"
4697                "                        calls + whose\n"
4698                "                            + arguments\n"
4699                "                            + are + also\n"
4700                "                            + wrapped,\n"
4701                "                        in + addition)\n"
4702                "          + to + being + bin - packed,\n"
4703                "      arg3);\n"
4704                "}",
4705                Style);
4706 
4707   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
4708   verifyFormat("void test() {\n"
4709                "  someFunction(\n"
4710                "      arg1,\n"
4711                "      this + argument + has +\n"
4712                "          anotherFunc(nested,\n"
4713                "                      calls + whose +\n"
4714                "                          arguments +\n"
4715                "                          are + also +\n"
4716                "                          wrapped,\n"
4717                "                      in + addition) +\n"
4718                "          to + being + bin - packed,\n"
4719                "      arg3);\n"
4720                "}",
4721                Style);
4722 }
4723 
4724 TEST_F(FormatTest, ConstructorInitializers) {
4725   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
4726   verifyFormat("Constructor() : Inttializer(FitsOnTheLine) {}",
4727                getLLVMStyleWithColumns(45));
4728   verifyFormat("Constructor()\n"
4729                "    : Inttializer(FitsOnTheLine) {}",
4730                getLLVMStyleWithColumns(44));
4731   verifyFormat("Constructor()\n"
4732                "    : Inttializer(FitsOnTheLine) {}",
4733                getLLVMStyleWithColumns(43));
4734 
4735   verifyFormat("template <typename T>\n"
4736                "Constructor() : Initializer(FitsOnTheLine) {}",
4737                getLLVMStyleWithColumns(45));
4738 
4739   verifyFormat(
4740       "SomeClass::Constructor()\n"
4741       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
4742 
4743   verifyFormat(
4744       "SomeClass::Constructor()\n"
4745       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4746       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}");
4747   verifyFormat(
4748       "SomeClass::Constructor()\n"
4749       "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4750       "      aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}");
4751   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4752                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
4753                "    : aaaaaaaaaa(aaaaaa) {}");
4754 
4755   verifyFormat("Constructor()\n"
4756                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4757                "      aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4758                "                               aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
4759                "      aaaaaaaaaaaaaaaaaaaaaaa() {}");
4760 
4761   verifyFormat("Constructor()\n"
4762                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4763                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4764 
4765   verifyFormat("Constructor(int Parameter = 0)\n"
4766                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
4767                "      aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}");
4768   verifyFormat("Constructor()\n"
4769                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
4770                "}",
4771                getLLVMStyleWithColumns(60));
4772   verifyFormat("Constructor()\n"
4773                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
4774                "          aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}");
4775 
4776   // Here a line could be saved by splitting the second initializer onto two
4777   // lines, but that is not desirable.
4778   verifyFormat("Constructor()\n"
4779                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
4780                "      aaaaaaaaaaa(aaaaaaaaaaa),\n"
4781                "      aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
4782 
4783   FormatStyle OnePerLine = getLLVMStyle();
4784   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4785   OnePerLine.AllowAllParametersOfDeclarationOnNextLine = false;
4786   verifyFormat("SomeClass::Constructor()\n"
4787                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4788                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4789                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4790                OnePerLine);
4791   verifyFormat("SomeClass::Constructor()\n"
4792                "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
4793                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
4794                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
4795                OnePerLine);
4796   verifyFormat("MyClass::MyClass(int var)\n"
4797                "    : some_var_(var),            // 4 space indent\n"
4798                "      some_other_var_(var + 1) { // lined up\n"
4799                "}",
4800                OnePerLine);
4801   verifyFormat("Constructor()\n"
4802                "    : aaaaa(aaaaaa),\n"
4803                "      aaaaa(aaaaaa),\n"
4804                "      aaaaa(aaaaaa),\n"
4805                "      aaaaa(aaaaaa),\n"
4806                "      aaaaa(aaaaaa) {}",
4807                OnePerLine);
4808   verifyFormat("Constructor()\n"
4809                "    : aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
4810                "            aaaaaaaaaaaaaaaaaaaaaa) {}",
4811                OnePerLine);
4812   OnePerLine.BinPackParameters = false;
4813   verifyFormat(
4814       "Constructor()\n"
4815       "    : aaaaaaaaaaaaaaaaaaaaaaaa(\n"
4816       "          aaaaaaaaaaa().aaa(),\n"
4817       "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
4818       OnePerLine);
4819   OnePerLine.ColumnLimit = 60;
4820   verifyFormat("Constructor()\n"
4821                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4822                "      bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
4823                OnePerLine);
4824 
4825   EXPECT_EQ("Constructor()\n"
4826             "    : // Comment forcing unwanted break.\n"
4827             "      aaaa(aaaa) {}",
4828             format("Constructor() :\n"
4829                    "    // Comment forcing unwanted break.\n"
4830                    "    aaaa(aaaa) {}"));
4831 }
4832 
4833 TEST_F(FormatTest, AllowAllConstructorInitializersOnNextLine) {
4834   FormatStyle Style = getLLVMStyle();
4835   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4836   Style.ColumnLimit = 60;
4837   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
4838   Style.AllowAllConstructorInitializersOnNextLine = true;
4839   Style.BinPackParameters = false;
4840 
4841   for (int i = 0; i < 4; ++i) {
4842     // Test all combinations of parameters that should not have an effect.
4843     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
4844     Style.AllowAllArgumentsOnNextLine = i & 2;
4845 
4846     Style.AllowAllConstructorInitializersOnNextLine = true;
4847     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4848     verifyFormat("Constructor()\n"
4849                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4850                  Style);
4851     verifyFormat("Constructor() : a(a), b(b) {}", Style);
4852 
4853     Style.AllowAllConstructorInitializersOnNextLine = false;
4854     verifyFormat("Constructor()\n"
4855                  "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4856                  "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4857                  Style);
4858     verifyFormat("Constructor() : a(a), b(b) {}", Style);
4859 
4860     Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
4861     Style.AllowAllConstructorInitializersOnNextLine = true;
4862     verifyFormat("Constructor()\n"
4863                  "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4864                  Style);
4865 
4866     Style.AllowAllConstructorInitializersOnNextLine = false;
4867     verifyFormat("Constructor()\n"
4868                  "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4869                  "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4870                  Style);
4871 
4872     Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4873     Style.AllowAllConstructorInitializersOnNextLine = true;
4874     verifyFormat("Constructor() :\n"
4875                  "    aaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4876                  Style);
4877 
4878     Style.AllowAllConstructorInitializersOnNextLine = false;
4879     verifyFormat("Constructor() :\n"
4880                  "    aaaaaaaaaaaaaaaaaa(a),\n"
4881                  "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4882                  Style);
4883   }
4884 
4885   // Test interactions between AllowAllParametersOfDeclarationOnNextLine and
4886   // AllowAllConstructorInitializersOnNextLine in all
4887   // BreakConstructorInitializers modes
4888   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
4889   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4890   Style.AllowAllConstructorInitializersOnNextLine = false;
4891   verifyFormat("SomeClassWithALongName::Constructor(\n"
4892                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
4893                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4894                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4895                Style);
4896 
4897   Style.AllowAllConstructorInitializersOnNextLine = true;
4898   verifyFormat("SomeClassWithALongName::Constructor(\n"
4899                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4900                "    int bbbbbbbbbbbbb,\n"
4901                "    int cccccccccccccccc)\n"
4902                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4903                Style);
4904 
4905   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4906   Style.AllowAllConstructorInitializersOnNextLine = false;
4907   verifyFormat("SomeClassWithALongName::Constructor(\n"
4908                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4909                "    int bbbbbbbbbbbbb)\n"
4910                "    : aaaaaaaaaaaaaaaaaaaa(a)\n"
4911                "    , bbbbbbbbbbbbbbbbbbbbb(b) {}",
4912                Style);
4913 
4914   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
4915 
4916   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4917   verifyFormat("SomeClassWithALongName::Constructor(\n"
4918                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb)\n"
4919                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4920                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4921                Style);
4922 
4923   Style.AllowAllConstructorInitializersOnNextLine = true;
4924   verifyFormat("SomeClassWithALongName::Constructor(\n"
4925                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4926                "    int bbbbbbbbbbbbb,\n"
4927                "    int cccccccccccccccc)\n"
4928                "    : aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4929                Style);
4930 
4931   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4932   Style.AllowAllConstructorInitializersOnNextLine = false;
4933   verifyFormat("SomeClassWithALongName::Constructor(\n"
4934                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4935                "    int bbbbbbbbbbbbb)\n"
4936                "    : aaaaaaaaaaaaaaaaaaaa(a),\n"
4937                "      bbbbbbbbbbbbbbbbbbbbb(b) {}",
4938                Style);
4939 
4940   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
4941   Style.AllowAllParametersOfDeclarationOnNextLine = true;
4942   verifyFormat("SomeClassWithALongName::Constructor(\n"
4943                "    int aaaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbbb) :\n"
4944                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
4945                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4946                Style);
4947 
4948   Style.AllowAllConstructorInitializersOnNextLine = true;
4949   verifyFormat("SomeClassWithALongName::Constructor(\n"
4950                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4951                "    int bbbbbbbbbbbbb,\n"
4952                "    int cccccccccccccccc) :\n"
4953                "    aaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbb(b) {}",
4954                Style);
4955 
4956   Style.AllowAllParametersOfDeclarationOnNextLine = false;
4957   Style.AllowAllConstructorInitializersOnNextLine = false;
4958   verifyFormat("SomeClassWithALongName::Constructor(\n"
4959                "    int aaaaaaaaaaaaaaaaaaaaaaaa,\n"
4960                "    int bbbbbbbbbbbbb) :\n"
4961                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
4962                "    bbbbbbbbbbbbbbbbbbbbb(b) {}",
4963                Style);
4964 }
4965 
4966 TEST_F(FormatTest, AllowAllArgumentsOnNextLine) {
4967   FormatStyle Style = getLLVMStyle();
4968   Style.ColumnLimit = 60;
4969   Style.BinPackArguments = false;
4970   for (int i = 0; i < 4; ++i) {
4971     // Test all combinations of parameters that should not have an effect.
4972     Style.AllowAllParametersOfDeclarationOnNextLine = i & 1;
4973     Style.AllowAllConstructorInitializersOnNextLine = i & 2;
4974 
4975     Style.AllowAllArgumentsOnNextLine = true;
4976     verifyFormat("void foo() {\n"
4977                  "  FunctionCallWithReallyLongName(\n"
4978                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb);\n"
4979                  "}",
4980                  Style);
4981     Style.AllowAllArgumentsOnNextLine = false;
4982     verifyFormat("void foo() {\n"
4983                  "  FunctionCallWithReallyLongName(\n"
4984                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4985                  "      bbbbbbbbbbbb);\n"
4986                  "}",
4987                  Style);
4988 
4989     Style.AllowAllArgumentsOnNextLine = true;
4990     verifyFormat("void foo() {\n"
4991                  "  auto VariableWithReallyLongName = {\n"
4992                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbbbbb};\n"
4993                  "}",
4994                  Style);
4995     Style.AllowAllArgumentsOnNextLine = false;
4996     verifyFormat("void foo() {\n"
4997                  "  auto VariableWithReallyLongName = {\n"
4998                  "      aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
4999                  "      bbbbbbbbbbbb};\n"
5000                  "}",
5001                  Style);
5002   }
5003 
5004   // This parameter should not affect declarations.
5005   Style.BinPackParameters = false;
5006   Style.AllowAllArgumentsOnNextLine = false;
5007   Style.AllowAllParametersOfDeclarationOnNextLine = true;
5008   verifyFormat("void FunctionCallWithReallyLongName(\n"
5009                "    int aaaaaaaaaaaaaaaaaaaaaaa, int bbbbbbbbbbbb);",
5010                Style);
5011   Style.AllowAllParametersOfDeclarationOnNextLine = false;
5012   verifyFormat("void FunctionCallWithReallyLongName(\n"
5013                "    int aaaaaaaaaaaaaaaaaaaaaaa,\n"
5014                "    int bbbbbbbbbbbb);",
5015                Style);
5016 }
5017 
5018 TEST_F(FormatTest, AllowAllArgumentsOnNextLineDontAlign) {
5019   // Check that AllowAllArgumentsOnNextLine is respected for both BAS_DontAlign
5020   // and BAS_Align.
5021   auto Style = getLLVMStyle();
5022   Style.ColumnLimit = 35;
5023   StringRef Input = "functionCall(paramA, paramB, paramC);\n"
5024                     "void functionDecl(int A, int B, int C);";
5025   Style.AllowAllArgumentsOnNextLine = false;
5026   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5027   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5028                       "    paramC);\n"
5029                       "void functionDecl(int A, int B,\n"
5030                       "    int C);"),
5031             format(Input, Style));
5032   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
5033   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5034                       "             paramC);\n"
5035                       "void functionDecl(int A, int B,\n"
5036                       "                  int C);"),
5037             format(Input, Style));
5038   // However, BAS_AlwaysBreak should take precedence over
5039   // AllowAllArgumentsOnNextLine.
5040   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
5041   EXPECT_EQ(StringRef("functionCall(\n"
5042                       "    paramA, paramB, paramC);\n"
5043                       "void functionDecl(\n"
5044                       "    int A, int B, int C);"),
5045             format(Input, Style));
5046 
5047   // When AllowAllArgumentsOnNextLine is set, we prefer breaking before the
5048   // first argument.
5049   Style.AllowAllArgumentsOnNextLine = true;
5050   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
5051   EXPECT_EQ(StringRef("functionCall(\n"
5052                       "    paramA, paramB, paramC);\n"
5053                       "void functionDecl(\n"
5054                       "    int A, int B, int C);"),
5055             format(Input, Style));
5056   // It wouldn't fit on one line with aligned parameters so this setting
5057   // doesn't change anything for BAS_Align.
5058   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
5059   EXPECT_EQ(StringRef("functionCall(paramA, paramB,\n"
5060                       "             paramC);\n"
5061                       "void functionDecl(int A, int B,\n"
5062                       "                  int C);"),
5063             format(Input, Style));
5064   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
5065   EXPECT_EQ(StringRef("functionCall(\n"
5066                       "    paramA, paramB, paramC);\n"
5067                       "void functionDecl(\n"
5068                       "    int A, int B, int C);"),
5069             format(Input, Style));
5070 }
5071 
5072 TEST_F(FormatTest, BreakConstructorInitializersAfterColon) {
5073   FormatStyle Style = getLLVMStyle();
5074   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
5075 
5076   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}");
5077   verifyFormat("Constructor() : Initializer(FitsOnTheLine) {}",
5078                getStyleWithColumns(Style, 45));
5079   verifyFormat("Constructor() :\n"
5080                "    Initializer(FitsOnTheLine) {}",
5081                getStyleWithColumns(Style, 44));
5082   verifyFormat("Constructor() :\n"
5083                "    Initializer(FitsOnTheLine) {}",
5084                getStyleWithColumns(Style, 43));
5085 
5086   verifyFormat("template <typename T>\n"
5087                "Constructor() : Initializer(FitsOnTheLine) {}",
5088                getStyleWithColumns(Style, 50));
5089   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5090   verifyFormat(
5091       "SomeClass::Constructor() :\n"
5092       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5093       Style);
5094 
5095   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
5096   verifyFormat(
5097       "SomeClass::Constructor() :\n"
5098       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5099       Style);
5100 
5101   verifyFormat(
5102       "SomeClass::Constructor() :\n"
5103       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5104       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5105       Style);
5106   verifyFormat(
5107       "SomeClass::Constructor() :\n"
5108       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5109       "    aaaaaaaaaaaaaaa(aaaaaaaaaaaa) {}",
5110       Style);
5111   verifyFormat("Constructor(aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5112                "            aaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
5113                "    aaaaaaaaaa(aaaaaa) {}",
5114                Style);
5115 
5116   verifyFormat("Constructor() :\n"
5117                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5118                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5119                "                             aaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5120                "    aaaaaaaaaaaaaaaaaaaaaaa() {}",
5121                Style);
5122 
5123   verifyFormat("Constructor() :\n"
5124                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5125                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5126                Style);
5127 
5128   verifyFormat("Constructor(int Parameter = 0) :\n"
5129                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa),\n"
5130                "    aaaaaaaaaaaa(aaaaaaaaaaaaaaaaa) {}",
5131                Style);
5132   verifyFormat("Constructor() :\n"
5133                "    aaaaaaaaaaaaaaaaaaaaaa(a), bbbbbbbbbbbbbbbbbbbbbbbb(b) {\n"
5134                "}",
5135                getStyleWithColumns(Style, 60));
5136   verifyFormat("Constructor() :\n"
5137                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5138                "        aaaaaaaaaaaaaaaaaaaaaaaaa(aaaa, aaaa)) {}",
5139                Style);
5140 
5141   // Here a line could be saved by splitting the second initializer onto two
5142   // lines, but that is not desirable.
5143   verifyFormat("Constructor() :\n"
5144                "    aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaa),\n"
5145                "    aaaaaaaaaaa(aaaaaaaaaaa),\n"
5146                "    aaaaaaaaaaaaaaaaaaaaat(aaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5147                Style);
5148 
5149   FormatStyle OnePerLine = Style;
5150   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5151   OnePerLine.AllowAllConstructorInitializersOnNextLine = false;
5152   verifyFormat("SomeClass::Constructor() :\n"
5153                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5154                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5155                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5156                OnePerLine);
5157   verifyFormat("SomeClass::Constructor() :\n"
5158                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa), // Some comment\n"
5159                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
5160                "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
5161                OnePerLine);
5162   verifyFormat("MyClass::MyClass(int var) :\n"
5163                "    some_var_(var),            // 4 space indent\n"
5164                "    some_other_var_(var + 1) { // lined up\n"
5165                "}",
5166                OnePerLine);
5167   verifyFormat("Constructor() :\n"
5168                "    aaaaa(aaaaaa),\n"
5169                "    aaaaa(aaaaaa),\n"
5170                "    aaaaa(aaaaaa),\n"
5171                "    aaaaa(aaaaaa),\n"
5172                "    aaaaa(aaaaaa) {}",
5173                OnePerLine);
5174   verifyFormat("Constructor() :\n"
5175                "    aaaaa(aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa,\n"
5176                "          aaaaaaaaaaaaaaaaaaaaaa) {}",
5177                OnePerLine);
5178   OnePerLine.BinPackParameters = false;
5179   verifyFormat("Constructor() :\n"
5180                "    aaaaaaaaaaaaaaaaaaaaaaaa(\n"
5181                "        aaaaaaaaaaa().aaa(),\n"
5182                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5183                OnePerLine);
5184   OnePerLine.ColumnLimit = 60;
5185   verifyFormat("Constructor() :\n"
5186                "    aaaaaaaaaaaaaaaaaaaa(a),\n"
5187                "    bbbbbbbbbbbbbbbbbbbbbbbb(b) {}",
5188                OnePerLine);
5189 
5190   EXPECT_EQ("Constructor() :\n"
5191             "    // Comment forcing unwanted break.\n"
5192             "    aaaa(aaaa) {}",
5193             format("Constructor() :\n"
5194                    "    // Comment forcing unwanted break.\n"
5195                    "    aaaa(aaaa) {}",
5196                    Style));
5197 
5198   Style.ColumnLimit = 0;
5199   verifyFormat("SomeClass::Constructor() :\n"
5200                "    a(a) {}",
5201                Style);
5202   verifyFormat("SomeClass::Constructor() noexcept :\n"
5203                "    a(a) {}",
5204                Style);
5205   verifyFormat("SomeClass::Constructor() :\n"
5206                "    a(a), b(b), c(c) {}",
5207                Style);
5208   verifyFormat("SomeClass::Constructor() :\n"
5209                "    a(a) {\n"
5210                "  foo();\n"
5211                "  bar();\n"
5212                "}",
5213                Style);
5214 
5215   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
5216   verifyFormat("SomeClass::Constructor() :\n"
5217                "    a(a), b(b), c(c) {\n"
5218                "}",
5219                Style);
5220   verifyFormat("SomeClass::Constructor() :\n"
5221                "    a(a) {\n"
5222                "}",
5223                Style);
5224 
5225   Style.ColumnLimit = 80;
5226   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
5227   Style.ConstructorInitializerIndentWidth = 2;
5228   verifyFormat("SomeClass::Constructor() : a(a), b(b), c(c) {}", Style);
5229   verifyFormat("SomeClass::Constructor() :\n"
5230                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5231                "  bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {}",
5232                Style);
5233 
5234   // `ConstructorInitializerIndentWidth` actually applies to InheritanceList as
5235   // well
5236   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
5237   verifyFormat(
5238       "class SomeClass\n"
5239       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5240       "    public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5241       Style);
5242   Style.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
5243   verifyFormat(
5244       "class SomeClass\n"
5245       "  : public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5246       "  , public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5247       Style);
5248   Style.BreakInheritanceList = FormatStyle::BILS_AfterColon;
5249   verifyFormat(
5250       "class SomeClass :\n"
5251       "  public aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5252       "  public bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb {};",
5253       Style);
5254 }
5255 
5256 #ifndef EXPENSIVE_CHECKS
5257 // Expensive checks enables libstdc++ checking which includes validating the
5258 // state of ranges used in std::priority_queue - this blows out the
5259 // runtime/scalability of the function and makes this test unacceptably slow.
5260 TEST_F(FormatTest, MemoizationTests) {
5261   // This breaks if the memoization lookup does not take \c Indent and
5262   // \c LastSpace into account.
5263   verifyFormat(
5264       "extern CFRunLoopTimerRef\n"
5265       "CFRunLoopTimerCreate(CFAllocatorRef allocato, CFAbsoluteTime fireDate,\n"
5266       "                     CFTimeInterval interval, CFOptionFlags flags,\n"
5267       "                     CFIndex order, CFRunLoopTimerCallBack callout,\n"
5268       "                     CFRunLoopTimerContext *context) {}");
5269 
5270   // Deep nesting somewhat works around our memoization.
5271   verifyFormat(
5272       "aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5273       "    aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5274       "        aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5275       "            aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(aaaaa(\n"
5276       "                aaaaa())))))))))))))))))))))))))))))))))))))));",
5277       getLLVMStyleWithColumns(65));
5278   verifyFormat(
5279       "aaaaa(\n"
5280       "    aaaaa,\n"
5281       "    aaaaa(\n"
5282       "        aaaaa,\n"
5283       "        aaaaa(\n"
5284       "            aaaaa,\n"
5285       "            aaaaa(\n"
5286       "                aaaaa,\n"
5287       "                aaaaa(\n"
5288       "                    aaaaa,\n"
5289       "                    aaaaa(\n"
5290       "                        aaaaa,\n"
5291       "                        aaaaa(\n"
5292       "                            aaaaa,\n"
5293       "                            aaaaa(\n"
5294       "                                aaaaa,\n"
5295       "                                aaaaa(\n"
5296       "                                    aaaaa,\n"
5297       "                                    aaaaa(\n"
5298       "                                        aaaaa,\n"
5299       "                                        aaaaa(\n"
5300       "                                            aaaaa,\n"
5301       "                                            aaaaa(\n"
5302       "                                                aaaaa,\n"
5303       "                                                aaaaa))))))))))));",
5304       getLLVMStyleWithColumns(65));
5305   verifyFormat(
5306       "a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(a(), a), a), a), a),\n"
5307       "                                  a),\n"
5308       "                                a),\n"
5309       "                              a),\n"
5310       "                            a),\n"
5311       "                          a),\n"
5312       "                        a),\n"
5313       "                      a),\n"
5314       "                    a),\n"
5315       "                  a),\n"
5316       "                a),\n"
5317       "              a),\n"
5318       "            a),\n"
5319       "          a),\n"
5320       "        a),\n"
5321       "      a),\n"
5322       "    a),\n"
5323       "  a)",
5324       getLLVMStyleWithColumns(65));
5325 
5326   // This test takes VERY long when memoization is broken.
5327   FormatStyle OnePerLine = getLLVMStyle();
5328   OnePerLine.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
5329   OnePerLine.BinPackParameters = false;
5330   std::string input = "Constructor()\n"
5331                       "    : aaaa(a,\n";
5332   for (unsigned i = 0, e = 80; i != e; ++i) {
5333     input += "           a,\n";
5334   }
5335   input += "           a) {}";
5336   verifyFormat(input, OnePerLine);
5337 }
5338 #endif
5339 
5340 TEST_F(FormatTest, BreaksAsHighAsPossible) {
5341   verifyFormat(
5342       "void f() {\n"
5343       "  if ((aaaaaaaaaaaaaaaaaaaaaaaaaaaaa && aaaaaaaaaaaaaaaaaaaaaaaaaa) ||\n"
5344       "      (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb && bbbbbbbbbbbbbbbbbbbbbbbbbb))\n"
5345       "    f();\n"
5346       "}");
5347   verifyFormat("if (Intervals[i].getRange().getFirst() <\n"
5348                "    Intervals[i - 1].getRange().getLast()) {\n}");
5349 }
5350 
5351 TEST_F(FormatTest, BreaksFunctionDeclarations) {
5352   // Principially, we break function declarations in a certain order:
5353   // 1) break amongst arguments.
5354   verifyFormat("Aaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccc,\n"
5355                "                              Cccccccccccccc cccccccccccccc);");
5356   verifyFormat("template <class TemplateIt>\n"
5357                "SomeReturnType SomeFunction(TemplateIt begin, TemplateIt end,\n"
5358                "                            TemplateIt *stop) {}");
5359 
5360   // 2) break after return type.
5361   verifyFormat(
5362       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5363       "bbbbbbbbbbbbbb(Cccccccccccccc cccccccccccccccccccccccccc);",
5364       getGoogleStyle());
5365 
5366   // 3) break after (.
5367   verifyFormat(
5368       "Aaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbb(\n"
5369       "    Cccccccccccccccccccccccccccccc cccccccccccccccccccccccccccccccc);",
5370       getGoogleStyle());
5371 
5372   // 4) break before after nested name specifiers.
5373   verifyFormat(
5374       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5375       "SomeClasssssssssssssssssssssssssssssssssssssss::\n"
5376       "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc);",
5377       getGoogleStyle());
5378 
5379   // However, there are exceptions, if a sufficient amount of lines can be
5380   // saved.
5381   // FIXME: The precise cut-offs wrt. the number of saved lines might need some
5382   // more adjusting.
5383   verifyFormat("Aaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
5384                "                                  Cccccccccccccc cccccccccc,\n"
5385                "                                  Cccccccccccccc cccccccccc,\n"
5386                "                                  Cccccccccccccc cccccccccc,\n"
5387                "                                  Cccccccccccccc cccccccccc);");
5388   verifyFormat(
5389       "Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5390       "bbbbbbbbbbb(Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5391       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5392       "            Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);",
5393       getGoogleStyle());
5394   verifyFormat(
5395       "Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(Cccccccccccccc cccccccccc,\n"
5396       "                                          Cccccccccccccc cccccccccc,\n"
5397       "                                          Cccccccccccccc cccccccccc,\n"
5398       "                                          Cccccccccccccc cccccccccc,\n"
5399       "                                          Cccccccccccccc cccccccccc,\n"
5400       "                                          Cccccccccccccc cccccccccc,\n"
5401       "                                          Cccccccccccccc cccccccccc);");
5402   verifyFormat("Aaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5403                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5404                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5405                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc,\n"
5406                "    Cccccccccccccc cccccccccc, Cccccccccccccc cccccccccc);");
5407 
5408   // Break after multi-line parameters.
5409   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5410                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5411                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5412                "    bbbb bbbb);");
5413   verifyFormat("void SomeLoooooooooooongFunction(\n"
5414                "    std::unique_ptr<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
5415                "        aaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5416                "    int bbbbbbbbbbbbb);");
5417 
5418   // Treat overloaded operators like other functions.
5419   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5420                "operator>(const SomeLoooooooooooooooooooooooooogType &other);");
5421   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5422                "operator>>(const SomeLooooooooooooooooooooooooogType &other);");
5423   verifyFormat("SomeLoooooooooooooooooooooooooogType\n"
5424                "operator<<(const SomeLooooooooooooooooooooooooogType &other);");
5425   verifyGoogleFormat(
5426       "SomeLoooooooooooooooooooooooooooooogType operator>>(\n"
5427       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
5428   verifyGoogleFormat(
5429       "SomeLoooooooooooooooooooooooooooooogType operator<<(\n"
5430       "    const SomeLooooooooogType &a, const SomeLooooooooogType &b);");
5431   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5432                "    int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1);");
5433   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa\n"
5434                "aaaaaaaaaaaaaaaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaa = 1);");
5435   verifyGoogleFormat(
5436       "typename aaaaaaaaaa<aaaaaa>::aaaaaaaaaaa\n"
5437       "aaaaaaaaaa<aaaaaa>::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5438       "    bool *aaaaaaaaaaaaaaaaaa, bool *aa) {}");
5439   verifyGoogleFormat("template <typename T>\n"
5440                      "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5441                      "aaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaaaaa(\n"
5442                      "    aaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaa);");
5443 
5444   FormatStyle Style = getLLVMStyle();
5445   Style.PointerAlignment = FormatStyle::PAS_Left;
5446   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5447                "    aaaaaaaaaaaaaaaaaaaaaaaaa* const aaaaaaaaaaaa) {}",
5448                Style);
5449   verifyFormat("void aaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa*\n"
5450                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5451                Style);
5452 }
5453 
5454 TEST_F(FormatTest, DontBreakBeforeQualifiedOperator) {
5455   // Regression test for https://bugs.llvm.org/show_bug.cgi?id=40516:
5456   // Prefer keeping `::` followed by `operator` together.
5457   EXPECT_EQ("const aaaa::bbbbbbb &\n"
5458             "ccccccccc::operator++() {\n"
5459             "  stuff();\n"
5460             "}",
5461             format("const aaaa::bbbbbbb\n"
5462                    "&ccccccccc::operator++() { stuff(); }",
5463                    getLLVMStyleWithColumns(40)));
5464 }
5465 
5466 TEST_F(FormatTest, TrailingReturnType) {
5467   verifyFormat("auto foo() -> int;\n");
5468   // correct trailing return type spacing
5469   verifyFormat("auto operator->() -> int;\n");
5470   verifyFormat("auto operator++(int) -> int;\n");
5471 
5472   verifyFormat("struct S {\n"
5473                "  auto bar() const -> int;\n"
5474                "};");
5475   verifyFormat("template <size_t Order, typename T>\n"
5476                "auto load_img(const std::string &filename)\n"
5477                "    -> alias::tensor<Order, T, mem::tag::cpu> {}");
5478   verifyFormat("auto SomeFunction(A aaaaaaaaaaaaaaaaaaaaa) const\n"
5479                "    -> decltype(f(aaaaaaaaaaaaaaaaaaaaa)) {}");
5480   verifyFormat("auto doSomething(Aaaaaa *aaaaaa) -> decltype(aaaaaa->f()) {}");
5481   verifyFormat("template <typename T>\n"
5482                "auto aaaaaaaaaaaaaaaaaaaaaa(T t)\n"
5483                "    -> decltype(eaaaaaaaaaaaaaaa<T>(t.a).aaaaaaaa());");
5484 
5485   // Not trailing return types.
5486   verifyFormat("void f() { auto a = b->c(); }");
5487 }
5488 
5489 TEST_F(FormatTest, DeductionGuides) {
5490   verifyFormat("template <class T> A(const T &, const T &) -> A<T &>;");
5491   verifyFormat("template <class T> explicit A(T &, T &&) -> A<T>;");
5492   verifyFormat("template <class... Ts> S(Ts...) -> S<Ts...>;");
5493   verifyFormat(
5494       "template <class... T>\n"
5495       "array(T &&...t) -> array<std::common_type_t<T...>, sizeof...(T)>;");
5496   verifyFormat("template <class T> A() -> A<decltype(p->foo<3>())>;");
5497   verifyFormat("template <class T> A() -> A<decltype(foo<traits<1>>)>;");
5498   verifyFormat("template <class T> A() -> A<sizeof(p->foo<1>)>;");
5499   verifyFormat("template <class T> A() -> A<(3 < 2)>;");
5500   verifyFormat("template <class T> A() -> A<((3) < (2))>;");
5501   verifyFormat("template <class T> x() -> x<1>;");
5502   verifyFormat("template <class T> explicit x(T &) -> x<1>;");
5503 
5504   // Ensure not deduction guides.
5505   verifyFormat("c()->f<int>();");
5506   verifyFormat("x()->foo<1>;");
5507   verifyFormat("x = p->foo<3>();");
5508   verifyFormat("x()->x<1>();");
5509   verifyFormat("x()->x<1>;");
5510 }
5511 
5512 TEST_F(FormatTest, BreaksFunctionDeclarationsWithTrailingTokens) {
5513   // Avoid breaking before trailing 'const' or other trailing annotations, if
5514   // they are not function-like.
5515   FormatStyle Style = getGoogleStyle();
5516   Style.ColumnLimit = 47;
5517   verifyFormat("void someLongFunction(\n"
5518                "    int someLoooooooooooooongParameter) const {\n}",
5519                getLLVMStyleWithColumns(47));
5520   verifyFormat("LoooooongReturnType\n"
5521                "someLoooooooongFunction() const {}",
5522                getLLVMStyleWithColumns(47));
5523   verifyFormat("LoooooongReturnType someLoooooooongFunction()\n"
5524                "    const {}",
5525                Style);
5526   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5527                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE;");
5528   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5529                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) OVERRIDE FINAL;");
5530   verifyFormat("void SomeFunction(aaaaa aaaaaaaaaaaaaaaaaaaa,\n"
5531                "                  aaaaa aaaaaaaaaaaaaaaaaaaa) override final;");
5532   verifyFormat("virtual void aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa,\n"
5533                "                   aaaaaaaaaaa aaaaa) const override;");
5534   verifyGoogleFormat(
5535       "virtual void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5536       "    const override;");
5537 
5538   // Even if the first parameter has to be wrapped.
5539   verifyFormat("void someLongFunction(\n"
5540                "    int someLongParameter) const {}",
5541                getLLVMStyleWithColumns(46));
5542   verifyFormat("void someLongFunction(\n"
5543                "    int someLongParameter) const {}",
5544                Style);
5545   verifyFormat("void someLongFunction(\n"
5546                "    int someLongParameter) override {}",
5547                Style);
5548   verifyFormat("void someLongFunction(\n"
5549                "    int someLongParameter) OVERRIDE {}",
5550                Style);
5551   verifyFormat("void someLongFunction(\n"
5552                "    int someLongParameter) final {}",
5553                Style);
5554   verifyFormat("void someLongFunction(\n"
5555                "    int someLongParameter) FINAL {}",
5556                Style);
5557   verifyFormat("void someLongFunction(\n"
5558                "    int parameter) const override {}",
5559                Style);
5560 
5561   Style.BreakBeforeBraces = FormatStyle::BS_Allman;
5562   verifyFormat("void someLongFunction(\n"
5563                "    int someLongParameter) const\n"
5564                "{\n"
5565                "}",
5566                Style);
5567 
5568   Style.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
5569   verifyFormat("void someLongFunction(\n"
5570                "    int someLongParameter) const\n"
5571                "  {\n"
5572                "  }",
5573                Style);
5574 
5575   // Unless these are unknown annotations.
5576   verifyFormat("void SomeFunction(aaaaaaaaaa aaaaaaaaaaaaaaa,\n"
5577                "                  aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5578                "    LONG_AND_UGLY_ANNOTATION;");
5579 
5580   // Breaking before function-like trailing annotations is fine to keep them
5581   // close to their arguments.
5582   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5583                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5584   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5585                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa);");
5586   verifyFormat("void aaaaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) const\n"
5587                "    LOCKS_EXCLUDED(aaaaaaaaaaaaa) {}");
5588   verifyGoogleFormat("void aaaaaaaaaaaaaa(aaaaaaaa aaa) override\n"
5589                      "    AAAAAAAAAAAAAAAAAAAAAAAA(aaaaaaaaaaaaaaa);");
5590   verifyFormat("SomeFunction([](int i) LOCKS_EXCLUDED(a) {});");
5591 
5592   verifyFormat(
5593       "void aaaaaaaaaaaaaaaaaa()\n"
5594       "    __attribute__((aaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaa,\n"
5595       "                   aaaaaaaaaaaaaaaaaaaaaaaaa));");
5596   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5597                "    __attribute__((unused));");
5598   verifyGoogleFormat(
5599       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5600       "    GUARDED_BY(aaaaaaaaaaaa);");
5601   verifyGoogleFormat(
5602       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5603       "    GUARDED_BY(aaaaaaaaaaaa);");
5604   verifyGoogleFormat(
5605       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
5606       "    aaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
5607   verifyGoogleFormat(
5608       "bool aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa GUARDED_BY(aaaaaaaaaaaa) =\n"
5609       "    aaaaaaaaaaaaaaaaaaaaaaaaa;");
5610 }
5611 
5612 TEST_F(FormatTest, FunctionAnnotations) {
5613   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5614                "int OldFunction(const string &parameter) {}");
5615   verifyFormat("DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5616                "string OldFunction(const string &parameter) {}");
5617   verifyFormat("template <typename T>\n"
5618                "DEPRECATED(\"Use NewClass::NewFunction instead.\")\n"
5619                "string OldFunction(const string &parameter) {}");
5620 
5621   // Not function annotations.
5622   verifyFormat("ASSERT(\"aaaaa\") << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
5623                "                << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
5624   verifyFormat("TEST_F(ThisIsATestFixtureeeeeeeeeeeee,\n"
5625                "       ThisIsATestWithAReallyReallyReallyReallyLongName) {}");
5626   verifyFormat("MACRO(abc).function() // wrap\n"
5627                "    << abc;");
5628   verifyFormat("MACRO(abc)->function() // wrap\n"
5629                "    << abc;");
5630   verifyFormat("MACRO(abc)::function() // wrap\n"
5631                "    << abc;");
5632 }
5633 
5634 TEST_F(FormatTest, BreaksDesireably) {
5635   verifyFormat("if (aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
5636                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa) ||\n"
5637                "    aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaa)) {\n}");
5638   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5639                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)) {\n"
5640                "}");
5641 
5642   verifyFormat(
5643       "aaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5644       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}");
5645 
5646   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5647                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5648                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5649 
5650   verifyFormat(
5651       "aaaaaaaa(aaaaaaaaaaaaa,\n"
5652       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5653       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
5654       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5655       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));");
5656 
5657   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5658                "    (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5659 
5660   verifyFormat(
5661       "void f() {\n"
5662       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa &&\n"
5663       "                                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5664       "}");
5665   verifyFormat(
5666       "aaaaaa(new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5667       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5668   verifyFormat(
5669       "aaaaaa(aaa, new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5670       "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaa));");
5671   verifyFormat(
5672       "aaaaaa(aaa,\n"
5673       "       new Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5674       "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
5675       "       aaaa);");
5676   verifyFormat("aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa +\n"
5677                "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5678                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5679 
5680   // Indent consistently independent of call expression and unary operator.
5681   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5682                "    dddddddddddddddddddddddddddddd));");
5683   verifyFormat("aaaaaaaaaaa(!bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
5684                "    dddddddddddddddddddddddddddddd));");
5685   verifyFormat("aaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbb.ccccccccccccccccc(\n"
5686                "    dddddddddddddddddddddddddddddd));");
5687 
5688   // This test case breaks on an incorrect memoization, i.e. an optimization not
5689   // taking into account the StopAt value.
5690   verifyFormat(
5691       "return aaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5692       "       aaaaaaaaaaa(aaaaaaaaa) || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5693       "       aaaaaaaaaaaaaaaaaaaaaaaaa || aaaaaaaaaaaaaaaaaaaaaaa ||\n"
5694       "       (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5695 
5696   verifyFormat("{\n  {\n    {\n"
5697                "      Annotation.SpaceRequiredBefore =\n"
5698                "          Line.Tokens[i - 1].Tok.isNot(tok::l_paren) &&\n"
5699                "          Line.Tokens[i - 1].Tok.isNot(tok::l_square);\n"
5700                "    }\n  }\n}");
5701 
5702   // Break on an outer level if there was a break on an inner level.
5703   EXPECT_EQ("f(g(h(a, // comment\n"
5704             "      b, c),\n"
5705             "    d, e),\n"
5706             "  x, y);",
5707             format("f(g(h(a, // comment\n"
5708                    "    b, c), d, e), x, y);"));
5709 
5710   // Prefer breaking similar line breaks.
5711   verifyFormat(
5712       "const int kTrackingOptions = NSTrackingMouseMoved |\n"
5713       "                             NSTrackingMouseEnteredAndExited |\n"
5714       "                             NSTrackingActiveAlways;");
5715 }
5716 
5717 TEST_F(FormatTest, FormatsDeclarationsOnePerLine) {
5718   FormatStyle NoBinPacking = getGoogleStyle();
5719   NoBinPacking.BinPackParameters = false;
5720   NoBinPacking.BinPackArguments = true;
5721   verifyFormat("void f() {\n"
5722                "  f(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaa,\n"
5723                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
5724                "}",
5725                NoBinPacking);
5726   verifyFormat("void f(int aaaaaaaaaaaaaaaaaaaa,\n"
5727                "       int aaaaaaaaaaaaaaaaaaaa,\n"
5728                "       int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
5729                NoBinPacking);
5730 
5731   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
5732   verifyFormat("void aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5733                "                        vector<int> bbbbbbbbbbbbbbb);",
5734                NoBinPacking);
5735   // FIXME: This behavior difference is probably not wanted. However, currently
5736   // we cannot distinguish BreakBeforeParameter being set because of the wrapped
5737   // template arguments from BreakBeforeParameter being set because of the
5738   // one-per-line formatting.
5739   verifyFormat(
5740       "void fffffffffff(aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa,\n"
5741       "                                             aaaaaaaaaa> aaaaaaaaaa);",
5742       NoBinPacking);
5743   verifyFormat(
5744       "void fffffffffff(\n"
5745       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaa>\n"
5746       "        aaaaaaaaaa);");
5747 }
5748 
5749 TEST_F(FormatTest, FormatsOneParameterPerLineIfNecessary) {
5750   FormatStyle NoBinPacking = getGoogleStyle();
5751   NoBinPacking.BinPackParameters = false;
5752   NoBinPacking.BinPackArguments = false;
5753   verifyFormat("f(aaaaaaaaaaaaaaaaaaaa,\n"
5754                "  aaaaaaaaaaaaaaaaaaaa,\n"
5755                "  aaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaa);",
5756                NoBinPacking);
5757   verifyFormat("aaaaaaa(aaaaaaaaaaaaa,\n"
5758                "        aaaaaaaaaaaaa,\n"
5759                "        aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));",
5760                NoBinPacking);
5761   verifyFormat(
5762       "aaaaaaaa(aaaaaaaaaaaaa,\n"
5763       "         aaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5764       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)),\n"
5765       "         aaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5766       "             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)));",
5767       NoBinPacking);
5768   verifyFormat("aaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
5769                "    .aaaaaaaaaaaaaaaaaa();",
5770                NoBinPacking);
5771   verifyFormat("void f() {\n"
5772                "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5773                "      aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaa);\n"
5774                "}",
5775                NoBinPacking);
5776 
5777   verifyFormat(
5778       "aaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
5779       "             aaaaaaaaaaaa,\n"
5780       "             aaaaaaaaaaaa);",
5781       NoBinPacking);
5782   verifyFormat(
5783       "somefunction(someotherFunction(ddddddddddddddddddddddddddddddddddd,\n"
5784       "                               ddddddddddddddddddddddddddddd),\n"
5785       "             test);",
5786       NoBinPacking);
5787 
5788   verifyFormat("std::vector<aaaaaaaaaaaaaaaaaaaaaaa,\n"
5789                "            aaaaaaaaaaaaaaaaaaaaaaa,\n"
5790                "            aaaaaaaaaaaaaaaaaaaaaaa>\n"
5791                "    aaaaaaaaaaaaaaaaaa;",
5792                NoBinPacking);
5793   verifyFormat("a(\"a\"\n"
5794                "  \"a\",\n"
5795                "  a);");
5796 
5797   NoBinPacking.AllowAllParametersOfDeclarationOnNextLine = false;
5798   verifyFormat("void aaaaaaaaaa(aaaaaaaaa,\n"
5799                "                aaaaaaaaa,\n"
5800                "                aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5801                NoBinPacking);
5802   verifyFormat(
5803       "void f() {\n"
5804       "  aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaa, aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa)\n"
5805       "      .aaaaaaa();\n"
5806       "}",
5807       NoBinPacking);
5808   verifyFormat(
5809       "template <class SomeType, class SomeOtherType>\n"
5810       "SomeType SomeFunction(SomeType Type, SomeOtherType OtherType) {}",
5811       NoBinPacking);
5812 }
5813 
5814 TEST_F(FormatTest, AdaptiveOnePerLineFormatting) {
5815   FormatStyle Style = getLLVMStyleWithColumns(15);
5816   Style.ExperimentalAutoDetectBinPacking = true;
5817   EXPECT_EQ("aaa(aaaa,\n"
5818             "    aaaa,\n"
5819             "    aaaa);\n"
5820             "aaa(aaaa,\n"
5821             "    aaaa,\n"
5822             "    aaaa);",
5823             format("aaa(aaaa,\n" // one-per-line
5824                    "  aaaa,\n"
5825                    "    aaaa  );\n"
5826                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
5827                    Style));
5828   EXPECT_EQ("aaa(aaaa, aaaa,\n"
5829             "    aaaa);\n"
5830             "aaa(aaaa, aaaa,\n"
5831             "    aaaa);",
5832             format("aaa(aaaa,  aaaa,\n" // bin-packed
5833                    "    aaaa  );\n"
5834                    "aaa(aaaa,  aaaa,  aaaa);", // inconclusive
5835                    Style));
5836 }
5837 
5838 TEST_F(FormatTest, FormatsBuilderPattern) {
5839   verifyFormat("return llvm::StringSwitch<Reference::Kind>(name)\n"
5840                "    .StartsWith(\".eh_frame_hdr\", ORDER_EH_FRAMEHDR)\n"
5841                "    .StartsWith(\".eh_frame\", ORDER_EH_FRAME)\n"
5842                "    .StartsWith(\".init\", ORDER_INIT)\n"
5843                "    .StartsWith(\".fini\", ORDER_FINI)\n"
5844                "    .StartsWith(\".hash\", ORDER_HASH)\n"
5845                "    .Default(ORDER_TEXT);\n");
5846 
5847   verifyFormat("return aaaaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa() <\n"
5848                "       aaaaaaaaaaaaaaa->aaaaa().aaaaaaaaaaaaa().aaaaaa();");
5849   verifyFormat("aaaaaaa->aaaaaaa\n"
5850                "    ->aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5851                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5852                "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
5853   verifyFormat(
5854       "aaaaaaa->aaaaaaa\n"
5855       "    ->aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5856       "    ->aaaaaaaa(aaaaaaaaaaaaaaa);");
5857   verifyFormat(
5858       "aaaaaaaaaaaaaaaaaaa()->aaaaaa(bbbbb)->aaaaaaaaaaaaaaaaaaa( // break\n"
5859       "    aaaaaaaaaaaaaa);");
5860   verifyFormat(
5861       "aaaaaaaaaaaaaaaaaaaaaaa *aaaaaaaaa =\n"
5862       "    aaaaaa->aaaaaaaaaaaa()\n"
5863       "        ->aaaaaaaaaaaaaaaa(\n"
5864       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5865       "        ->aaaaaaaaaaaaaaaaa();");
5866   verifyGoogleFormat(
5867       "void f() {\n"
5868       "  someo->Add((new util::filetools::Handler(dir))\n"
5869       "                 ->OnEvent1(NewPermanentCallback(\n"
5870       "                     this, &HandlerHolderClass::EventHandlerCBA))\n"
5871       "                 ->OnEvent2(NewPermanentCallback(\n"
5872       "                     this, &HandlerHolderClass::EventHandlerCBB))\n"
5873       "                 ->OnEvent3(NewPermanentCallback(\n"
5874       "                     this, &HandlerHolderClass::EventHandlerCBC))\n"
5875       "                 ->OnEvent5(NewPermanentCallback(\n"
5876       "                     this, &HandlerHolderClass::EventHandlerCBD))\n"
5877       "                 ->OnEvent6(NewPermanentCallback(\n"
5878       "                     this, &HandlerHolderClass::EventHandlerCBE)));\n"
5879       "}");
5880 
5881   verifyFormat(
5882       "aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa().aaaaaaaaaaa();");
5883   verifyFormat("aaaaaaaaaaaaaaa()\n"
5884                "    .aaaaaaaaaaaaaaa()\n"
5885                "    .aaaaaaaaaaaaaaa()\n"
5886                "    .aaaaaaaaaaaaaaa()\n"
5887                "    .aaaaaaaaaaaaaaa();");
5888   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5889                "    .aaaaaaaaaaaaaaa()\n"
5890                "    .aaaaaaaaaaaaaaa()\n"
5891                "    .aaaaaaaaaaaaaaa();");
5892   verifyFormat("aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5893                "    .aaaaaaaaaaaaaaa.aaaaaaaaaaaaaaa()\n"
5894                "    .aaaaaaaaaaaaaaa();");
5895   verifyFormat("aaaaaaaaaaaaa->aaaaaaaaaaaaaaaaaaaaaaaa()\n"
5896                "    ->aaaaaaaaaaaaaae(0)\n"
5897                "    ->aaaaaaaaaaaaaaa();");
5898 
5899   // Don't linewrap after very short segments.
5900   verifyFormat("a().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5901                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5902                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5903   verifyFormat("aa().aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5904                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5905                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5906   verifyFormat("aaa()\n"
5907                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5908                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5909                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
5910 
5911   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
5912                "    .aaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
5913                "    .has<bbbbbbbbbbbbbbbbbbbbb>();");
5914   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaa()\n"
5915                "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
5916                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>();");
5917 
5918   // Prefer not to break after empty parentheses.
5919   verifyFormat("FirstToken->WhitespaceRange.getBegin().getLocWithOffset(\n"
5920                "    First->LastNewlineOffset);");
5921 
5922   // Prefer not to create "hanging" indents.
5923   verifyFormat(
5924       "return !soooooooooooooome_map\n"
5925       "            .insert(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5926       "            .second;");
5927   verifyFormat(
5928       "return aaaaaaaaaaaaaaaa\n"
5929       "    .aaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa)\n"
5930       "    .aaaa(aaaaaaaaaaaaaa);");
5931   // No hanging indent here.
5932   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa.aaaaaaaaaaaaaaa(\n"
5933                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5934   verifyFormat("aaaaaaaaaaaaaaaa.aaaaaaaaaaaaaa().aaaaaaaaaaaaaaa(\n"
5935                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5936   verifyFormat("aaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
5937                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5938                getLLVMStyleWithColumns(60));
5939   verifyFormat("aaaaaaaaaaaaaaaaaa\n"
5940                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa)\n"
5941                "    .aaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
5942                getLLVMStyleWithColumns(59));
5943   verifyFormat("aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
5944                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
5945                "    .aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
5946 
5947   // Dont break if only closing statements before member call
5948   verifyFormat("test() {\n"
5949                "  ([]() -> {\n"
5950                "    int b = 32;\n"
5951                "    return 3;\n"
5952                "  }).foo();\n"
5953                "}");
5954   verifyFormat("test() {\n"
5955                "  (\n"
5956                "      []() -> {\n"
5957                "        int b = 32;\n"
5958                "        return 3;\n"
5959                "      },\n"
5960                "      foo, bar)\n"
5961                "      .foo();\n"
5962                "}");
5963   verifyFormat("test() {\n"
5964                "  ([]() -> {\n"
5965                "    int b = 32;\n"
5966                "    return 3;\n"
5967                "  })\n"
5968                "      .foo()\n"
5969                "      .bar();\n"
5970                "}");
5971   verifyFormat("test() {\n"
5972                "  ([]() -> {\n"
5973                "    int b = 32;\n"
5974                "    return 3;\n"
5975                "  })\n"
5976                "      .foo(\"aaaaaaaaaaaaaaaaa\"\n"
5977                "           \"bbbb\");\n"
5978                "}",
5979                getLLVMStyleWithColumns(30));
5980 }
5981 
5982 TEST_F(FormatTest, BreaksAccordingToOperatorPrecedence) {
5983   verifyFormat(
5984       "if (aaaaaaaaaaaaaaaaaaaaaaaaa ||\n"
5985       "    bbbbbbbbbbbbbbbbbbbbbbbbb && ccccccccccccccccccccccccc) {\n}");
5986   verifyFormat(
5987       "if (aaaaaaaaaaaaaaaaaaaaaaaaa or\n"
5988       "    bbbbbbbbbbbbbbbbbbbbbbbbb and cccccccccccccccccccccccc) {\n}");
5989 
5990   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa && bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
5991                "    ccccccccccccccccccccccccc) {\n}");
5992   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa and bbbbbbbbbbbbbbbbbbbbbbbb or\n"
5993                "    ccccccccccccccccccccccccc) {\n}");
5994 
5995   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb ||\n"
5996                "    ccccccccccccccccccccccccc) {\n}");
5997   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb or\n"
5998                "    ccccccccccccccccccccccccc) {\n}");
5999 
6000   verifyFormat(
6001       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa || bbbbbbbbbbbbbbbbbbbbbbbbb) &&\n"
6002       "    ccccccccccccccccccccccccc) {\n}");
6003   verifyFormat(
6004       "if ((aaaaaaaaaaaaaaaaaaaaaaaaa or bbbbbbbbbbbbbbbbbbbbbbbbb) and\n"
6005       "    ccccccccccccccccccccccccc) {\n}");
6006 
6007   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA ||\n"
6008                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB ||\n"
6009                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC ||\n"
6010                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
6011   verifyFormat("return aaaa & AAAAAAAAAAAAAAAAAAAAAAAAAAAAA or\n"
6012                "       bbbb & BBBBBBBBBBBBBBBBBBBBBBBBBBBBB or\n"
6013                "       cccc & CCCCCCCCCCCCCCCCCCCCCCCCCC or\n"
6014                "       dddd & DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD;");
6015 
6016   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa ||\n"
6017                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) &&\n"
6018                "    aaaaaaaaaaaaaaa != aa) {\n}");
6019   verifyFormat("if ((aaaaaaaaaa != aaaaaaaaaaaaaaa or\n"
6020                "     aaaaaaaaaaaaaaaaaaaaaaaa() >= aaaaaaaaaaaaaaaaaaaa) and\n"
6021                "    aaaaaaaaaaaaaaa != aa) {\n}");
6022 }
6023 
6024 TEST_F(FormatTest, BreaksAfterAssignments) {
6025   verifyFormat(
6026       "unsigned Cost =\n"
6027       "    TTI.getMemoryOpCost(I->getOpcode(), VectorTy, SI->getAlignment(),\n"
6028       "                        SI->getPointerAddressSpaceee());\n");
6029   verifyFormat(
6030       "CharSourceRange LineRange = CharSourceRange::getTokenRange(\n"
6031       "    Line.Tokens.front().Tok.getLo(), Line.Tokens.back().Tok.getLoc());");
6032 
6033   verifyFormat(
6034       "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaa = aaaaaaaaaaaaaa(0).aaaa().aaaaaaaaa(\n"
6035       "    aaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaa);");
6036   verifyFormat("unsigned OriginalStartColumn =\n"
6037                "    SourceMgr.getSpellingColumnNumber(\n"
6038                "        Current.FormatTok.getStartOfNonWhitespace()) -\n"
6039                "    1;");
6040 }
6041 
6042 TEST_F(FormatTest, ConfigurableBreakAssignmentPenalty) {
6043   FormatStyle Style = getLLVMStyle();
6044   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6045                "    bbbbbbbbbbbbbbbbbbbbbbbbbb + cccccccccccccccccccccccccc;",
6046                Style);
6047 
6048   Style.PenaltyBreakAssignment = 20;
6049   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaa = bbbbbbbbbbbbbbbbbbbbbbbbbb +\n"
6050                "                                 cccccccccccccccccccccccccc;",
6051                Style);
6052 }
6053 
6054 TEST_F(FormatTest, AlignsAfterAssignments) {
6055   verifyFormat(
6056       "int Result = aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6057       "             aaaaaaaaaaaaaaaaaaaaaaaaa;");
6058   verifyFormat(
6059       "Result += aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6060       "          aaaaaaaaaaaaaaaaaaaaaaaaa;");
6061   verifyFormat(
6062       "Result >>= aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6063       "           aaaaaaaaaaaaaaaaaaaaaaaaa;");
6064   verifyFormat(
6065       "int Result = (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6066       "              aaaaaaaaaaaaaaaaaaaaaaaaa);");
6067   verifyFormat(
6068       "double LooooooooooooooooooooooooongResult = aaaaaaaaaaaaaaaaaaaaaaaa +\n"
6069       "                                            aaaaaaaaaaaaaaaaaaaaaaaa +\n"
6070       "                                            aaaaaaaaaaaaaaaaaaaaaaaa;");
6071 }
6072 
6073 TEST_F(FormatTest, AlignsAfterReturn) {
6074   verifyFormat(
6075       "return aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6076       "       aaaaaaaaaaaaaaaaaaaaaaaaa;");
6077   verifyFormat(
6078       "return (aaaaaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6079       "        aaaaaaaaaaaaaaaaaaaaaaaaa);");
6080   verifyFormat(
6081       "return aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
6082       "       aaaaaaaaaaaaaaaaaaaaaa();");
6083   verifyFormat(
6084       "return (aaaaaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >=\n"
6085       "        aaaaaaaaaaaaaaaaaaaaaa());");
6086   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6087                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6088   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6089                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) &&\n"
6090                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6091   verifyFormat("return\n"
6092                "    // true if code is one of a or b.\n"
6093                "    code == a || code == b;");
6094 }
6095 
6096 TEST_F(FormatTest, AlignsAfterOpenBracket) {
6097   verifyFormat(
6098       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
6099       "                                                aaaaaaaaa aaaaaaa) {}");
6100   verifyFormat(
6101       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
6102       "                                               aaaaaaaaaaa aaaaaaaaa);");
6103   verifyFormat(
6104       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
6105       "                                             aaaaaaaaaaaaaaaaaaaaa));");
6106   FormatStyle Style = getLLVMStyle();
6107   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6108   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6109                "    aaaaaaaaaaa aaaaaaaa, aaaaaaaaa aaaaaaa) {}",
6110                Style);
6111   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
6112                "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaa aaaaaaaaa);",
6113                Style);
6114   verifyFormat("SomeLongVariableName->someFunction(\n"
6115                "    foooooooo(aaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaa));",
6116                Style);
6117   verifyFormat(
6118       "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaa aaaaaaaa,\n"
6119       "    aaaaaaaaa aaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6120       Style);
6121   verifyFormat(
6122       "SomeLongVariableName->someVeryLongFunctionName(aaaaaaaaaaa aaaaaaaaa,\n"
6123       "    aaaaaaaaaaa aaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6124       Style);
6125   verifyFormat(
6126       "SomeLongVariableName->someFunction(foooooooo(aaaaaaaaaaaaaaa,\n"
6127       "    aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
6128       Style);
6129 
6130   verifyFormat("bbbbbbbbbbbb(aaaaaaaaaaaaaaaaaaaaaaaa, //\n"
6131                "    ccccccc(aaaaaaaaaaaaaaaaa,         //\n"
6132                "        b));",
6133                Style);
6134 
6135   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
6136   Style.BinPackArguments = false;
6137   Style.BinPackParameters = false;
6138   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6139                "    aaaaaaaaaaa aaaaaaaa,\n"
6140                "    aaaaaaaaa aaaaaaa,\n"
6141                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {}",
6142                Style);
6143   verifyFormat("SomeLongVariableName->someVeryLongFunctionName(\n"
6144                "    aaaaaaaaaaa aaaaaaaaa,\n"
6145                "    aaaaaaaaaaa aaaaaaaaa,\n"
6146                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6147                Style);
6148   verifyFormat("SomeLongVariableName->someFunction(foooooooo(\n"
6149                "    aaaaaaaaaaaaaaa,\n"
6150                "    aaaaaaaaaaaaaaaaaaaaa,\n"
6151                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa));",
6152                Style);
6153   verifyFormat(
6154       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa(\n"
6155       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
6156       Style);
6157   verifyFormat(
6158       "aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaa.aaaaaaaaaa(\n"
6159       "    aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)));",
6160       Style);
6161   verifyFormat(
6162       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6163       "    aaaaaaaaaaaaaaaaaaaaa(\n"
6164       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)),\n"
6165       "    aaaaaaaaaaaaaaaa);",
6166       Style);
6167   verifyFormat(
6168       "aaaaaaaaaaaaaaaaaaaaaaaa(\n"
6169       "    aaaaaaaaaaaaaaaaaaaaa(\n"
6170       "        aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa)) &&\n"
6171       "    aaaaaaaaaaaaaaaa);",
6172       Style);
6173 }
6174 
6175 TEST_F(FormatTest, ParenthesesAndOperandAlignment) {
6176   FormatStyle Style = getLLVMStyleWithColumns(40);
6177   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6178                "          bbbbbbbbbbbbbbbbbbbbbb);",
6179                Style);
6180   Style.AlignAfterOpenBracket = FormatStyle::BAS_Align;
6181   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6182   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6183                "          bbbbbbbbbbbbbbbbbbbbbb);",
6184                Style);
6185   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6186   Style.AlignOperands = FormatStyle::OAS_Align;
6187   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6188                "          bbbbbbbbbbbbbbbbbbbbbb);",
6189                Style);
6190   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
6191   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6192   verifyFormat("int a = f(aaaaaaaaaaaaaaaaaaaaaa &&\n"
6193                "    bbbbbbbbbbbbbbbbbbbbbb);",
6194                Style);
6195 }
6196 
6197 TEST_F(FormatTest, BreaksConditionalExpressions) {
6198   verifyFormat(
6199       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6200       "                               ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6201       "                               : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6202   verifyFormat(
6203       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
6204       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6205       "                                : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6206   verifyFormat(
6207       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6208       "                                   : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6209   verifyFormat("aaaa(aaaaaaaaa, aaaaaaaaa,\n"
6210                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6211                "             : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6212   verifyFormat(
6213       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa)\n"
6214       "                                                    : aaaaaaaaaaaaa);");
6215   verifyFormat(
6216       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6217       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6218       "                                    : aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6219       "                   aaaaaaaaaaaaa);");
6220   verifyFormat(
6221       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6222       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6223       "                   aaaaaaaaaaaaa);");
6224   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6225                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6226                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6227                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6228                "          aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6229   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6230                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6231                "           ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6232                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
6233                "           : aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6234                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6235                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6236   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6237                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6238                "           ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6239                "                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6240                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);");
6241   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6242                "    ? aaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6243                "    : aaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6244   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
6245                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6246                "        ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6247                "        : aaaaaaaaaaaaaaaa;");
6248   verifyFormat(
6249       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6250       "    ? aaaaaaaaaaaaaaa\n"
6251       "    : aaaaaaaaaaaaaaa;");
6252   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
6253                "          aaaaaaaaa\n"
6254                "      ? b\n"
6255                "      : c);");
6256   verifyFormat("return aaaa == bbbb\n"
6257                "           // comment\n"
6258                "           ? aaaa\n"
6259                "           : bbbb;");
6260   verifyFormat("unsigned Indent =\n"
6261                "    format(TheLine.First,\n"
6262                "           IndentForLevel[TheLine.Level] >= 0\n"
6263                "               ? IndentForLevel[TheLine.Level]\n"
6264                "               : TheLine * 2,\n"
6265                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
6266                getLLVMStyleWithColumns(60));
6267   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
6268                "                  ? aaaaaaaaaaaaaaa\n"
6269                "                  : bbbbbbbbbbbbbbb //\n"
6270                "                        ? ccccccccccccccc\n"
6271                "                        : ddddddddddddddd;");
6272   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa //\n"
6273                "                  ? aaaaaaaaaaaaaaa\n"
6274                "                  : (bbbbbbbbbbbbbbb //\n"
6275                "                         ? ccccccccccccccc\n"
6276                "                         : ddddddddddddddd);");
6277   verifyFormat(
6278       "int aaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6279       "                                      ? aaaaaaaaaaaaaaaaaaaaaaaaa +\n"
6280       "                                            aaaaaaaaaaaaaaaaaaaaa +\n"
6281       "                                            aaaaaaaaaaaaaaaaaaaaa\n"
6282       "                                      : aaaaaaaaaa;");
6283   verifyFormat(
6284       "aaaaaa = aaaaaaaaaaaa ? aaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6285       "                                   : aaaaaaaaaaaaaaaaaaaaaa\n"
6286       "                      : aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
6287 
6288   FormatStyle NoBinPacking = getLLVMStyle();
6289   NoBinPacking.BinPackArguments = false;
6290   verifyFormat(
6291       "void f() {\n"
6292       "  g(aaa,\n"
6293       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
6294       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6295       "        ? aaaaaaaaaaaaaaa\n"
6296       "        : aaaaaaaaaaaaaaa);\n"
6297       "}",
6298       NoBinPacking);
6299   verifyFormat(
6300       "void f() {\n"
6301       "  g(aaa,\n"
6302       "    aaaaaaaaaa == aaaaaaaaaa ? aaaa : aaaaa,\n"
6303       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6304       "        ?: aaaaaaaaaaaaaaa);\n"
6305       "}",
6306       NoBinPacking);
6307 
6308   verifyFormat("SomeFunction(aaaaaaaaaaaaaaaaa,\n"
6309                "             // comment.\n"
6310                "             ccccccccccccccccccccccccccccccccccccccc\n"
6311                "                 ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6312                "                 : bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);");
6313 
6314   // Assignments in conditional expressions. Apparently not uncommon :-(.
6315   verifyFormat("return a != b\n"
6316                "           // comment\n"
6317                "           ? a = b\n"
6318                "           : a = b;");
6319   verifyFormat("return a != b\n"
6320                "           // comment\n"
6321                "           ? a = a != b\n"
6322                "                     // comment\n"
6323                "                     ? a = b\n"
6324                "                     : a\n"
6325                "           : a;\n");
6326   verifyFormat("return a != b\n"
6327                "           // comment\n"
6328                "           ? a\n"
6329                "           : a = a != b\n"
6330                "                     // comment\n"
6331                "                     ? a = b\n"
6332                "                     : a;");
6333 
6334   // Chained conditionals
6335   FormatStyle Style = getLLVMStyle();
6336   Style.ColumnLimit = 70;
6337   Style.AlignOperands = FormatStyle::OAS_Align;
6338   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6339                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6340                "                        : 3333333333333333;",
6341                Style);
6342   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6343                "       : bbbbbbbbbb     ? 2222222222222222\n"
6344                "                        : 3333333333333333;",
6345                Style);
6346   verifyFormat("return aaaaaaaaaa         ? 1111111111111111\n"
6347                "       : bbbbbbbbbbbbbbbb ? 2222222222222222\n"
6348                "                          : 3333333333333333;",
6349                Style);
6350   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6351                "       : bbbbbbbbbbbbbb ? 222222\n"
6352                "                        : 333333;",
6353                Style);
6354   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6355                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6356                "       : cccccccccccccc ? 3333333333333333\n"
6357                "                        : 4444444444444444;",
6358                Style);
6359   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc)\n"
6360                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6361                "                        : 3333333333333333;",
6362                Style);
6363   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6364                "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6365                "                        : (aaa ? bbb : ccc);",
6366                Style);
6367   verifyFormat(
6368       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6369       "                                             : cccccccccccccccccc)\n"
6370       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6371       "                        : 3333333333333333;",
6372       Style);
6373   verifyFormat(
6374       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6375       "                                             : cccccccccccccccccc)\n"
6376       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6377       "                        : 3333333333333333;",
6378       Style);
6379   verifyFormat(
6380       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6381       "                                             : dddddddddddddddddd)\n"
6382       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6383       "                        : 3333333333333333;",
6384       Style);
6385   verifyFormat(
6386       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6387       "                                             : dddddddddddddddddd)\n"
6388       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6389       "                        : 3333333333333333;",
6390       Style);
6391   verifyFormat(
6392       "return aaaaaaaaa        ? 1111111111111111\n"
6393       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6394       "                        : a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6395       "                                             : dddddddddddddddddd)\n",
6396       Style);
6397   verifyFormat(
6398       "return aaaaaaaaaaaaaaaa ? 1111111111111111\n"
6399       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6400       "                        : (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6401       "                                             : cccccccccccccccccc);",
6402       Style);
6403   verifyFormat(
6404       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6405       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6406       "                                             : eeeeeeeeeeeeeeeeee)\n"
6407       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6408       "                        : 3333333333333333;",
6409       Style);
6410   verifyFormat(
6411       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaa    ? bbbbbbbbbbbbbbbbbb\n"
6412       "                           : ccccccccccccccc ? dddddddddddddddddd\n"
6413       "                                             : eeeeeeeeeeeeeeeeee)\n"
6414       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6415       "                        : 3333333333333333;",
6416       Style);
6417   verifyFormat(
6418       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6419       "                           : cccccccccccc    ? dddddddddddddddddd\n"
6420       "                                             : eeeeeeeeeeeeeeeeee)\n"
6421       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6422       "                        : 3333333333333333;",
6423       Style);
6424   verifyFormat(
6425       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6426       "                                             : cccccccccccccccccc\n"
6427       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6428       "                        : 3333333333333333;",
6429       Style);
6430   verifyFormat(
6431       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6432       "                          : cccccccccccccccc ? dddddddddddddddddd\n"
6433       "                                             : eeeeeeeeeeeeeeeeee\n"
6434       "       : bbbbbbbbbbbbbb ? 2222222222222222\n"
6435       "                        : 3333333333333333;",
6436       Style);
6437   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa\n"
6438                "           ? (aaaaaaaaaaaaaaaaaa   ? bbbbbbbbbbbbbbbbbb\n"
6439                "              : cccccccccccccccccc ? dddddddddddddddddd\n"
6440                "                                   : eeeeeeeeeeeeeeeeee)\n"
6441                "       : bbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
6442                "                             : 3333333333333333;",
6443                Style);
6444   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaa\n"
6445                "           ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb\n"
6446                "             : cccccccccccccccc ? dddddddddddddddddd\n"
6447                "                                : eeeeeeeeeeeeeeeeee\n"
6448                "       : bbbbbbbbbbbbbbbbbbbbbbb ? 2222222222222222\n"
6449                "                                 : 3333333333333333;",
6450                Style);
6451 
6452   Style.AlignOperands = FormatStyle::OAS_DontAlign;
6453   Style.BreakBeforeTernaryOperators = false;
6454   // FIXME: Aligning the question marks is weird given DontAlign.
6455   // Consider disabling this alignment in this case. Also check whether this
6456   // will render the adjustment from https://reviews.llvm.org/D82199
6457   // unnecessary.
6458   verifyFormat("int x = aaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa :\n"
6459                "    bbbb                ? cccccccccccccccccc :\n"
6460                "                          ddddd;\n",
6461                Style);
6462 }
6463 
6464 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
6465   FormatStyle Style = getLLVMStyle();
6466   Style.BreakBeforeTernaryOperators = false;
6467   Style.ColumnLimit = 70;
6468   verifyFormat(
6469       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6470       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6471       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6472       Style);
6473   verifyFormat(
6474       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
6475       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6476       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6477       Style);
6478   verifyFormat(
6479       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6480       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6481       Style);
6482   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
6483                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6484                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6485                Style);
6486   verifyFormat(
6487       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
6488       "                                                      aaaaaaaaaaaaa);",
6489       Style);
6490   verifyFormat(
6491       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6492       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6493       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6494       "                   aaaaaaaaaaaaa);",
6495       Style);
6496   verifyFormat(
6497       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6498       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6499       "                   aaaaaaaaaaaaa);",
6500       Style);
6501   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6502                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6503                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6504                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6505                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6506                Style);
6507   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6508                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6509                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6510                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6511                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6512                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6513                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6514                Style);
6515   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6516                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
6517                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6518                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6519                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6520                Style);
6521   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6522                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6523                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6524                Style);
6525   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
6526                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6527                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6528                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6529                Style);
6530   verifyFormat(
6531       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6532       "    aaaaaaaaaaaaaaa :\n"
6533       "    aaaaaaaaaaaaaaa;",
6534       Style);
6535   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
6536                "          aaaaaaaaa ?\n"
6537                "      b :\n"
6538                "      c);",
6539                Style);
6540   verifyFormat("unsigned Indent =\n"
6541                "    format(TheLine.First,\n"
6542                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
6543                "               IndentForLevel[TheLine.Level] :\n"
6544                "               TheLine * 2,\n"
6545                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
6546                Style);
6547   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6548                "                  aaaaaaaaaaaaaaa :\n"
6549                "                  bbbbbbbbbbbbbbb ? //\n"
6550                "                      ccccccccccccccc :\n"
6551                "                      ddddddddddddddd;",
6552                Style);
6553   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6554                "                  aaaaaaaaaaaaaaa :\n"
6555                "                  (bbbbbbbbbbbbbbb ? //\n"
6556                "                       ccccccccccccccc :\n"
6557                "                       ddddddddddddddd);",
6558                Style);
6559   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6560                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
6561                "            ccccccccccccccccccccccccccc;",
6562                Style);
6563   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6564                "           aaaaa :\n"
6565                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
6566                Style);
6567 
6568   // Chained conditionals
6569   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6570                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6571                "                          3333333333333333;",
6572                Style);
6573   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6574                "       bbbbbbbbbb       ? 2222222222222222 :\n"
6575                "                          3333333333333333;",
6576                Style);
6577   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
6578                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6579                "                          3333333333333333;",
6580                Style);
6581   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6582                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
6583                "                          333333;",
6584                Style);
6585   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6586                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6587                "       cccccccccccccccc ? 3333333333333333 :\n"
6588                "                          4444444444444444;",
6589                Style);
6590   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
6591                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6592                "                          3333333333333333;",
6593                Style);
6594   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6595                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6596                "                          (aaa ? bbb : ccc);",
6597                Style);
6598   verifyFormat(
6599       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6600       "                                               cccccccccccccccccc) :\n"
6601       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6602       "                          3333333333333333;",
6603       Style);
6604   verifyFormat(
6605       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6606       "                                               cccccccccccccccccc) :\n"
6607       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6608       "                          3333333333333333;",
6609       Style);
6610   verifyFormat(
6611       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6612       "                                               dddddddddddddddddd) :\n"
6613       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6614       "                          3333333333333333;",
6615       Style);
6616   verifyFormat(
6617       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6618       "                                               dddddddddddddddddd) :\n"
6619       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6620       "                          3333333333333333;",
6621       Style);
6622   verifyFormat(
6623       "return aaaaaaaaa        ? 1111111111111111 :\n"
6624       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6625       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6626       "                                               dddddddddddddddddd)\n",
6627       Style);
6628   verifyFormat(
6629       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6630       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6631       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6632       "                                               cccccccccccccccccc);",
6633       Style);
6634   verifyFormat(
6635       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6636       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
6637       "                                               eeeeeeeeeeeeeeeeee) :\n"
6638       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6639       "                          3333333333333333;",
6640       Style);
6641   verifyFormat(
6642       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6643       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
6644       "                                               eeeeeeeeeeeeeeeeee) :\n"
6645       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6646       "                          3333333333333333;",
6647       Style);
6648   verifyFormat(
6649       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
6650       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
6651       "                                               eeeeeeeeeeeeeeeeee) :\n"
6652       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6653       "                          3333333333333333;",
6654       Style);
6655   verifyFormat(
6656       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6657       "                                               cccccccccccccccccc :\n"
6658       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6659       "                          3333333333333333;",
6660       Style);
6661   verifyFormat(
6662       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6663       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
6664       "                                               eeeeeeeeeeeeeeeeee :\n"
6665       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6666       "                          3333333333333333;",
6667       Style);
6668   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
6669                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6670                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
6671                "                                 eeeeeeeeeeeeeeeeee) :\n"
6672                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6673                "                               3333333333333333;",
6674                Style);
6675   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
6676                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6677                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
6678                "                                  eeeeeeeeeeeeeeeeee :\n"
6679                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6680                "                               3333333333333333;",
6681                Style);
6682 }
6683 
6684 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
6685   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
6686                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
6687   verifyFormat("bool a = true, b = false;");
6688 
6689   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6690                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
6691                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
6692                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
6693   verifyFormat(
6694       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6695       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
6696       "     d = e && f;");
6697   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
6698                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
6699   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
6700                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
6701   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
6702                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
6703 
6704   FormatStyle Style = getGoogleStyle();
6705   Style.PointerAlignment = FormatStyle::PAS_Left;
6706   Style.DerivePointerAlignment = false;
6707   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6708                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
6709                "    *b = bbbbbbbbbbbbbbbbbbb;",
6710                Style);
6711   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
6712                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
6713                Style);
6714   verifyFormat("vector<int*> a, b;", Style);
6715   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
6716 }
6717 
6718 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
6719   verifyFormat("arr[foo ? bar : baz];");
6720   verifyFormat("f()[foo ? bar : baz];");
6721   verifyFormat("(a + b)[foo ? bar : baz];");
6722   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
6723 }
6724 
6725 TEST_F(FormatTest, AlignsStringLiterals) {
6726   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
6727                "                                      \"short literal\");");
6728   verifyFormat(
6729       "looooooooooooooooooooooooongFunction(\n"
6730       "    \"short literal\"\n"
6731       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
6732   verifyFormat("someFunction(\"Always break between multi-line\"\n"
6733                "             \" string literals\",\n"
6734                "             and, other, parameters);");
6735   EXPECT_EQ("fun + \"1243\" /* comment */\n"
6736             "      \"5678\";",
6737             format("fun + \"1243\" /* comment */\n"
6738                    "    \"5678\";",
6739                    getLLVMStyleWithColumns(28)));
6740   EXPECT_EQ(
6741       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
6742       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
6743       "         \"aaaaaaaaaaaaaaaa\";",
6744       format("aaaaaa ="
6745              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
6746              "aaaaaaaaaaaaaaaaaaaaa\" "
6747              "\"aaaaaaaaaaaaaaaa\";"));
6748   verifyFormat("a = a + \"a\"\n"
6749                "        \"a\"\n"
6750                "        \"a\";");
6751   verifyFormat("f(\"a\", \"b\"\n"
6752                "       \"c\");");
6753 
6754   verifyFormat(
6755       "#define LL_FORMAT \"ll\"\n"
6756       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
6757       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
6758 
6759   verifyFormat("#define A(X)          \\\n"
6760                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
6761                "  \"ccccc\"",
6762                getLLVMStyleWithColumns(23));
6763   verifyFormat("#define A \"def\"\n"
6764                "f(\"abc\" A \"ghi\"\n"
6765                "  \"jkl\");");
6766 
6767   verifyFormat("f(L\"a\"\n"
6768                "  L\"b\");");
6769   verifyFormat("#define A(X)            \\\n"
6770                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
6771                "  L\"ccccc\"",
6772                getLLVMStyleWithColumns(25));
6773 
6774   verifyFormat("f(@\"a\"\n"
6775                "  @\"b\");");
6776   verifyFormat("NSString s = @\"a\"\n"
6777                "             @\"b\"\n"
6778                "             @\"c\";");
6779   verifyFormat("NSString s = @\"a\"\n"
6780                "              \"b\"\n"
6781                "              \"c\";");
6782 }
6783 
6784 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
6785   FormatStyle Style = getLLVMStyle();
6786   // No declarations or definitions should be moved to own line.
6787   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
6788   verifyFormat("class A {\n"
6789                "  int f() { return 1; }\n"
6790                "  int g();\n"
6791                "};\n"
6792                "int f() { return 1; }\n"
6793                "int g();\n",
6794                Style);
6795 
6796   // All declarations and definitions should have the return type moved to its
6797   // own line.
6798   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
6799   Style.TypenameMacros = {"LIST"};
6800   verifyFormat("SomeType\n"
6801                "funcdecl(LIST(uint64_t));",
6802                Style);
6803   verifyFormat("class E {\n"
6804                "  int\n"
6805                "  f() {\n"
6806                "    return 1;\n"
6807                "  }\n"
6808                "  int\n"
6809                "  g();\n"
6810                "};\n"
6811                "int\n"
6812                "f() {\n"
6813                "  return 1;\n"
6814                "}\n"
6815                "int\n"
6816                "g();\n",
6817                Style);
6818 
6819   // Top-level definitions, and no kinds of declarations should have the
6820   // return type moved to its own line.
6821   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
6822   verifyFormat("class B {\n"
6823                "  int f() { return 1; }\n"
6824                "  int g();\n"
6825                "};\n"
6826                "int\n"
6827                "f() {\n"
6828                "  return 1;\n"
6829                "}\n"
6830                "int g();\n",
6831                Style);
6832 
6833   // Top-level definitions and declarations should have the return type moved
6834   // to its own line.
6835   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
6836   verifyFormat("class C {\n"
6837                "  int f() { return 1; }\n"
6838                "  int g();\n"
6839                "};\n"
6840                "int\n"
6841                "f() {\n"
6842                "  return 1;\n"
6843                "}\n"
6844                "int\n"
6845                "g();\n",
6846                Style);
6847 
6848   // All definitions should have the return type moved to its own line, but no
6849   // kinds of declarations.
6850   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
6851   verifyFormat("class D {\n"
6852                "  int\n"
6853                "  f() {\n"
6854                "    return 1;\n"
6855                "  }\n"
6856                "  int g();\n"
6857                "};\n"
6858                "int\n"
6859                "f() {\n"
6860                "  return 1;\n"
6861                "}\n"
6862                "int g();\n",
6863                Style);
6864   verifyFormat("const char *\n"
6865                "f(void) {\n" // Break here.
6866                "  return \"\";\n"
6867                "}\n"
6868                "const char *bar(void);\n", // No break here.
6869                Style);
6870   verifyFormat("template <class T>\n"
6871                "T *\n"
6872                "f(T &c) {\n" // Break here.
6873                "  return NULL;\n"
6874                "}\n"
6875                "template <class T> T *f(T &c);\n", // No break here.
6876                Style);
6877   verifyFormat("class C {\n"
6878                "  int\n"
6879                "  operator+() {\n"
6880                "    return 1;\n"
6881                "  }\n"
6882                "  int\n"
6883                "  operator()() {\n"
6884                "    return 1;\n"
6885                "  }\n"
6886                "};\n",
6887                Style);
6888   verifyFormat("void\n"
6889                "A::operator()() {}\n"
6890                "void\n"
6891                "A::operator>>() {}\n"
6892                "void\n"
6893                "A::operator+() {}\n"
6894                "void\n"
6895                "A::operator*() {}\n"
6896                "void\n"
6897                "A::operator->() {}\n"
6898                "void\n"
6899                "A::operator void *() {}\n"
6900                "void\n"
6901                "A::operator void &() {}\n"
6902                "void\n"
6903                "A::operator void &&() {}\n"
6904                "void\n"
6905                "A::operator char *() {}\n"
6906                "void\n"
6907                "A::operator[]() {}\n"
6908                "void\n"
6909                "A::operator!() {}\n"
6910                "void\n"
6911                "A::operator**() {}\n"
6912                "void\n"
6913                "A::operator<Foo> *() {}\n"
6914                "void\n"
6915                "A::operator<Foo> **() {}\n"
6916                "void\n"
6917                "A::operator<Foo> &() {}\n"
6918                "void\n"
6919                "A::operator void **() {}\n",
6920                Style);
6921   verifyFormat("constexpr auto\n"
6922                "operator()() const -> reference {}\n"
6923                "constexpr auto\n"
6924                "operator>>() const -> reference {}\n"
6925                "constexpr auto\n"
6926                "operator+() const -> reference {}\n"
6927                "constexpr auto\n"
6928                "operator*() const -> reference {}\n"
6929                "constexpr auto\n"
6930                "operator->() const -> reference {}\n"
6931                "constexpr auto\n"
6932                "operator++() const -> reference {}\n"
6933                "constexpr auto\n"
6934                "operator void *() const -> reference {}\n"
6935                "constexpr auto\n"
6936                "operator void **() const -> reference {}\n"
6937                "constexpr auto\n"
6938                "operator void *() const -> reference {}\n"
6939                "constexpr auto\n"
6940                "operator void &() const -> reference {}\n"
6941                "constexpr auto\n"
6942                "operator void &&() const -> reference {}\n"
6943                "constexpr auto\n"
6944                "operator char *() const -> reference {}\n"
6945                "constexpr auto\n"
6946                "operator!() const -> reference {}\n"
6947                "constexpr auto\n"
6948                "operator[]() const -> reference {}\n",
6949                Style);
6950   verifyFormat("void *operator new(std::size_t s);", // No break here.
6951                Style);
6952   verifyFormat("void *\n"
6953                "operator new(std::size_t s) {}",
6954                Style);
6955   verifyFormat("void *\n"
6956                "operator delete[](void *ptr) {}",
6957                Style);
6958   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
6959   verifyFormat("const char *\n"
6960                "f(void)\n" // Break here.
6961                "{\n"
6962                "  return \"\";\n"
6963                "}\n"
6964                "const char *bar(void);\n", // No break here.
6965                Style);
6966   verifyFormat("template <class T>\n"
6967                "T *\n"     // Problem here: no line break
6968                "f(T &c)\n" // Break here.
6969                "{\n"
6970                "  return NULL;\n"
6971                "}\n"
6972                "template <class T> T *f(T &c);\n", // No break here.
6973                Style);
6974   verifyFormat("int\n"
6975                "foo(A<bool> a)\n"
6976                "{\n"
6977                "  return a;\n"
6978                "}\n",
6979                Style);
6980   verifyFormat("int\n"
6981                "foo(A<8> a)\n"
6982                "{\n"
6983                "  return a;\n"
6984                "}\n",
6985                Style);
6986   verifyFormat("int\n"
6987                "foo(A<B<bool>, 8> a)\n"
6988                "{\n"
6989                "  return a;\n"
6990                "}\n",
6991                Style);
6992   verifyFormat("int\n"
6993                "foo(A<B<8>, bool> a)\n"
6994                "{\n"
6995                "  return a;\n"
6996                "}\n",
6997                Style);
6998   verifyFormat("int\n"
6999                "foo(A<B<bool>, bool> a)\n"
7000                "{\n"
7001                "  return a;\n"
7002                "}\n",
7003                Style);
7004   verifyFormat("int\n"
7005                "foo(A<B<8>, 8> a)\n"
7006                "{\n"
7007                "  return a;\n"
7008                "}\n",
7009                Style);
7010 
7011   Style = getGNUStyle();
7012 
7013   // Test for comments at the end of function declarations.
7014   verifyFormat("void\n"
7015                "foo (int a, /*abc*/ int b) // def\n"
7016                "{\n"
7017                "}\n",
7018                Style);
7019 
7020   verifyFormat("void\n"
7021                "foo (int a, /* abc */ int b) /* def */\n"
7022                "{\n"
7023                "}\n",
7024                Style);
7025 
7026   // Definitions that should not break after return type
7027   verifyFormat("void foo (int a, int b); // def\n", Style);
7028   verifyFormat("void foo (int a, int b); /* def */\n", Style);
7029   verifyFormat("void foo (int a, int b);\n", Style);
7030 }
7031 
7032 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
7033   FormatStyle NoBreak = getLLVMStyle();
7034   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
7035   FormatStyle Break = getLLVMStyle();
7036   Break.AlwaysBreakBeforeMultilineStrings = true;
7037   verifyFormat("aaaa = \"bbbb\"\n"
7038                "       \"cccc\";",
7039                NoBreak);
7040   verifyFormat("aaaa =\n"
7041                "    \"bbbb\"\n"
7042                "    \"cccc\";",
7043                Break);
7044   verifyFormat("aaaa(\"bbbb\"\n"
7045                "     \"cccc\");",
7046                NoBreak);
7047   verifyFormat("aaaa(\n"
7048                "    \"bbbb\"\n"
7049                "    \"cccc\");",
7050                Break);
7051   verifyFormat("aaaa(qqq, \"bbbb\"\n"
7052                "          \"cccc\");",
7053                NoBreak);
7054   verifyFormat("aaaa(qqq,\n"
7055                "     \"bbbb\"\n"
7056                "     \"cccc\");",
7057                Break);
7058   verifyFormat("aaaa(qqq,\n"
7059                "     L\"bbbb\"\n"
7060                "     L\"cccc\");",
7061                Break);
7062   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
7063                "                      \"bbbb\"));",
7064                Break);
7065   verifyFormat("string s = someFunction(\n"
7066                "    \"abc\"\n"
7067                "    \"abc\");",
7068                Break);
7069 
7070   // As we break before unary operators, breaking right after them is bad.
7071   verifyFormat("string foo = abc ? \"x\"\n"
7072                "                   \"blah blah blah blah blah blah\"\n"
7073                "                 : \"y\";",
7074                Break);
7075 
7076   // Don't break if there is no column gain.
7077   verifyFormat("f(\"aaaa\"\n"
7078                "  \"bbbb\");",
7079                Break);
7080 
7081   // Treat literals with escaped newlines like multi-line string literals.
7082   EXPECT_EQ("x = \"a\\\n"
7083             "b\\\n"
7084             "c\";",
7085             format("x = \"a\\\n"
7086                    "b\\\n"
7087                    "c\";",
7088                    NoBreak));
7089   EXPECT_EQ("xxxx =\n"
7090             "    \"a\\\n"
7091             "b\\\n"
7092             "c\";",
7093             format("xxxx = \"a\\\n"
7094                    "b\\\n"
7095                    "c\";",
7096                    Break));
7097 
7098   EXPECT_EQ("NSString *const kString =\n"
7099             "    @\"aaaa\"\n"
7100             "    @\"bbbb\";",
7101             format("NSString *const kString = @\"aaaa\"\n"
7102                    "@\"bbbb\";",
7103                    Break));
7104 
7105   Break.ColumnLimit = 0;
7106   verifyFormat("const char *hello = \"hello llvm\";", Break);
7107 }
7108 
7109 TEST_F(FormatTest, AlignsPipes) {
7110   verifyFormat(
7111       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7112       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7113       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7114   verifyFormat(
7115       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
7116       "                     << aaaaaaaaaaaaaaaaaaaa;");
7117   verifyFormat(
7118       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7119       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7120   verifyFormat(
7121       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7122       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7123   verifyFormat(
7124       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
7125       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
7126       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
7127   verifyFormat(
7128       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7129       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7130       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7131   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7132                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7133                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7134                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7135   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
7136                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
7137   verifyFormat(
7138       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7139       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7140   verifyFormat(
7141       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
7142       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
7143 
7144   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
7145                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
7146   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7147                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7148                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
7149                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
7150   verifyFormat("LOG_IF(aaa == //\n"
7151                "       bbb)\n"
7152                "    << a << b;");
7153 
7154   // But sometimes, breaking before the first "<<" is desirable.
7155   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7156                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
7157   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
7158                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7159                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7160   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
7161                "    << BEF << IsTemplate << Description << E->getType();");
7162   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7163                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7164                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7165   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7166                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7167                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7168                "    << aaa;");
7169 
7170   verifyFormat(
7171       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7172       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7173 
7174   // Incomplete string literal.
7175   EXPECT_EQ("llvm::errs() << \"\n"
7176             "             << a;",
7177             format("llvm::errs() << \"\n<<a;"));
7178 
7179   verifyFormat("void f() {\n"
7180                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
7181                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
7182                "}");
7183 
7184   // Handle 'endl'.
7185   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
7186                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
7187   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
7188 
7189   // Handle '\n'.
7190   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
7191                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
7192   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
7193                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
7194   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
7195                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
7196   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
7197 }
7198 
7199 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
7200   verifyFormat("return out << \"somepacket = {\\n\"\n"
7201                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
7202                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
7203                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
7204                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
7205                "           << \"}\";");
7206 
7207   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
7208                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
7209                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
7210   verifyFormat(
7211       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
7212       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
7213       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
7214       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
7215       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
7216   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
7217                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7218   verifyFormat(
7219       "void f() {\n"
7220       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
7221       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7222       "}");
7223 
7224   // Breaking before the first "<<" is generally not desirable.
7225   verifyFormat(
7226       "llvm::errs()\n"
7227       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7228       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7229       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7230       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7231       getLLVMStyleWithColumns(70));
7232   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7233                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7234                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7235                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7236                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7237                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7238                getLLVMStyleWithColumns(70));
7239 
7240   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
7241                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
7242                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
7243   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
7244                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
7245                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
7246   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
7247                "           (aaaa + aaaa);",
7248                getLLVMStyleWithColumns(40));
7249   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
7250                "                  (aaaaaaa + aaaaa));",
7251                getLLVMStyleWithColumns(40));
7252   verifyFormat(
7253       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
7254       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
7255       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
7256 }
7257 
7258 TEST_F(FormatTest, UnderstandsEquals) {
7259   verifyFormat(
7260       "aaaaaaaaaaaaaaaaa =\n"
7261       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7262   verifyFormat(
7263       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7264       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
7265   verifyFormat(
7266       "if (a) {\n"
7267       "  f();\n"
7268       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7269       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
7270       "}");
7271 
7272   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7273                "        100000000 + 10000000) {\n}");
7274 }
7275 
7276 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
7277   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
7278                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
7279 
7280   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
7281                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
7282 
7283   verifyFormat(
7284       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
7285       "                                                          Parameter2);");
7286 
7287   verifyFormat(
7288       "ShortObject->shortFunction(\n"
7289       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
7290       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
7291 
7292   verifyFormat("loooooooooooooongFunction(\n"
7293                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
7294 
7295   verifyFormat(
7296       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
7297       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
7298 
7299   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
7300                "    .WillRepeatedly(Return(SomeValue));");
7301   verifyFormat("void f() {\n"
7302                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
7303                "      .Times(2)\n"
7304                "      .WillRepeatedly(Return(SomeValue));\n"
7305                "}");
7306   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
7307                "    ccccccccccccccccccccccc);");
7308   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7309                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7310                "          .aaaaa(aaaaa),\n"
7311                "      aaaaaaaaaaaaaaaaaaaaa);");
7312   verifyFormat("void f() {\n"
7313                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7314                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
7315                "}");
7316   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7317                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7318                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7319                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7320                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7321   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7322                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7323                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7324                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
7325                "}");
7326 
7327   // Here, it is not necessary to wrap at "." or "->".
7328   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
7329                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
7330   verifyFormat(
7331       "aaaaaaaaaaa->aaaaaaaaa(\n"
7332       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7333       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
7334 
7335   verifyFormat(
7336       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7337       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
7338   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
7339                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
7340   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
7341                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
7342 
7343   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7344                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7345                "    .a();");
7346 
7347   FormatStyle NoBinPacking = getLLVMStyle();
7348   NoBinPacking.BinPackParameters = false;
7349   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7350                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7351                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
7352                "                         aaaaaaaaaaaaaaaaaaa,\n"
7353                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7354                NoBinPacking);
7355 
7356   // If there is a subsequent call, change to hanging indentation.
7357   verifyFormat(
7358       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7359       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
7360       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7361   verifyFormat(
7362       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7363       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
7364   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7365                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7366                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7367   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7368                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7369                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
7370 }
7371 
7372 TEST_F(FormatTest, WrapsTemplateDeclarations) {
7373   verifyFormat("template <typename T>\n"
7374                "virtual void loooooooooooongFunction(int Param1, int Param2);");
7375   verifyFormat("template <typename T>\n"
7376                "// T should be one of {A, B}.\n"
7377                "virtual void loooooooooooongFunction(int Param1, int Param2);");
7378   verifyFormat(
7379       "template <typename T>\n"
7380       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
7381   verifyFormat("template <typename T>\n"
7382                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
7383                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
7384   verifyFormat(
7385       "template <typename T>\n"
7386       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
7387       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
7388   verifyFormat(
7389       "template <typename T>\n"
7390       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
7391       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
7392       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7393   verifyFormat("template <typename T>\n"
7394                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7395                "    int aaaaaaaaaaaaaaaaaaaaaa);");
7396   verifyFormat(
7397       "template <typename T1, typename T2 = char, typename T3 = char,\n"
7398       "          typename T4 = char>\n"
7399       "void f();");
7400   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
7401                "          template <typename> class cccccccccccccccccccccc,\n"
7402                "          typename ddddddddddddd>\n"
7403                "class C {};");
7404   verifyFormat(
7405       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
7406       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7407 
7408   verifyFormat("void f() {\n"
7409                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
7410                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
7411                "}");
7412 
7413   verifyFormat("template <typename T> class C {};");
7414   verifyFormat("template <typename T> void f();");
7415   verifyFormat("template <typename T> void f() {}");
7416   verifyFormat(
7417       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
7418       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7419       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
7420       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
7421       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7422       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
7423       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
7424       getLLVMStyleWithColumns(72));
7425   EXPECT_EQ("static_cast<A< //\n"
7426             "    B> *>(\n"
7427             "\n"
7428             ");",
7429             format("static_cast<A<//\n"
7430                    "    B>*>(\n"
7431                    "\n"
7432                    "    );"));
7433   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7434                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
7435 
7436   FormatStyle AlwaysBreak = getLLVMStyle();
7437   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7438   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
7439   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
7440   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
7441   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7442                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
7443                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
7444   verifyFormat("template <template <typename> class Fooooooo,\n"
7445                "          template <typename> class Baaaaaaar>\n"
7446                "struct C {};",
7447                AlwaysBreak);
7448   verifyFormat("template <typename T> // T can be A, B or C.\n"
7449                "struct C {};",
7450                AlwaysBreak);
7451   verifyFormat("template <enum E> class A {\n"
7452                "public:\n"
7453                "  E *f();\n"
7454                "};");
7455 
7456   FormatStyle NeverBreak = getLLVMStyle();
7457   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
7458   verifyFormat("template <typename T> class C {};", NeverBreak);
7459   verifyFormat("template <typename T> void f();", NeverBreak);
7460   verifyFormat("template <typename T> void f() {}", NeverBreak);
7461   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
7462                "bbbbbbbbbbbbbbbbbbbb) {}",
7463                NeverBreak);
7464   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7465                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
7466                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
7467                NeverBreak);
7468   verifyFormat("template <template <typename> class Fooooooo,\n"
7469                "          template <typename> class Baaaaaaar>\n"
7470                "struct C {};",
7471                NeverBreak);
7472   verifyFormat("template <typename T> // T can be A, B or C.\n"
7473                "struct C {};",
7474                NeverBreak);
7475   verifyFormat("template <enum E> class A {\n"
7476                "public:\n"
7477                "  E *f();\n"
7478                "};",
7479                NeverBreak);
7480   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
7481   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
7482                "bbbbbbbbbbbbbbbbbbbb) {}",
7483                NeverBreak);
7484 }
7485 
7486 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
7487   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
7488   Style.ColumnLimit = 60;
7489   EXPECT_EQ("// Baseline - no comments.\n"
7490             "template <\n"
7491             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
7492             "void f() {}",
7493             format("// Baseline - no comments.\n"
7494                    "template <\n"
7495                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
7496                    "void f() {}",
7497                    Style));
7498 
7499   EXPECT_EQ("template <\n"
7500             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
7501             "void f() {}",
7502             format("template <\n"
7503                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7504                    "void f() {}",
7505                    Style));
7506 
7507   EXPECT_EQ(
7508       "template <\n"
7509       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
7510       "void f() {}",
7511       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
7512              "void f() {}",
7513              Style));
7514 
7515   EXPECT_EQ(
7516       "template <\n"
7517       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
7518       "                                               // multiline\n"
7519       "void f() {}",
7520       format("template <\n"
7521              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7522              "                                              // multiline\n"
7523              "void f() {}",
7524              Style));
7525 
7526   EXPECT_EQ(
7527       "template <typename aaaaaaaaaa<\n"
7528       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
7529       "void f() {}",
7530       format(
7531           "template <\n"
7532           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
7533           "void f() {}",
7534           Style));
7535 }
7536 
7537 TEST_F(FormatTest, WrapsTemplateParameters) {
7538   FormatStyle Style = getLLVMStyle();
7539   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7540   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
7541   verifyFormat(
7542       "template <typename... a> struct q {};\n"
7543       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
7544       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
7545       "    y;",
7546       Style);
7547   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7548   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
7549   verifyFormat(
7550       "template <typename... a> struct r {};\n"
7551       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
7552       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
7553       "    y;",
7554       Style);
7555   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7556   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
7557   verifyFormat("template <typename... a> struct s {};\n"
7558                "extern s<\n"
7559                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7560                "aaaaaaaaaaaaaaaaaaaaaa,\n"
7561                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7562                "aaaaaaaaaaaaaaaaaaaaaa>\n"
7563                "    y;",
7564                Style);
7565   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7566   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
7567   verifyFormat("template <typename... a> struct t {};\n"
7568                "extern t<\n"
7569                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7570                "aaaaaaaaaaaaaaaaaaaaaa,\n"
7571                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7572                "aaaaaaaaaaaaaaaaaaaaaa>\n"
7573                "    y;",
7574                Style);
7575 }
7576 
7577 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
7578   verifyFormat(
7579       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7580       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7581   verifyFormat(
7582       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7583       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7584       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
7585 
7586   // FIXME: Should we have the extra indent after the second break?
7587   verifyFormat(
7588       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7589       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7590       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7591 
7592   verifyFormat(
7593       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
7594       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
7595 
7596   // Breaking at nested name specifiers is generally not desirable.
7597   verifyFormat(
7598       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7599       "    aaaaaaaaaaaaaaaaaaaaaaa);");
7600 
7601   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
7602                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7603                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7604                "                   aaaaaaaaaaaaaaaaaaaaa);",
7605                getLLVMStyleWithColumns(74));
7606 
7607   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7608                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7609                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7610 }
7611 
7612 TEST_F(FormatTest, UnderstandsTemplateParameters) {
7613   verifyFormat("A<int> a;");
7614   verifyFormat("A<A<A<int>>> a;");
7615   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
7616   verifyFormat("bool x = a < 1 || 2 > a;");
7617   verifyFormat("bool x = 5 < f<int>();");
7618   verifyFormat("bool x = f<int>() > 5;");
7619   verifyFormat("bool x = 5 < a<int>::x;");
7620   verifyFormat("bool x = a < 4 ? a > 2 : false;");
7621   verifyFormat("bool x = f() ? a < 2 : a > 2;");
7622 
7623   verifyGoogleFormat("A<A<int>> a;");
7624   verifyGoogleFormat("A<A<A<int>>> a;");
7625   verifyGoogleFormat("A<A<A<A<int>>>> a;");
7626   verifyGoogleFormat("A<A<int> > a;");
7627   verifyGoogleFormat("A<A<A<int> > > a;");
7628   verifyGoogleFormat("A<A<A<A<int> > > > a;");
7629   verifyGoogleFormat("A<::A<int>> a;");
7630   verifyGoogleFormat("A<::A> a;");
7631   verifyGoogleFormat("A< ::A> a;");
7632   verifyGoogleFormat("A< ::A<int> > a;");
7633   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
7634   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
7635   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
7636   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
7637   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
7638             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
7639 
7640   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
7641 
7642   // template closer followed by a token that starts with > or =
7643   verifyFormat("bool b = a<1> > 1;");
7644   verifyFormat("bool b = a<1> >= 1;");
7645   verifyFormat("int i = a<1> >> 1;");
7646   FormatStyle Style = getLLVMStyle();
7647   Style.SpaceBeforeAssignmentOperators = false;
7648   verifyFormat("bool b= a<1> == 1;", Style);
7649   verifyFormat("a<int> = 1;", Style);
7650   verifyFormat("a<int> >>= 1;", Style);
7651 
7652   verifyFormat("test >> a >> b;");
7653   verifyFormat("test << a >> b;");
7654 
7655   verifyFormat("f<int>();");
7656   verifyFormat("template <typename T> void f() {}");
7657   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
7658   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
7659                "sizeof(char)>::type>;");
7660   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
7661   verifyFormat("f(a.operator()<A>());");
7662   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7663                "      .template operator()<A>());",
7664                getLLVMStyleWithColumns(35));
7665 
7666   // Not template parameters.
7667   verifyFormat("return a < b && c > d;");
7668   verifyFormat("void f() {\n"
7669                "  while (a < b && c > d) {\n"
7670                "  }\n"
7671                "}");
7672   verifyFormat("template <typename... Types>\n"
7673                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
7674 
7675   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7676                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
7677                getLLVMStyleWithColumns(60));
7678   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
7679   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
7680   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
7681   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
7682 }
7683 
7684 TEST_F(FormatTest, UnderstandsShiftOperators) {
7685   verifyFormat("if (i < x >> 1)");
7686   verifyFormat("while (i < x >> 1)");
7687   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
7688   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
7689   verifyFormat(
7690       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
7691   verifyFormat("Foo.call<Bar<Function>>()");
7692   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
7693   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
7694                "++i, v = v >> 1)");
7695   verifyFormat("if (w<u<v<x>>, 1>::t)");
7696 }
7697 
7698 TEST_F(FormatTest, BitshiftOperatorWidth) {
7699   EXPECT_EQ("int a = 1 << 2; /* foo\n"
7700             "                   bar */",
7701             format("int    a=1<<2;  /* foo\n"
7702                    "                   bar */"));
7703 
7704   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
7705             "                     bar */",
7706             format("int  b  =256>>1 ;  /* foo\n"
7707                    "                      bar */"));
7708 }
7709 
7710 TEST_F(FormatTest, UnderstandsBinaryOperators) {
7711   verifyFormat("COMPARE(a, ==, b);");
7712   verifyFormat("auto s = sizeof...(Ts) - 1;");
7713 }
7714 
7715 TEST_F(FormatTest, UnderstandsPointersToMembers) {
7716   verifyFormat("int A::*x;");
7717   verifyFormat("int (S::*func)(void *);");
7718   verifyFormat("void f() { int (S::*func)(void *); }");
7719   verifyFormat("typedef bool *(Class::*Member)() const;");
7720   verifyFormat("void f() {\n"
7721                "  (a->*f)();\n"
7722                "  a->*x;\n"
7723                "  (a.*f)();\n"
7724                "  ((*a).*f)();\n"
7725                "  a.*x;\n"
7726                "}");
7727   verifyFormat("void f() {\n"
7728                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
7729                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
7730                "}");
7731   verifyFormat(
7732       "(aaaaaaaaaa->*bbbbbbb)(\n"
7733       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7734   FormatStyle Style = getLLVMStyle();
7735   Style.PointerAlignment = FormatStyle::PAS_Left;
7736   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
7737 }
7738 
7739 TEST_F(FormatTest, UnderstandsUnaryOperators) {
7740   verifyFormat("int a = -2;");
7741   verifyFormat("f(-1, -2, -3);");
7742   verifyFormat("a[-1] = 5;");
7743   verifyFormat("int a = 5 + -2;");
7744   verifyFormat("if (i == -1) {\n}");
7745   verifyFormat("if (i != -1) {\n}");
7746   verifyFormat("if (i > -1) {\n}");
7747   verifyFormat("if (i < -1) {\n}");
7748   verifyFormat("++(a->f());");
7749   verifyFormat("--(a->f());");
7750   verifyFormat("(a->f())++;");
7751   verifyFormat("a[42]++;");
7752   verifyFormat("if (!(a->f())) {\n}");
7753   verifyFormat("if (!+i) {\n}");
7754   verifyFormat("~&a;");
7755 
7756   verifyFormat("a-- > b;");
7757   verifyFormat("b ? -a : c;");
7758   verifyFormat("n * sizeof char16;");
7759   verifyFormat("n * alignof char16;", getGoogleStyle());
7760   verifyFormat("sizeof(char);");
7761   verifyFormat("alignof(char);", getGoogleStyle());
7762 
7763   verifyFormat("return -1;");
7764   verifyFormat("throw -1;");
7765   verifyFormat("switch (a) {\n"
7766                "case -1:\n"
7767                "  break;\n"
7768                "}");
7769   verifyFormat("#define X -1");
7770   verifyFormat("#define X -kConstant");
7771 
7772   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
7773   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
7774 
7775   verifyFormat("int a = /* confusing comment */ -1;");
7776   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
7777   verifyFormat("int a = i /* confusing comment */++;");
7778 
7779   verifyFormat("co_yield -1;");
7780   verifyFormat("co_return -1;");
7781 
7782   // Check that * is not treated as a binary operator when we set
7783   // PointerAlignment as PAS_Left after a keyword and not a declaration.
7784   FormatStyle PASLeftStyle = getLLVMStyle();
7785   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
7786   verifyFormat("co_return *a;", PASLeftStyle);
7787   verifyFormat("co_await *a;", PASLeftStyle);
7788   verifyFormat("co_yield *a", PASLeftStyle);
7789   verifyFormat("return *a;", PASLeftStyle);
7790 }
7791 
7792 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
7793   verifyFormat("if (!aaaaaaaaaa( // break\n"
7794                "        aaaaa)) {\n"
7795                "}");
7796   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
7797                "    aaaaa));");
7798   verifyFormat("*aaa = aaaaaaa( // break\n"
7799                "    bbbbbb);");
7800 }
7801 
7802 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
7803   verifyFormat("bool operator<();");
7804   verifyFormat("bool operator>();");
7805   verifyFormat("bool operator=();");
7806   verifyFormat("bool operator==();");
7807   verifyFormat("bool operator!=();");
7808   verifyFormat("int operator+();");
7809   verifyFormat("int operator++();");
7810   verifyFormat("int operator++(int) volatile noexcept;");
7811   verifyFormat("bool operator,();");
7812   verifyFormat("bool operator();");
7813   verifyFormat("bool operator()();");
7814   verifyFormat("bool operator[]();");
7815   verifyFormat("operator bool();");
7816   verifyFormat("operator int();");
7817   verifyFormat("operator void *();");
7818   verifyFormat("operator SomeType<int>();");
7819   verifyFormat("operator SomeType<int, int>();");
7820   verifyFormat("operator SomeType<SomeType<int>>();");
7821   verifyFormat("void *operator new(std::size_t size);");
7822   verifyFormat("void *operator new[](std::size_t size);");
7823   verifyFormat("void operator delete(void *ptr);");
7824   verifyFormat("void operator delete[](void *ptr);");
7825   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
7826                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
7827   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
7828                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
7829 
7830   verifyFormat(
7831       "ostream &operator<<(ostream &OutputStream,\n"
7832       "                    SomeReallyLongType WithSomeReallyLongValue);");
7833   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
7834                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
7835                "  return left.group < right.group;\n"
7836                "}");
7837   verifyFormat("SomeType &operator=(const SomeType &S);");
7838   verifyFormat("f.template operator()<int>();");
7839 
7840   verifyGoogleFormat("operator void*();");
7841   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
7842   verifyGoogleFormat("operator ::A();");
7843 
7844   verifyFormat("using A::operator+;");
7845   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
7846                "int i;");
7847 }
7848 
7849 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
7850   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
7851   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
7852   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
7853   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
7854   verifyFormat("Deleted &operator=(const Deleted &) &;");
7855   verifyFormat("Deleted &operator=(const Deleted &) &&;");
7856   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
7857   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
7858   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
7859   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
7860   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
7861   verifyFormat("void Fn(T const &) const &;");
7862   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
7863   verifyFormat("template <typename T>\n"
7864                "void F(T) && = delete;",
7865                getGoogleStyle());
7866 
7867   FormatStyle AlignLeft = getLLVMStyle();
7868   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
7869   verifyFormat("void A::b() && {}", AlignLeft);
7870   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
7871   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
7872                AlignLeft);
7873   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
7874   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
7875   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
7876   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
7877   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
7878   verifyFormat("auto Function(T) & -> void;", AlignLeft);
7879   verifyFormat("void Fn(T const&) const&;", AlignLeft);
7880   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
7881 
7882   FormatStyle Spaces = getLLVMStyle();
7883   Spaces.SpacesInCStyleCastParentheses = true;
7884   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
7885   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
7886   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
7887   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
7888 
7889   Spaces.SpacesInCStyleCastParentheses = false;
7890   Spaces.SpacesInParentheses = true;
7891   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
7892   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
7893                Spaces);
7894   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
7895   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
7896 
7897   FormatStyle BreakTemplate = getLLVMStyle();
7898   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7899 
7900   verifyFormat("struct f {\n"
7901                "  template <class T>\n"
7902                "  int &foo(const std::string &str) &noexcept {}\n"
7903                "};",
7904                BreakTemplate);
7905 
7906   verifyFormat("struct f {\n"
7907                "  template <class T>\n"
7908                "  int &foo(const std::string &str) &&noexcept {}\n"
7909                "};",
7910                BreakTemplate);
7911 
7912   verifyFormat("struct f {\n"
7913                "  template <class T>\n"
7914                "  int &foo(const std::string &str) const &noexcept {}\n"
7915                "};",
7916                BreakTemplate);
7917 
7918   verifyFormat("struct f {\n"
7919                "  template <class T>\n"
7920                "  int &foo(const std::string &str) const &noexcept {}\n"
7921                "};",
7922                BreakTemplate);
7923 
7924   verifyFormat("struct f {\n"
7925                "  template <class T>\n"
7926                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
7927                "};",
7928                BreakTemplate);
7929 
7930   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
7931   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
7932       FormatStyle::BTDS_Yes;
7933   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
7934 
7935   verifyFormat("struct f {\n"
7936                "  template <class T>\n"
7937                "  int& foo(const std::string& str) & noexcept {}\n"
7938                "};",
7939                AlignLeftBreakTemplate);
7940 
7941   verifyFormat("struct f {\n"
7942                "  template <class T>\n"
7943                "  int& foo(const std::string& str) && noexcept {}\n"
7944                "};",
7945                AlignLeftBreakTemplate);
7946 
7947   verifyFormat("struct f {\n"
7948                "  template <class T>\n"
7949                "  int& foo(const std::string& str) const& noexcept {}\n"
7950                "};",
7951                AlignLeftBreakTemplate);
7952 
7953   verifyFormat("struct f {\n"
7954                "  template <class T>\n"
7955                "  int& foo(const std::string& str) const&& noexcept {}\n"
7956                "};",
7957                AlignLeftBreakTemplate);
7958 
7959   verifyFormat("struct f {\n"
7960                "  template <class T>\n"
7961                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
7962                "};",
7963                AlignLeftBreakTemplate);
7964 
7965   // The `&` in `Type&` should not be confused with a trailing `&` of
7966   // DEPRECATED(reason) member function.
7967   verifyFormat("struct f {\n"
7968                "  template <class T>\n"
7969                "  DEPRECATED(reason)\n"
7970                "  Type &foo(arguments) {}\n"
7971                "};",
7972                BreakTemplate);
7973 
7974   verifyFormat("struct f {\n"
7975                "  template <class T>\n"
7976                "  DEPRECATED(reason)\n"
7977                "  Type& foo(arguments) {}\n"
7978                "};",
7979                AlignLeftBreakTemplate);
7980 
7981   verifyFormat("void (*foopt)(int) = &func;");
7982 }
7983 
7984 TEST_F(FormatTest, UnderstandsNewAndDelete) {
7985   verifyFormat("void f() {\n"
7986                "  A *a = new A;\n"
7987                "  A *a = new (placement) A;\n"
7988                "  delete a;\n"
7989                "  delete (A *)a;\n"
7990                "}");
7991   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
7992                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
7993   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7994                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
7995                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
7996   verifyFormat("delete[] h->p;");
7997 }
7998 
7999 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
8000   verifyFormat("int *f(int *a) {}");
8001   verifyFormat("int main(int argc, char **argv) {}");
8002   verifyFormat("Test::Test(int b) : a(b * b) {}");
8003   verifyIndependentOfContext("f(a, *a);");
8004   verifyFormat("void g() { f(*a); }");
8005   verifyIndependentOfContext("int a = b * 10;");
8006   verifyIndependentOfContext("int a = 10 * b;");
8007   verifyIndependentOfContext("int a = b * c;");
8008   verifyIndependentOfContext("int a += b * c;");
8009   verifyIndependentOfContext("int a -= b * c;");
8010   verifyIndependentOfContext("int a *= b * c;");
8011   verifyIndependentOfContext("int a /= b * c;");
8012   verifyIndependentOfContext("int a = *b;");
8013   verifyIndependentOfContext("int a = *b * c;");
8014   verifyIndependentOfContext("int a = b * *c;");
8015   verifyIndependentOfContext("int a = b * (10);");
8016   verifyIndependentOfContext("S << b * (10);");
8017   verifyIndependentOfContext("return 10 * b;");
8018   verifyIndependentOfContext("return *b * *c;");
8019   verifyIndependentOfContext("return a & ~b;");
8020   verifyIndependentOfContext("f(b ? *c : *d);");
8021   verifyIndependentOfContext("int a = b ? *c : *d;");
8022   verifyIndependentOfContext("*b = a;");
8023   verifyIndependentOfContext("a * ~b;");
8024   verifyIndependentOfContext("a * !b;");
8025   verifyIndependentOfContext("a * +b;");
8026   verifyIndependentOfContext("a * -b;");
8027   verifyIndependentOfContext("a * ++b;");
8028   verifyIndependentOfContext("a * --b;");
8029   verifyIndependentOfContext("a[4] * b;");
8030   verifyIndependentOfContext("a[a * a] = 1;");
8031   verifyIndependentOfContext("f() * b;");
8032   verifyIndependentOfContext("a * [self dostuff];");
8033   verifyIndependentOfContext("int x = a * (a + b);");
8034   verifyIndependentOfContext("(a *)(a + b);");
8035   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
8036   verifyIndependentOfContext("int *pa = (int *)&a;");
8037   verifyIndependentOfContext("return sizeof(int **);");
8038   verifyIndependentOfContext("return sizeof(int ******);");
8039   verifyIndependentOfContext("return (int **&)a;");
8040   verifyIndependentOfContext("f((*PointerToArray)[10]);");
8041   verifyFormat("void f(Type (*parameter)[10]) {}");
8042   verifyFormat("void f(Type (&parameter)[10]) {}");
8043   verifyGoogleFormat("return sizeof(int**);");
8044   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
8045   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
8046   verifyFormat("auto a = [](int **&, int ***) {};");
8047   verifyFormat("auto PointerBinding = [](const char *S) {};");
8048   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
8049   verifyFormat("[](const decltype(*a) &value) {}");
8050   verifyFormat("[](const typeof(*a) &value) {}");
8051   verifyFormat("[](const _Atomic(a *) &value) {}");
8052   verifyFormat("[](const __underlying_type(a) &value) {}");
8053   verifyFormat("decltype(a * b) F();");
8054   verifyFormat("typeof(a * b) F();");
8055   verifyFormat("#define MACRO() [](A *a) { return 1; }");
8056   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
8057   verifyIndependentOfContext("typedef void (*f)(int *a);");
8058   verifyIndependentOfContext("int i{a * b};");
8059   verifyIndependentOfContext("aaa && aaa->f();");
8060   verifyIndependentOfContext("int x = ~*p;");
8061   verifyFormat("Constructor() : a(a), area(width * height) {}");
8062   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
8063   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
8064   verifyFormat("void f() { f(a, c * d); }");
8065   verifyFormat("void f() { f(new a(), c * d); }");
8066   verifyFormat("void f(const MyOverride &override);");
8067   verifyFormat("void f(const MyFinal &final);");
8068   verifyIndependentOfContext("bool a = f() && override.f();");
8069   verifyIndependentOfContext("bool a = f() && final.f();");
8070 
8071   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
8072 
8073   verifyIndependentOfContext("A<int *> a;");
8074   verifyIndependentOfContext("A<int **> a;");
8075   verifyIndependentOfContext("A<int *, int *> a;");
8076   verifyIndependentOfContext("A<int *[]> a;");
8077   verifyIndependentOfContext(
8078       "const char *const p = reinterpret_cast<const char *const>(q);");
8079   verifyIndependentOfContext("A<int **, int **> a;");
8080   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
8081   verifyFormat("for (char **a = b; *a; ++a) {\n}");
8082   verifyFormat("for (; a && b;) {\n}");
8083   verifyFormat("bool foo = true && [] { return false; }();");
8084 
8085   verifyFormat(
8086       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8087       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8088 
8089   verifyGoogleFormat("int const* a = &b;");
8090   verifyGoogleFormat("**outparam = 1;");
8091   verifyGoogleFormat("*outparam = a * b;");
8092   verifyGoogleFormat("int main(int argc, char** argv) {}");
8093   verifyGoogleFormat("A<int*> a;");
8094   verifyGoogleFormat("A<int**> a;");
8095   verifyGoogleFormat("A<int*, int*> a;");
8096   verifyGoogleFormat("A<int**, int**> a;");
8097   verifyGoogleFormat("f(b ? *c : *d);");
8098   verifyGoogleFormat("int a = b ? *c : *d;");
8099   verifyGoogleFormat("Type* t = **x;");
8100   verifyGoogleFormat("Type* t = *++*x;");
8101   verifyGoogleFormat("*++*x;");
8102   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
8103   verifyGoogleFormat("Type* t = x++ * y;");
8104   verifyGoogleFormat(
8105       "const char* const p = reinterpret_cast<const char* const>(q);");
8106   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
8107   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
8108   verifyGoogleFormat("template <typename T>\n"
8109                      "void f(int i = 0, SomeType** temps = NULL);");
8110 
8111   FormatStyle Left = getLLVMStyle();
8112   Left.PointerAlignment = FormatStyle::PAS_Left;
8113   verifyFormat("x = *a(x) = *a(y);", Left);
8114   verifyFormat("for (;; *a = b) {\n}", Left);
8115   verifyFormat("return *this += 1;", Left);
8116   verifyFormat("throw *x;", Left);
8117   verifyFormat("delete *x;", Left);
8118   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
8119   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
8120   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
8121   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
8122   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
8123   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
8124   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
8125   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
8126   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
8127 
8128   verifyIndependentOfContext("a = *(x + y);");
8129   verifyIndependentOfContext("a = &(x + y);");
8130   verifyIndependentOfContext("*(x + y).call();");
8131   verifyIndependentOfContext("&(x + y)->call();");
8132   verifyFormat("void f() { &(*I).first; }");
8133 
8134   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
8135   verifyFormat(
8136       "int *MyValues = {\n"
8137       "    *A, // Operator detection might be confused by the '{'\n"
8138       "    *BB // Operator detection might be confused by previous comment\n"
8139       "};");
8140 
8141   verifyIndependentOfContext("if (int *a = &b)");
8142   verifyIndependentOfContext("if (int &a = *b)");
8143   verifyIndependentOfContext("if (a & b[i])");
8144   verifyIndependentOfContext("if constexpr (a & b[i])");
8145   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
8146   verifyIndependentOfContext("if (a * (b * c))");
8147   verifyIndependentOfContext("if constexpr (a * (b * c))");
8148   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
8149   verifyIndependentOfContext("if (a::b::c::d & b[i])");
8150   verifyIndependentOfContext("if (*b[i])");
8151   verifyIndependentOfContext("if (int *a = (&b))");
8152   verifyIndependentOfContext("while (int *a = &b)");
8153   verifyIndependentOfContext("while (a * (b * c))");
8154   verifyIndependentOfContext("size = sizeof *a;");
8155   verifyIndependentOfContext("if (a && (b = c))");
8156   verifyFormat("void f() {\n"
8157                "  for (const int &v : Values) {\n"
8158                "  }\n"
8159                "}");
8160   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
8161   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
8162   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
8163 
8164   verifyFormat("#define A (!a * b)");
8165   verifyFormat("#define MACRO     \\\n"
8166                "  int *i = a * b; \\\n"
8167                "  void f(a *b);",
8168                getLLVMStyleWithColumns(19));
8169 
8170   verifyIndependentOfContext("A = new SomeType *[Length];");
8171   verifyIndependentOfContext("A = new SomeType *[Length]();");
8172   verifyIndependentOfContext("T **t = new T *;");
8173   verifyIndependentOfContext("T **t = new T *();");
8174   verifyGoogleFormat("A = new SomeType*[Length]();");
8175   verifyGoogleFormat("A = new SomeType*[Length];");
8176   verifyGoogleFormat("T** t = new T*;");
8177   verifyGoogleFormat("T** t = new T*();");
8178 
8179   verifyFormat("STATIC_ASSERT((a & b) == 0);");
8180   verifyFormat("STATIC_ASSERT(0 == (a & b));");
8181   verifyFormat("template <bool a, bool b> "
8182                "typename t::if<x && y>::type f() {}");
8183   verifyFormat("template <int *y> f() {}");
8184   verifyFormat("vector<int *> v;");
8185   verifyFormat("vector<int *const> v;");
8186   verifyFormat("vector<int *const **const *> v;");
8187   verifyFormat("vector<int *volatile> v;");
8188   verifyFormat("vector<a *_Nonnull> v;");
8189   verifyFormat("vector<a *_Nullable> v;");
8190   verifyFormat("vector<a *_Null_unspecified> v;");
8191   verifyFormat("vector<a *__ptr32> v;");
8192   verifyFormat("vector<a *__ptr64> v;");
8193   verifyFormat("vector<a *__capability> v;");
8194   FormatStyle TypeMacros = getLLVMStyle();
8195   TypeMacros.TypenameMacros = {"LIST"};
8196   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
8197   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
8198   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
8199   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
8200   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
8201 
8202   FormatStyle CustomQualifier = getLLVMStyle();
8203   // Add indentifers that should not be parsed as a qualifier by default.
8204   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
8205   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
8206   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
8207   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
8208   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
8209   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
8210   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
8211   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
8212   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
8213   verifyFormat("vector<a * _NotAQualifier> v;");
8214   verifyFormat("vector<a * __not_a_qualifier> v;");
8215   verifyFormat("vector<a * b> v;");
8216   verifyFormat("foo<b && false>();");
8217   verifyFormat("foo<b & 1>();");
8218   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
8219   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
8220   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
8221   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
8222   verifyFormat(
8223       "template <class T, class = typename std::enable_if<\n"
8224       "                       std::is_integral<T>::value &&\n"
8225       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
8226       "void F();",
8227       getLLVMStyleWithColumns(70));
8228   verifyFormat("template <class T,\n"
8229                "          class = typename std::enable_if<\n"
8230                "              std::is_integral<T>::value &&\n"
8231                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
8232                "          class U>\n"
8233                "void F();",
8234                getLLVMStyleWithColumns(70));
8235   verifyFormat(
8236       "template <class T,\n"
8237       "          class = typename ::std::enable_if<\n"
8238       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
8239       "void F();",
8240       getGoogleStyleWithColumns(68));
8241 
8242   verifyIndependentOfContext("MACRO(int *i);");
8243   verifyIndependentOfContext("MACRO(auto *a);");
8244   verifyIndependentOfContext("MACRO(const A *a);");
8245   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
8246   verifyIndependentOfContext("MACRO(decltype(A) *a);");
8247   verifyIndependentOfContext("MACRO(typeof(A) *a);");
8248   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
8249   verifyIndependentOfContext("MACRO(A *const a);");
8250   verifyIndependentOfContext("MACRO(A *restrict a);");
8251   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
8252   verifyIndependentOfContext("MACRO(A *__restrict a);");
8253   verifyIndependentOfContext("MACRO(A *volatile a);");
8254   verifyIndependentOfContext("MACRO(A *__volatile a);");
8255   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
8256   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
8257   verifyIndependentOfContext("MACRO(A *_Nullable a);");
8258   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
8259   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
8260   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
8261   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
8262   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
8263   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
8264   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
8265   verifyIndependentOfContext("MACRO(A *__capability);");
8266   verifyIndependentOfContext("MACRO(A &__capability);");
8267   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
8268   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
8269   // If we add __my_qualifier to AttributeMacros it should always be parsed as
8270   // a type declaration:
8271   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
8272   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
8273   // Also check that TypenameMacros prevents parsing it as multiplication:
8274   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
8275   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
8276 
8277   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
8278   verifyFormat("void f() { f(float{1}, a * a); }");
8279   // FIXME: Is there a way to make this work?
8280   // verifyIndependentOfContext("MACRO(A *a);");
8281   verifyFormat("MACRO(A &B);");
8282   verifyFormat("MACRO(A *B);");
8283   verifyFormat("void f() { MACRO(A * B); }");
8284   verifyFormat("void f() { MACRO(A & B); }");
8285 
8286   // This lambda was mis-formatted after D88956 (treating it as a binop):
8287   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
8288   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
8289   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
8290   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
8291 
8292   verifyFormat("DatumHandle const *operator->() const { return input_; }");
8293   verifyFormat("return options != nullptr && operator==(*options);");
8294 
8295   EXPECT_EQ("#define OP(x)                                    \\\n"
8296             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
8297             "    return s << a.DebugString();                 \\\n"
8298             "  }",
8299             format("#define OP(x) \\\n"
8300                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
8301                    "    return s << a.DebugString(); \\\n"
8302                    "  }",
8303                    getLLVMStyleWithColumns(50)));
8304 
8305   // FIXME: We cannot handle this case yet; we might be able to figure out that
8306   // foo<x> d > v; doesn't make sense.
8307   verifyFormat("foo<a<b && c> d> v;");
8308 
8309   FormatStyle PointerMiddle = getLLVMStyle();
8310   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
8311   verifyFormat("delete *x;", PointerMiddle);
8312   verifyFormat("int * x;", PointerMiddle);
8313   verifyFormat("int *[] x;", PointerMiddle);
8314   verifyFormat("template <int * y> f() {}", PointerMiddle);
8315   verifyFormat("int * f(int * a) {}", PointerMiddle);
8316   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
8317   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
8318   verifyFormat("A<int *> a;", PointerMiddle);
8319   verifyFormat("A<int **> a;", PointerMiddle);
8320   verifyFormat("A<int *, int *> a;", PointerMiddle);
8321   verifyFormat("A<int *[]> a;", PointerMiddle);
8322   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
8323   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
8324   verifyFormat("T ** t = new T *;", PointerMiddle);
8325 
8326   // Member function reference qualifiers aren't binary operators.
8327   verifyFormat("string // break\n"
8328                "operator()() & {}");
8329   verifyFormat("string // break\n"
8330                "operator()() && {}");
8331   verifyGoogleFormat("template <typename T>\n"
8332                      "auto x() & -> int {}");
8333 }
8334 
8335 TEST_F(FormatTest, UnderstandsAttributes) {
8336   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
8337   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
8338                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
8339   FormatStyle AfterType = getLLVMStyle();
8340   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8341   verifyFormat("__attribute__((nodebug)) void\n"
8342                "foo() {}\n",
8343                AfterType);
8344   verifyFormat("__unused void\n"
8345                "foo() {}",
8346                AfterType);
8347 
8348   FormatStyle CustomAttrs = getLLVMStyle();
8349   CustomAttrs.AttributeMacros.push_back("__unused");
8350   CustomAttrs.AttributeMacros.push_back("__attr1");
8351   CustomAttrs.AttributeMacros.push_back("__attr2");
8352   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
8353   verifyFormat("vector<SomeType *__attribute((foo))> v;");
8354   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
8355   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
8356   // Check that it is parsed as a multiplication without AttributeMacros and
8357   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
8358   verifyFormat("vector<SomeType * __attr1> v;");
8359   verifyFormat("vector<SomeType __attr1 *> v;");
8360   verifyFormat("vector<SomeType __attr1 *const> v;");
8361   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
8362   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
8363   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
8364   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
8365   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
8366   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
8367   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
8368   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
8369 
8370   // Check that these are not parsed as function declarations:
8371   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8372   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
8373   verifyFormat("SomeType s(InitValue);", CustomAttrs);
8374   verifyFormat("SomeType s{InitValue};", CustomAttrs);
8375   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
8376   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
8377   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
8378   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
8379   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
8380   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
8381 }
8382 
8383 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
8384   // Check that qualifiers on pointers don't break parsing of casts.
8385   verifyFormat("x = (foo *const)*v;");
8386   verifyFormat("x = (foo *volatile)*v;");
8387   verifyFormat("x = (foo *restrict)*v;");
8388   verifyFormat("x = (foo *__attribute__((foo)))*v;");
8389   verifyFormat("x = (foo *_Nonnull)*v;");
8390   verifyFormat("x = (foo *_Nullable)*v;");
8391   verifyFormat("x = (foo *_Null_unspecified)*v;");
8392   verifyFormat("x = (foo *_Nonnull)*v;");
8393   verifyFormat("x = (foo *[[clang::attr]])*v;");
8394   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
8395   verifyFormat("x = (foo *__ptr32)*v;");
8396   verifyFormat("x = (foo *__ptr64)*v;");
8397   verifyFormat("x = (foo *__capability)*v;");
8398 
8399   // Check that we handle multiple trailing qualifiers and skip them all to
8400   // determine that the expression is a cast to a pointer type.
8401   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
8402   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
8403   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
8404   StringRef AllQualifiers =
8405       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
8406       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
8407   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
8408   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
8409 
8410   // Also check that address-of is not parsed as a binary bitwise-and:
8411   verifyFormat("x = (foo *const)&v;");
8412   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
8413   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
8414 
8415   // Check custom qualifiers:
8416   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
8417   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
8418   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
8419   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
8420   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
8421                CustomQualifier);
8422   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
8423                CustomQualifier);
8424 
8425   // Check that unknown identifiers result in binary operator parsing:
8426   verifyFormat("x = (foo * __unknown_qualifier) * v;");
8427   verifyFormat("x = (foo * __unknown_qualifier) & v;");
8428 }
8429 
8430 TEST_F(FormatTest, UnderstandsSquareAttributes) {
8431   verifyFormat("SomeType s [[unused]] (InitValue);");
8432   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
8433   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
8434   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
8435   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
8436   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8437                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
8438   verifyFormat("[[nodiscard]] bool f() { return false; }");
8439   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
8440   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
8441   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
8442 
8443   // Make sure we do not mistake attributes for array subscripts.
8444   verifyFormat("int a() {}\n"
8445                "[[unused]] int b() {}\n");
8446   verifyFormat("NSArray *arr;\n"
8447                "arr[[Foo() bar]];");
8448 
8449   // On the other hand, we still need to correctly find array subscripts.
8450   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
8451 
8452   // Make sure that we do not mistake Objective-C method inside array literals
8453   // as attributes, even if those method names are also keywords.
8454   verifyFormat("@[ [foo bar] ];");
8455   verifyFormat("@[ [NSArray class] ];");
8456   verifyFormat("@[ [foo enum] ];");
8457 
8458   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
8459 
8460   // Make sure we do not parse attributes as lambda introducers.
8461   FormatStyle MultiLineFunctions = getLLVMStyle();
8462   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8463   verifyFormat("[[unused]] int b() {\n"
8464                "  return 42;\n"
8465                "}\n",
8466                MultiLineFunctions);
8467 }
8468 
8469 TEST_F(FormatTest, AttributeClass) {
8470   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
8471   verifyFormat("class S {\n"
8472                "  S(S&&) = default;\n"
8473                "};",
8474                Style);
8475   verifyFormat("class [[nodiscard]] S {\n"
8476                "  S(S&&) = default;\n"
8477                "};",
8478                Style);
8479   verifyFormat("class __attribute((maybeunused)) S {\n"
8480                "  S(S&&) = default;\n"
8481                "};",
8482                Style);
8483   verifyFormat("struct S {\n"
8484                "  S(S&&) = default;\n"
8485                "};",
8486                Style);
8487   verifyFormat("struct [[nodiscard]] S {\n"
8488                "  S(S&&) = default;\n"
8489                "};",
8490                Style);
8491 }
8492 
8493 TEST_F(FormatTest, AttributesAfterMacro) {
8494   FormatStyle Style = getLLVMStyle();
8495   verifyFormat("MACRO;\n"
8496                "__attribute__((maybe_unused)) int foo() {\n"
8497                "  //...\n"
8498                "}");
8499 
8500   verifyFormat("MACRO;\n"
8501                "[[nodiscard]] int foo() {\n"
8502                "  //...\n"
8503                "}");
8504 
8505   EXPECT_EQ("MACRO\n\n"
8506             "__attribute__((maybe_unused)) int foo() {\n"
8507             "  //...\n"
8508             "}",
8509             format("MACRO\n\n"
8510                    "__attribute__((maybe_unused)) int foo() {\n"
8511                    "  //...\n"
8512                    "}"));
8513 
8514   EXPECT_EQ("MACRO\n\n"
8515             "[[nodiscard]] int foo() {\n"
8516             "  //...\n"
8517             "}",
8518             format("MACRO\n\n"
8519                    "[[nodiscard]] int foo() {\n"
8520                    "  //...\n"
8521                    "}"));
8522 }
8523 
8524 TEST_F(FormatTest, AttributePenaltyBreaking) {
8525   FormatStyle Style = getLLVMStyle();
8526   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
8527                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
8528                Style);
8529   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
8530                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
8531                Style);
8532   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
8533                "shared_ptr<ALongTypeName> &C d) {\n}",
8534                Style);
8535 }
8536 
8537 TEST_F(FormatTest, UnderstandsEllipsis) {
8538   FormatStyle Style = getLLVMStyle();
8539   verifyFormat("int printf(const char *fmt, ...);");
8540   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
8541   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
8542 
8543   verifyFormat("template <int *...PP> a;", Style);
8544 
8545   Style.PointerAlignment = FormatStyle::PAS_Left;
8546   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
8547 
8548   verifyFormat("template <int*... PP> a;", Style);
8549 
8550   Style.PointerAlignment = FormatStyle::PAS_Middle;
8551   verifyFormat("template <int *... PP> a;", Style);
8552 }
8553 
8554 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
8555   EXPECT_EQ("int *a;\n"
8556             "int *a;\n"
8557             "int *a;",
8558             format("int *a;\n"
8559                    "int* a;\n"
8560                    "int *a;",
8561                    getGoogleStyle()));
8562   EXPECT_EQ("int* a;\n"
8563             "int* a;\n"
8564             "int* a;",
8565             format("int* a;\n"
8566                    "int* a;\n"
8567                    "int *a;",
8568                    getGoogleStyle()));
8569   EXPECT_EQ("int *a;\n"
8570             "int *a;\n"
8571             "int *a;",
8572             format("int *a;\n"
8573                    "int * a;\n"
8574                    "int *  a;",
8575                    getGoogleStyle()));
8576   EXPECT_EQ("auto x = [] {\n"
8577             "  int *a;\n"
8578             "  int *a;\n"
8579             "  int *a;\n"
8580             "};",
8581             format("auto x=[]{int *a;\n"
8582                    "int * a;\n"
8583                    "int *  a;};",
8584                    getGoogleStyle()));
8585 }
8586 
8587 TEST_F(FormatTest, UnderstandsRvalueReferences) {
8588   verifyFormat("int f(int &&a) {}");
8589   verifyFormat("int f(int a, char &&b) {}");
8590   verifyFormat("void f() { int &&a = b; }");
8591   verifyGoogleFormat("int f(int a, char&& b) {}");
8592   verifyGoogleFormat("void f() { int&& a = b; }");
8593 
8594   verifyIndependentOfContext("A<int &&> a;");
8595   verifyIndependentOfContext("A<int &&, int &&> a;");
8596   verifyGoogleFormat("A<int&&> a;");
8597   verifyGoogleFormat("A<int&&, int&&> a;");
8598 
8599   // Not rvalue references:
8600   verifyFormat("template <bool B, bool C> class A {\n"
8601                "  static_assert(B && C, \"Something is wrong\");\n"
8602                "};");
8603   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
8604   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
8605   verifyFormat("#define A(a, b) (a && b)");
8606 }
8607 
8608 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
8609   verifyFormat("void f() {\n"
8610                "  x[aaaaaaaaa -\n"
8611                "    b] = 23;\n"
8612                "}",
8613                getLLVMStyleWithColumns(15));
8614 }
8615 
8616 TEST_F(FormatTest, FormatsCasts) {
8617   verifyFormat("Type *A = static_cast<Type *>(P);");
8618   verifyFormat("Type *A = (Type *)P;");
8619   verifyFormat("Type *A = (vector<Type *, int *>)P;");
8620   verifyFormat("int a = (int)(2.0f);");
8621   verifyFormat("int a = (int)2.0f;");
8622   verifyFormat("x[(int32)y];");
8623   verifyFormat("x = (int32)y;");
8624   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
8625   verifyFormat("int a = (int)*b;");
8626   verifyFormat("int a = (int)2.0f;");
8627   verifyFormat("int a = (int)~0;");
8628   verifyFormat("int a = (int)++a;");
8629   verifyFormat("int a = (int)sizeof(int);");
8630   verifyFormat("int a = (int)+2;");
8631   verifyFormat("my_int a = (my_int)2.0f;");
8632   verifyFormat("my_int a = (my_int)sizeof(int);");
8633   verifyFormat("return (my_int)aaa;");
8634   verifyFormat("#define x ((int)-1)");
8635   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
8636   verifyFormat("#define p(q) ((int *)&q)");
8637   verifyFormat("fn(a)(b) + 1;");
8638 
8639   verifyFormat("void f() { my_int a = (my_int)*b; }");
8640   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
8641   verifyFormat("my_int a = (my_int)~0;");
8642   verifyFormat("my_int a = (my_int)++a;");
8643   verifyFormat("my_int a = (my_int)-2;");
8644   verifyFormat("my_int a = (my_int)1;");
8645   verifyFormat("my_int a = (my_int *)1;");
8646   verifyFormat("my_int a = (const my_int)-1;");
8647   verifyFormat("my_int a = (const my_int *)-1;");
8648   verifyFormat("my_int a = (my_int)(my_int)-1;");
8649   verifyFormat("my_int a = (ns::my_int)-2;");
8650   verifyFormat("case (my_int)ONE:");
8651   verifyFormat("auto x = (X)this;");
8652   // Casts in Obj-C style calls used to not be recognized as such.
8653   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
8654 
8655   // FIXME: single value wrapped with paren will be treated as cast.
8656   verifyFormat("void f(int i = (kValue)*kMask) {}");
8657 
8658   verifyFormat("{ (void)F; }");
8659 
8660   // Don't break after a cast's
8661   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8662                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
8663                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
8664 
8665   // These are not casts.
8666   verifyFormat("void f(int *) {}");
8667   verifyFormat("f(foo)->b;");
8668   verifyFormat("f(foo).b;");
8669   verifyFormat("f(foo)(b);");
8670   verifyFormat("f(foo)[b];");
8671   verifyFormat("[](foo) { return 4; }(bar);");
8672   verifyFormat("(*funptr)(foo)[4];");
8673   verifyFormat("funptrs[4](foo)[4];");
8674   verifyFormat("void f(int *);");
8675   verifyFormat("void f(int *) = 0;");
8676   verifyFormat("void f(SmallVector<int>) {}");
8677   verifyFormat("void f(SmallVector<int>);");
8678   verifyFormat("void f(SmallVector<int>) = 0;");
8679   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
8680   verifyFormat("int a = sizeof(int) * b;");
8681   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
8682   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
8683   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
8684   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
8685 
8686   // These are not casts, but at some point were confused with casts.
8687   verifyFormat("virtual void foo(int *) override;");
8688   verifyFormat("virtual void foo(char &) const;");
8689   verifyFormat("virtual void foo(int *a, char *) const;");
8690   verifyFormat("int a = sizeof(int *) + b;");
8691   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
8692   verifyFormat("bool b = f(g<int>) && c;");
8693   verifyFormat("typedef void (*f)(int i) func;");
8694   verifyFormat("void operator++(int) noexcept;");
8695   verifyFormat("void operator++(int &) noexcept;");
8696   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
8697                "&) noexcept;");
8698   verifyFormat(
8699       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
8700   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
8701   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
8702   verifyFormat("void operator delete(nothrow_t &) noexcept;");
8703   verifyFormat("void operator delete(foo &) noexcept;");
8704   verifyFormat("void operator delete(foo) noexcept;");
8705   verifyFormat("void operator delete(int) noexcept;");
8706   verifyFormat("void operator delete(int &) noexcept;");
8707   verifyFormat("void operator delete(int &) volatile noexcept;");
8708   verifyFormat("void operator delete(int &) const");
8709   verifyFormat("void operator delete(int &) = default");
8710   verifyFormat("void operator delete(int &) = delete");
8711   verifyFormat("void operator delete(int &) [[noreturn]]");
8712   verifyFormat("void operator delete(int &) throw();");
8713   verifyFormat("void operator delete(int &) throw(int);");
8714   verifyFormat("auto operator delete(int &) -> int;");
8715   verifyFormat("auto operator delete(int &) override");
8716   verifyFormat("auto operator delete(int &) final");
8717 
8718   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
8719                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8720   // FIXME: The indentation here is not ideal.
8721   verifyFormat(
8722       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8723       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
8724       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
8725 }
8726 
8727 TEST_F(FormatTest, FormatsFunctionTypes) {
8728   verifyFormat("A<bool()> a;");
8729   verifyFormat("A<SomeType()> a;");
8730   verifyFormat("A<void (*)(int, std::string)> a;");
8731   verifyFormat("A<void *(int)>;");
8732   verifyFormat("void *(*a)(int *, SomeType *);");
8733   verifyFormat("int (*func)(void *);");
8734   verifyFormat("void f() { int (*func)(void *); }");
8735   verifyFormat("template <class CallbackClass>\n"
8736                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
8737 
8738   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
8739   verifyGoogleFormat("void* (*a)(int);");
8740   verifyGoogleFormat(
8741       "template <class CallbackClass>\n"
8742       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
8743 
8744   // Other constructs can look somewhat like function types:
8745   verifyFormat("A<sizeof(*x)> a;");
8746   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
8747   verifyFormat("some_var = function(*some_pointer_var)[0];");
8748   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
8749   verifyFormat("int x = f(&h)();");
8750   verifyFormat("returnsFunction(&param1, &param2)(param);");
8751   verifyFormat("std::function<\n"
8752                "    LooooooooooongTemplatedType<\n"
8753                "        SomeType>*(\n"
8754                "        LooooooooooooooooongType type)>\n"
8755                "    function;",
8756                getGoogleStyleWithColumns(40));
8757 }
8758 
8759 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
8760   verifyFormat("A (*foo_)[6];");
8761   verifyFormat("vector<int> (*foo_)[6];");
8762 }
8763 
8764 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
8765   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8766                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
8767   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
8768                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
8769   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8770                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
8771 
8772   // Different ways of ()-initializiation.
8773   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8774                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
8775   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8776                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
8777   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8778                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
8779   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8780                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
8781 
8782   // Lambdas should not confuse the variable declaration heuristic.
8783   verifyFormat("LooooooooooooooooongType\n"
8784                "    variable(nullptr, [](A *a) {});",
8785                getLLVMStyleWithColumns(40));
8786 }
8787 
8788 TEST_F(FormatTest, BreaksLongDeclarations) {
8789   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
8790                "    AnotherNameForTheLongType;");
8791   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
8792                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8793   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8794                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
8795   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
8796                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
8797   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8798                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8799   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
8800                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8801   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
8802                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8803   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
8804                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8805   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
8806                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8807   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
8808                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8809   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
8810                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8811   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8812                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
8813   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8814                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
8815   FormatStyle Indented = getLLVMStyle();
8816   Indented.IndentWrappedFunctionNames = true;
8817   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8818                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
8819                Indented);
8820   verifyFormat(
8821       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8822       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8823       Indented);
8824   verifyFormat(
8825       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
8826       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8827       Indented);
8828   verifyFormat(
8829       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
8830       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8831       Indented);
8832 
8833   // FIXME: Without the comment, this breaks after "(".
8834   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
8835                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
8836                getGoogleStyle());
8837 
8838   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
8839                "                  int LoooooooooooooooooooongParam2) {}");
8840   verifyFormat(
8841       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
8842       "                                   SourceLocation L, IdentifierIn *II,\n"
8843       "                                   Type *T) {}");
8844   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
8845                "ReallyReaaallyLongFunctionName(\n"
8846                "    const std::string &SomeParameter,\n"
8847                "    const SomeType<string, SomeOtherTemplateParameter>\n"
8848                "        &ReallyReallyLongParameterName,\n"
8849                "    const SomeType<string, SomeOtherTemplateParameter>\n"
8850                "        &AnotherLongParameterName) {}");
8851   verifyFormat("template <typename A>\n"
8852                "SomeLoooooooooooooooooooooongType<\n"
8853                "    typename some_namespace::SomeOtherType<A>::Type>\n"
8854                "Function() {}");
8855 
8856   verifyGoogleFormat(
8857       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
8858       "    aaaaaaaaaaaaaaaaaaaaaaa;");
8859   verifyGoogleFormat(
8860       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
8861       "                                   SourceLocation L) {}");
8862   verifyGoogleFormat(
8863       "some_namespace::LongReturnType\n"
8864       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
8865       "    int first_long_parameter, int second_parameter) {}");
8866 
8867   verifyGoogleFormat("template <typename T>\n"
8868                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
8869                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
8870   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8871                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
8872 
8873   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
8874                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8875                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8876   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8877                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
8878                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
8879   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8880                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
8881                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
8882                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8883 
8884   verifyFormat("template <typename T> // Templates on own line.\n"
8885                "static int            // Some comment.\n"
8886                "MyFunction(int a);",
8887                getLLVMStyle());
8888 }
8889 
8890 TEST_F(FormatTest, FormatsAccessModifiers) {
8891   FormatStyle Style = getLLVMStyle();
8892   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
8893             FormatStyle::ELBAMS_LogicalBlock);
8894   verifyFormat("struct foo {\n"
8895                "private:\n"
8896                "  void f() {}\n"
8897                "\n"
8898                "private:\n"
8899                "  int i;\n"
8900                "\n"
8901                "protected:\n"
8902                "  int j;\n"
8903                "};\n",
8904                Style);
8905   verifyFormat("struct foo {\n"
8906                "private:\n"
8907                "  void f() {}\n"
8908                "\n"
8909                "private:\n"
8910                "  int i;\n"
8911                "\n"
8912                "protected:\n"
8913                "  int j;\n"
8914                "};\n",
8915                "struct foo {\n"
8916                "private:\n"
8917                "  void f() {}\n"
8918                "private:\n"
8919                "  int i;\n"
8920                "protected:\n"
8921                "  int j;\n"
8922                "};\n",
8923                Style);
8924   verifyFormat("struct foo { /* comment */\n"
8925                "private:\n"
8926                "  int i;\n"
8927                "  // comment\n"
8928                "private:\n"
8929                "  int j;\n"
8930                "};\n",
8931                Style);
8932   verifyFormat("struct foo {\n"
8933                "#ifdef FOO\n"
8934                "#endif\n"
8935                "private:\n"
8936                "  int i;\n"
8937                "#ifdef FOO\n"
8938                "private:\n"
8939                "#endif\n"
8940                "  int j;\n"
8941                "};\n",
8942                Style);
8943   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
8944   verifyFormat("struct foo {\n"
8945                "private:\n"
8946                "  void f() {}\n"
8947                "private:\n"
8948                "  int i;\n"
8949                "protected:\n"
8950                "  int j;\n"
8951                "};\n",
8952                Style);
8953   verifyFormat("struct foo {\n"
8954                "private:\n"
8955                "  void f() {}\n"
8956                "private:\n"
8957                "  int i;\n"
8958                "protected:\n"
8959                "  int j;\n"
8960                "};\n",
8961                "struct foo {\n"
8962                "\n"
8963                "private:\n"
8964                "  void f() {}\n"
8965                "\n"
8966                "private:\n"
8967                "  int i;\n"
8968                "\n"
8969                "protected:\n"
8970                "  int j;\n"
8971                "};\n",
8972                Style);
8973   verifyFormat("struct foo { /* comment */\n"
8974                "private:\n"
8975                "  int i;\n"
8976                "  // comment\n"
8977                "private:\n"
8978                "  int j;\n"
8979                "};\n",
8980                "struct foo { /* comment */\n"
8981                "\n"
8982                "private:\n"
8983                "  int i;\n"
8984                "  // comment\n"
8985                "\n"
8986                "private:\n"
8987                "  int j;\n"
8988                "};\n",
8989                Style);
8990   verifyFormat("struct foo {\n"
8991                "#ifdef FOO\n"
8992                "#endif\n"
8993                "private:\n"
8994                "  int i;\n"
8995                "#ifdef FOO\n"
8996                "private:\n"
8997                "#endif\n"
8998                "  int j;\n"
8999                "};\n",
9000                "struct foo {\n"
9001                "#ifdef FOO\n"
9002                "#endif\n"
9003                "\n"
9004                "private:\n"
9005                "  int i;\n"
9006                "#ifdef FOO\n"
9007                "\n"
9008                "private:\n"
9009                "#endif\n"
9010                "  int j;\n"
9011                "};\n",
9012                Style);
9013   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9014   verifyFormat("struct foo {\n"
9015                "private:\n"
9016                "  void f() {}\n"
9017                "\n"
9018                "private:\n"
9019                "  int i;\n"
9020                "\n"
9021                "protected:\n"
9022                "  int j;\n"
9023                "};\n",
9024                Style);
9025   verifyFormat("struct foo {\n"
9026                "private:\n"
9027                "  void f() {}\n"
9028                "\n"
9029                "private:\n"
9030                "  int i;\n"
9031                "\n"
9032                "protected:\n"
9033                "  int j;\n"
9034                "};\n",
9035                "struct foo {\n"
9036                "private:\n"
9037                "  void f() {}\n"
9038                "private:\n"
9039                "  int i;\n"
9040                "protected:\n"
9041                "  int j;\n"
9042                "};\n",
9043                Style);
9044   verifyFormat("struct foo { /* comment */\n"
9045                "private:\n"
9046                "  int i;\n"
9047                "  // comment\n"
9048                "\n"
9049                "private:\n"
9050                "  int j;\n"
9051                "};\n",
9052                "struct foo { /* comment */\n"
9053                "private:\n"
9054                "  int i;\n"
9055                "  // comment\n"
9056                "\n"
9057                "private:\n"
9058                "  int j;\n"
9059                "};\n",
9060                Style);
9061   verifyFormat("struct foo {\n"
9062                "#ifdef FOO\n"
9063                "#endif\n"
9064                "\n"
9065                "private:\n"
9066                "  int i;\n"
9067                "#ifdef FOO\n"
9068                "\n"
9069                "private:\n"
9070                "#endif\n"
9071                "  int j;\n"
9072                "};\n",
9073                "struct foo {\n"
9074                "#ifdef FOO\n"
9075                "#endif\n"
9076                "private:\n"
9077                "  int i;\n"
9078                "#ifdef FOO\n"
9079                "private:\n"
9080                "#endif\n"
9081                "  int j;\n"
9082                "};\n",
9083                Style);
9084   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9085   EXPECT_EQ("struct foo {\n"
9086             "\n"
9087             "private:\n"
9088             "  void f() {}\n"
9089             "\n"
9090             "private:\n"
9091             "  int i;\n"
9092             "\n"
9093             "protected:\n"
9094             "  int j;\n"
9095             "};\n",
9096             format("struct foo {\n"
9097                    "\n"
9098                    "private:\n"
9099                    "  void f() {}\n"
9100                    "\n"
9101                    "private:\n"
9102                    "  int i;\n"
9103                    "\n"
9104                    "protected:\n"
9105                    "  int j;\n"
9106                    "};\n",
9107                    Style));
9108   verifyFormat("struct foo {\n"
9109                "private:\n"
9110                "  void f() {}\n"
9111                "private:\n"
9112                "  int i;\n"
9113                "protected:\n"
9114                "  int j;\n"
9115                "};\n",
9116                Style);
9117   EXPECT_EQ("struct foo { /* comment */\n"
9118             "\n"
9119             "private:\n"
9120             "  int i;\n"
9121             "  // comment\n"
9122             "\n"
9123             "private:\n"
9124             "  int j;\n"
9125             "};\n",
9126             format("struct foo { /* comment */\n"
9127                    "\n"
9128                    "private:\n"
9129                    "  int i;\n"
9130                    "  // comment\n"
9131                    "\n"
9132                    "private:\n"
9133                    "  int j;\n"
9134                    "};\n",
9135                    Style));
9136   verifyFormat("struct foo { /* comment */\n"
9137                "private:\n"
9138                "  int i;\n"
9139                "  // comment\n"
9140                "private:\n"
9141                "  int j;\n"
9142                "};\n",
9143                Style);
9144   EXPECT_EQ("struct foo {\n"
9145             "#ifdef FOO\n"
9146             "#endif\n"
9147             "\n"
9148             "private:\n"
9149             "  int i;\n"
9150             "#ifdef FOO\n"
9151             "\n"
9152             "private:\n"
9153             "#endif\n"
9154             "  int j;\n"
9155             "};\n",
9156             format("struct foo {\n"
9157                    "#ifdef FOO\n"
9158                    "#endif\n"
9159                    "\n"
9160                    "private:\n"
9161                    "  int i;\n"
9162                    "#ifdef FOO\n"
9163                    "\n"
9164                    "private:\n"
9165                    "#endif\n"
9166                    "  int j;\n"
9167                    "};\n",
9168                    Style));
9169   verifyFormat("struct foo {\n"
9170                "#ifdef FOO\n"
9171                "#endif\n"
9172                "private:\n"
9173                "  int i;\n"
9174                "#ifdef FOO\n"
9175                "private:\n"
9176                "#endif\n"
9177                "  int j;\n"
9178                "};\n",
9179                Style);
9180 }
9181 
9182 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
9183 
9184   FormatStyle Style = getLLVMStyle();
9185   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
9186   verifyFormat("struct foo {\n"
9187                "private:\n"
9188                "  void f() {}\n"
9189                "\n"
9190                "private:\n"
9191                "  int i;\n"
9192                "\n"
9193                "protected:\n"
9194                "  int j;\n"
9195                "};\n",
9196                Style);
9197 
9198   // Check if lines are removed.
9199   verifyFormat("struct foo {\n"
9200                "private:\n"
9201                "  void f() {}\n"
9202                "\n"
9203                "private:\n"
9204                "  int i;\n"
9205                "\n"
9206                "protected:\n"
9207                "  int j;\n"
9208                "};\n",
9209                "struct foo {\n"
9210                "private:\n"
9211                "\n"
9212                "  void f() {}\n"
9213                "\n"
9214                "private:\n"
9215                "\n"
9216                "  int i;\n"
9217                "\n"
9218                "protected:\n"
9219                "\n"
9220                "  int j;\n"
9221                "};\n",
9222                Style);
9223 
9224   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9225   verifyFormat("struct foo {\n"
9226                "private:\n"
9227                "\n"
9228                "  void f() {}\n"
9229                "\n"
9230                "private:\n"
9231                "\n"
9232                "  int i;\n"
9233                "\n"
9234                "protected:\n"
9235                "\n"
9236                "  int j;\n"
9237                "};\n",
9238                Style);
9239 
9240   // Check if lines are added.
9241   verifyFormat("struct foo {\n"
9242                "private:\n"
9243                "\n"
9244                "  void f() {}\n"
9245                "\n"
9246                "private:\n"
9247                "\n"
9248                "  int i;\n"
9249                "\n"
9250                "protected:\n"
9251                "\n"
9252                "  int j;\n"
9253                "};\n",
9254                "struct foo {\n"
9255                "private:\n"
9256                "  void f() {}\n"
9257                "\n"
9258                "private:\n"
9259                "  int i;\n"
9260                "\n"
9261                "protected:\n"
9262                "  int j;\n"
9263                "};\n",
9264                Style);
9265 
9266   // Leave tests rely on the code layout, test::messUp can not be used.
9267   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9268   Style.MaxEmptyLinesToKeep = 0u;
9269   EXPECT_EQ("struct foo {\n"
9270             "private:\n"
9271             "  void f() {}\n"
9272             "private:\n"
9273             "  int i;\n"
9274             "protected:\n"
9275             "  int j;\n"
9276             "};\n",
9277             format("struct foo {\n"
9278                    "private:\n"
9279                    "  void f() {}\n"
9280                    "\n"
9281                    "private:\n"
9282                    "  int i;\n"
9283                    "\n"
9284                    "protected:\n"
9285                    "  int j;\n"
9286                    "};\n",
9287                    Style));
9288 
9289   // Check if MaxEmptyLinesToKeep is respected.
9290   EXPECT_EQ("struct foo {\n"
9291             "private:\n"
9292             "  void f() {}\n"
9293             "private:\n"
9294             "  int i;\n"
9295             "protected:\n"
9296             "  int j;\n"
9297             "};\n",
9298             format("struct foo {\n"
9299                    "private:\n"
9300                    "\n\n\n"
9301                    "  void f() {}\n"
9302                    "\n"
9303                    "private:\n"
9304                    "\n\n\n"
9305                    "  int i;\n"
9306                    "\n"
9307                    "protected:\n"
9308                    "\n\n\n"
9309                    "  int j;\n"
9310                    "};\n",
9311                    Style));
9312 
9313   Style.MaxEmptyLinesToKeep = 1u;
9314   EXPECT_EQ("struct foo {\n"
9315             "private:\n"
9316             "\n"
9317             "  void f() {}\n"
9318             "\n"
9319             "private:\n"
9320             "\n"
9321             "  int i;\n"
9322             "\n"
9323             "protected:\n"
9324             "\n"
9325             "  int j;\n"
9326             "};\n",
9327             format("struct foo {\n"
9328                    "private:\n"
9329                    "\n"
9330                    "  void f() {}\n"
9331                    "\n"
9332                    "private:\n"
9333                    "\n"
9334                    "  int i;\n"
9335                    "\n"
9336                    "protected:\n"
9337                    "\n"
9338                    "  int j;\n"
9339                    "};\n",
9340                    Style));
9341   // Check if no lines are kept.
9342   EXPECT_EQ("struct foo {\n"
9343             "private:\n"
9344             "  void f() {}\n"
9345             "\n"
9346             "private:\n"
9347             "  int i;\n"
9348             "\n"
9349             "protected:\n"
9350             "  int j;\n"
9351             "};\n",
9352             format("struct foo {\n"
9353                    "private:\n"
9354                    "  void f() {}\n"
9355                    "\n"
9356                    "private:\n"
9357                    "  int i;\n"
9358                    "\n"
9359                    "protected:\n"
9360                    "  int j;\n"
9361                    "};\n",
9362                    Style));
9363   // Check if MaxEmptyLinesToKeep is respected.
9364   EXPECT_EQ("struct foo {\n"
9365             "private:\n"
9366             "\n"
9367             "  void f() {}\n"
9368             "\n"
9369             "private:\n"
9370             "\n"
9371             "  int i;\n"
9372             "\n"
9373             "protected:\n"
9374             "\n"
9375             "  int j;\n"
9376             "};\n",
9377             format("struct foo {\n"
9378                    "private:\n"
9379                    "\n\n\n"
9380                    "  void f() {}\n"
9381                    "\n"
9382                    "private:\n"
9383                    "\n\n\n"
9384                    "  int i;\n"
9385                    "\n"
9386                    "protected:\n"
9387                    "\n\n\n"
9388                    "  int j;\n"
9389                    "};\n",
9390                    Style));
9391 
9392   Style.MaxEmptyLinesToKeep = 10u;
9393   EXPECT_EQ("struct foo {\n"
9394             "private:\n"
9395             "\n\n\n"
9396             "  void f() {}\n"
9397             "\n"
9398             "private:\n"
9399             "\n\n\n"
9400             "  int i;\n"
9401             "\n"
9402             "protected:\n"
9403             "\n\n\n"
9404             "  int j;\n"
9405             "};\n",
9406             format("struct foo {\n"
9407                    "private:\n"
9408                    "\n\n\n"
9409                    "  void f() {}\n"
9410                    "\n"
9411                    "private:\n"
9412                    "\n\n\n"
9413                    "  int i;\n"
9414                    "\n"
9415                    "protected:\n"
9416                    "\n\n\n"
9417                    "  int j;\n"
9418                    "};\n",
9419                    Style));
9420 
9421   // Test with comments.
9422   Style = getLLVMStyle();
9423   verifyFormat("struct foo {\n"
9424                "private:\n"
9425                "  // comment\n"
9426                "  void f() {}\n"
9427                "\n"
9428                "private: /* comment */\n"
9429                "  int i;\n"
9430                "};\n",
9431                Style);
9432   verifyFormat("struct foo {\n"
9433                "private:\n"
9434                "  // comment\n"
9435                "  void f() {}\n"
9436                "\n"
9437                "private: /* comment */\n"
9438                "  int i;\n"
9439                "};\n",
9440                "struct foo {\n"
9441                "private:\n"
9442                "\n"
9443                "  // comment\n"
9444                "  void f() {}\n"
9445                "\n"
9446                "private: /* comment */\n"
9447                "\n"
9448                "  int i;\n"
9449                "};\n",
9450                Style);
9451 
9452   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9453   verifyFormat("struct foo {\n"
9454                "private:\n"
9455                "\n"
9456                "  // comment\n"
9457                "  void f() {}\n"
9458                "\n"
9459                "private: /* comment */\n"
9460                "\n"
9461                "  int i;\n"
9462                "};\n",
9463                "struct foo {\n"
9464                "private:\n"
9465                "  // comment\n"
9466                "  void f() {}\n"
9467                "\n"
9468                "private: /* comment */\n"
9469                "  int i;\n"
9470                "};\n",
9471                Style);
9472   verifyFormat("struct foo {\n"
9473                "private:\n"
9474                "\n"
9475                "  // comment\n"
9476                "  void f() {}\n"
9477                "\n"
9478                "private: /* comment */\n"
9479                "\n"
9480                "  int i;\n"
9481                "};\n",
9482                Style);
9483 
9484   // Test with preprocessor defines.
9485   Style = getLLVMStyle();
9486   verifyFormat("struct foo {\n"
9487                "private:\n"
9488                "#ifdef FOO\n"
9489                "#endif\n"
9490                "  void f() {}\n"
9491                "};\n",
9492                Style);
9493   verifyFormat("struct foo {\n"
9494                "private:\n"
9495                "#ifdef FOO\n"
9496                "#endif\n"
9497                "  void f() {}\n"
9498                "};\n",
9499                "struct foo {\n"
9500                "private:\n"
9501                "\n"
9502                "#ifdef FOO\n"
9503                "#endif\n"
9504                "  void f() {}\n"
9505                "};\n",
9506                Style);
9507 
9508   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9509   verifyFormat("struct foo {\n"
9510                "private:\n"
9511                "\n"
9512                "#ifdef FOO\n"
9513                "#endif\n"
9514                "  void f() {}\n"
9515                "};\n",
9516                "struct foo {\n"
9517                "private:\n"
9518                "#ifdef FOO\n"
9519                "#endif\n"
9520                "  void f() {}\n"
9521                "};\n",
9522                Style);
9523   verifyFormat("struct foo {\n"
9524                "private:\n"
9525                "\n"
9526                "#ifdef FOO\n"
9527                "#endif\n"
9528                "  void f() {}\n"
9529                "};\n",
9530                Style);
9531 }
9532 
9533 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
9534   // Combined tests of EmptyLineAfterAccessModifier and
9535   // EmptyLineBeforeAccessModifier.
9536   FormatStyle Style = getLLVMStyle();
9537   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9538   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9539   verifyFormat("struct foo {\n"
9540                "private:\n"
9541                "\n"
9542                "protected:\n"
9543                "};\n",
9544                Style);
9545 
9546   Style.MaxEmptyLinesToKeep = 10u;
9547   // Both remove all new lines.
9548   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9549   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
9550   verifyFormat("struct foo {\n"
9551                "private:\n"
9552                "protected:\n"
9553                "};\n",
9554                "struct foo {\n"
9555                "private:\n"
9556                "\n\n\n"
9557                "protected:\n"
9558                "};\n",
9559                Style);
9560 
9561   // Leave tests rely on the code layout, test::messUp can not be used.
9562   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9563   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9564   Style.MaxEmptyLinesToKeep = 10u;
9565   EXPECT_EQ("struct foo {\n"
9566             "private:\n"
9567             "\n\n\n"
9568             "protected:\n"
9569             "};\n",
9570             format("struct foo {\n"
9571                    "private:\n"
9572                    "\n\n\n"
9573                    "protected:\n"
9574                    "};\n",
9575                    Style));
9576   Style.MaxEmptyLinesToKeep = 3u;
9577   EXPECT_EQ("struct foo {\n"
9578             "private:\n"
9579             "\n\n\n"
9580             "protected:\n"
9581             "};\n",
9582             format("struct foo {\n"
9583                    "private:\n"
9584                    "\n\n\n"
9585                    "protected:\n"
9586                    "};\n",
9587                    Style));
9588   Style.MaxEmptyLinesToKeep = 1u;
9589   EXPECT_EQ("struct foo {\n"
9590             "private:\n"
9591             "\n\n\n"
9592             "protected:\n"
9593             "};\n",
9594             format("struct foo {\n"
9595                    "private:\n"
9596                    "\n\n\n"
9597                    "protected:\n"
9598                    "};\n",
9599                    Style)); // Based on new lines in original document and not
9600                             // on the setting.
9601 
9602   Style.MaxEmptyLinesToKeep = 10u;
9603   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9604   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9605   // Newlines are kept if they are greater than zero,
9606   // test::messUp removes all new lines which changes the logic
9607   EXPECT_EQ("struct foo {\n"
9608             "private:\n"
9609             "\n\n\n"
9610             "protected:\n"
9611             "};\n",
9612             format("struct foo {\n"
9613                    "private:\n"
9614                    "\n\n\n"
9615                    "protected:\n"
9616                    "};\n",
9617                    Style));
9618 
9619   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9620   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9621   // test::messUp removes all new lines which changes the logic
9622   EXPECT_EQ("struct foo {\n"
9623             "private:\n"
9624             "\n\n\n"
9625             "protected:\n"
9626             "};\n",
9627             format("struct foo {\n"
9628                    "private:\n"
9629                    "\n\n\n"
9630                    "protected:\n"
9631                    "};\n",
9632                    Style));
9633 
9634   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9635   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
9636   EXPECT_EQ("struct foo {\n"
9637             "private:\n"
9638             "\n\n\n"
9639             "protected:\n"
9640             "};\n",
9641             format("struct foo {\n"
9642                    "private:\n"
9643                    "\n\n\n"
9644                    "protected:\n"
9645                    "};\n",
9646                    Style)); // test::messUp removes all new lines which changes
9647                             // the logic.
9648 
9649   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9650   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9651   verifyFormat("struct foo {\n"
9652                "private:\n"
9653                "protected:\n"
9654                "};\n",
9655                "struct foo {\n"
9656                "private:\n"
9657                "\n\n\n"
9658                "protected:\n"
9659                "};\n",
9660                Style);
9661 
9662   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9663   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
9664   EXPECT_EQ("struct foo {\n"
9665             "private:\n"
9666             "\n\n\n"
9667             "protected:\n"
9668             "};\n",
9669             format("struct foo {\n"
9670                    "private:\n"
9671                    "\n\n\n"
9672                    "protected:\n"
9673                    "};\n",
9674                    Style)); // test::messUp removes all new lines which changes
9675                             // the logic.
9676 
9677   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9678   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9679   verifyFormat("struct foo {\n"
9680                "private:\n"
9681                "protected:\n"
9682                "};\n",
9683                "struct foo {\n"
9684                "private:\n"
9685                "\n\n\n"
9686                "protected:\n"
9687                "};\n",
9688                Style);
9689 
9690   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
9691   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9692   verifyFormat("struct foo {\n"
9693                "private:\n"
9694                "protected:\n"
9695                "};\n",
9696                "struct foo {\n"
9697                "private:\n"
9698                "\n\n\n"
9699                "protected:\n"
9700                "};\n",
9701                Style);
9702 
9703   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
9704   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9705   verifyFormat("struct foo {\n"
9706                "private:\n"
9707                "protected:\n"
9708                "};\n",
9709                "struct foo {\n"
9710                "private:\n"
9711                "\n\n\n"
9712                "protected:\n"
9713                "};\n",
9714                Style);
9715 
9716   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
9717   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
9718   verifyFormat("struct foo {\n"
9719                "private:\n"
9720                "protected:\n"
9721                "};\n",
9722                "struct foo {\n"
9723                "private:\n"
9724                "\n\n\n"
9725                "protected:\n"
9726                "};\n",
9727                Style);
9728 }
9729 
9730 TEST_F(FormatTest, FormatsArrays) {
9731   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
9732                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
9733   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
9734                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
9735   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
9736                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
9737   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9738                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
9739   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9740                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
9741   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9742                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
9743                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
9744   verifyFormat(
9745       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
9746       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
9747       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
9748   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
9749                "    .aaaaaaaaaaaaaaaaaaaaaa();");
9750 
9751   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
9752                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
9753   verifyFormat(
9754       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
9755       "                                  .aaaaaaa[0]\n"
9756       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
9757   verifyFormat("a[::b::c];");
9758 
9759   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
9760 
9761   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
9762   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
9763 }
9764 
9765 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
9766   verifyFormat("(a)->b();");
9767   verifyFormat("--a;");
9768 }
9769 
9770 TEST_F(FormatTest, HandlesIncludeDirectives) {
9771   verifyFormat("#include <string>\n"
9772                "#include <a/b/c.h>\n"
9773                "#include \"a/b/string\"\n"
9774                "#include \"string.h\"\n"
9775                "#include \"string.h\"\n"
9776                "#include <a-a>\n"
9777                "#include < path with space >\n"
9778                "#include_next <test.h>"
9779                "#include \"abc.h\" // this is included for ABC\n"
9780                "#include \"some long include\" // with a comment\n"
9781                "#include \"some very long include path\"\n"
9782                "#include <some/very/long/include/path>\n",
9783                getLLVMStyleWithColumns(35));
9784   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
9785   EXPECT_EQ("#include <a>", format("#include<a>"));
9786 
9787   verifyFormat("#import <string>");
9788   verifyFormat("#import <a/b/c.h>");
9789   verifyFormat("#import \"a/b/string\"");
9790   verifyFormat("#import \"string.h\"");
9791   verifyFormat("#import \"string.h\"");
9792   verifyFormat("#if __has_include(<strstream>)\n"
9793                "#include <strstream>\n"
9794                "#endif");
9795 
9796   verifyFormat("#define MY_IMPORT <a/b>");
9797 
9798   verifyFormat("#if __has_include(<a/b>)");
9799   verifyFormat("#if __has_include_next(<a/b>)");
9800   verifyFormat("#define F __has_include(<a/b>)");
9801   verifyFormat("#define F __has_include_next(<a/b>)");
9802 
9803   // Protocol buffer definition or missing "#".
9804   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
9805                getLLVMStyleWithColumns(30));
9806 
9807   FormatStyle Style = getLLVMStyle();
9808   Style.AlwaysBreakBeforeMultilineStrings = true;
9809   Style.ColumnLimit = 0;
9810   verifyFormat("#import \"abc.h\"", Style);
9811 
9812   // But 'import' might also be a regular C++ namespace.
9813   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9814                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9815 }
9816 
9817 //===----------------------------------------------------------------------===//
9818 // Error recovery tests.
9819 //===----------------------------------------------------------------------===//
9820 
9821 TEST_F(FormatTest, IncompleteParameterLists) {
9822   FormatStyle NoBinPacking = getLLVMStyle();
9823   NoBinPacking.BinPackParameters = false;
9824   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
9825                "                        double *min_x,\n"
9826                "                        double *max_x,\n"
9827                "                        double *min_y,\n"
9828                "                        double *max_y,\n"
9829                "                        double *min_z,\n"
9830                "                        double *max_z, ) {}",
9831                NoBinPacking);
9832 }
9833 
9834 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
9835   verifyFormat("void f() { return; }\n42");
9836   verifyFormat("void f() {\n"
9837                "  if (0)\n"
9838                "    return;\n"
9839                "}\n"
9840                "42");
9841   verifyFormat("void f() { return }\n42");
9842   verifyFormat("void f() {\n"
9843                "  if (0)\n"
9844                "    return\n"
9845                "}\n"
9846                "42");
9847 }
9848 
9849 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
9850   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
9851   EXPECT_EQ("void f() {\n"
9852             "  if (a)\n"
9853             "    return\n"
9854             "}",
9855             format("void  f  (  )  {  if  ( a )  return  }"));
9856   EXPECT_EQ("namespace N {\n"
9857             "void f()\n"
9858             "}",
9859             format("namespace  N  {  void f()  }"));
9860   EXPECT_EQ("namespace N {\n"
9861             "void f() {}\n"
9862             "void g()\n"
9863             "} // namespace N",
9864             format("namespace N  { void f( ) { } void g( ) }"));
9865 }
9866 
9867 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
9868   verifyFormat("int aaaaaaaa =\n"
9869                "    // Overlylongcomment\n"
9870                "    b;",
9871                getLLVMStyleWithColumns(20));
9872   verifyFormat("function(\n"
9873                "    ShortArgument,\n"
9874                "    LoooooooooooongArgument);\n",
9875                getLLVMStyleWithColumns(20));
9876 }
9877 
9878 TEST_F(FormatTest, IncorrectAccessSpecifier) {
9879   verifyFormat("public:");
9880   verifyFormat("class A {\n"
9881                "public\n"
9882                "  void f() {}\n"
9883                "};");
9884   verifyFormat("public\n"
9885                "int qwerty;");
9886   verifyFormat("public\n"
9887                "B {}");
9888   verifyFormat("public\n"
9889                "{}");
9890   verifyFormat("public\n"
9891                "B { int x; }");
9892 }
9893 
9894 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
9895   verifyFormat("{");
9896   verifyFormat("#})");
9897   verifyNoCrash("(/**/[:!] ?[).");
9898 }
9899 
9900 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
9901   // Found by oss-fuzz:
9902   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
9903   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9904   Style.ColumnLimit = 60;
9905   verifyNoCrash(
9906       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
9907       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
9908       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
9909       Style);
9910 }
9911 
9912 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
9913   verifyFormat("do {\n}");
9914   verifyFormat("do {\n}\n"
9915                "f();");
9916   verifyFormat("do {\n}\n"
9917                "wheeee(fun);");
9918   verifyFormat("do {\n"
9919                "  f();\n"
9920                "}");
9921 }
9922 
9923 TEST_F(FormatTest, IncorrectCodeMissingParens) {
9924   verifyFormat("if {\n  foo;\n  foo();\n}");
9925   verifyFormat("switch {\n  foo;\n  foo();\n}");
9926   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
9927   verifyFormat("while {\n  foo;\n  foo();\n}");
9928   verifyFormat("do {\n  foo;\n  foo();\n} while;");
9929 }
9930 
9931 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
9932   verifyIncompleteFormat("namespace {\n"
9933                          "class Foo { Foo (\n"
9934                          "};\n"
9935                          "} // namespace");
9936 }
9937 
9938 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
9939   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
9940   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
9941   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
9942   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
9943 
9944   EXPECT_EQ("{\n"
9945             "  {\n"
9946             "    breakme(\n"
9947             "        qwe);\n"
9948             "  }\n",
9949             format("{\n"
9950                    "    {\n"
9951                    " breakme(qwe);\n"
9952                    "}\n",
9953                    getLLVMStyleWithColumns(10)));
9954 }
9955 
9956 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
9957   verifyFormat("int x = {\n"
9958                "    avariable,\n"
9959                "    b(alongervariable)};",
9960                getLLVMStyleWithColumns(25));
9961 }
9962 
9963 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
9964   verifyFormat("return (a)(b){1, 2, 3};");
9965 }
9966 
9967 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
9968   verifyFormat("vector<int> x{1, 2, 3, 4};");
9969   verifyFormat("vector<int> x{\n"
9970                "    1,\n"
9971                "    2,\n"
9972                "    3,\n"
9973                "    4,\n"
9974                "};");
9975   verifyFormat("vector<T> x{{}, {}, {}, {}};");
9976   verifyFormat("f({1, 2});");
9977   verifyFormat("auto v = Foo{-1};");
9978   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
9979   verifyFormat("Class::Class : member{1, 2, 3} {}");
9980   verifyFormat("new vector<int>{1, 2, 3};");
9981   verifyFormat("new int[3]{1, 2, 3};");
9982   verifyFormat("new int{1};");
9983   verifyFormat("return {arg1, arg2};");
9984   verifyFormat("return {arg1, SomeType{parameter}};");
9985   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
9986   verifyFormat("new T{arg1, arg2};");
9987   verifyFormat("f(MyMap[{composite, key}]);");
9988   verifyFormat("class Class {\n"
9989                "  T member = {arg1, arg2};\n"
9990                "};");
9991   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
9992   verifyFormat("const struct A a = {.a = 1, .b = 2};");
9993   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
9994   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
9995   verifyFormat("int a = std::is_integral<int>{} + 0;");
9996 
9997   verifyFormat("int foo(int i) { return fo1{}(i); }");
9998   verifyFormat("int foo(int i) { return fo1{}(i); }");
9999   verifyFormat("auto i = decltype(x){};");
10000   verifyFormat("auto i = typeof(x){};");
10001   verifyFormat("auto i = _Atomic(x){};");
10002   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
10003   verifyFormat("Node n{1, Node{1000}, //\n"
10004                "       2};");
10005   verifyFormat("Aaaa aaaaaaa{\n"
10006                "    {\n"
10007                "        aaaa,\n"
10008                "    },\n"
10009                "};");
10010   verifyFormat("class C : public D {\n"
10011                "  SomeClass SC{2};\n"
10012                "};");
10013   verifyFormat("class C : public A {\n"
10014                "  class D : public B {\n"
10015                "    void f() { int i{2}; }\n"
10016                "  };\n"
10017                "};");
10018   verifyFormat("#define A {a, a},");
10019 
10020   // Avoid breaking between equal sign and opening brace
10021   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
10022   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
10023   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
10024                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
10025                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
10026                "     {\"ccccccccccccccccccccc\", 2}};",
10027                AvoidBreakingFirstArgument);
10028 
10029   // Binpacking only if there is no trailing comma
10030   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
10031                "                      cccccccccc, dddddddddd};",
10032                getLLVMStyleWithColumns(50));
10033   verifyFormat("const Aaaaaa aaaaa = {\n"
10034                "    aaaaaaaaaaa,\n"
10035                "    bbbbbbbbbbb,\n"
10036                "    ccccccccccc,\n"
10037                "    ddddddddddd,\n"
10038                "};",
10039                getLLVMStyleWithColumns(50));
10040 
10041   // Cases where distinguising braced lists and blocks is hard.
10042   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
10043   verifyFormat("void f() {\n"
10044                "  return; // comment\n"
10045                "}\n"
10046                "SomeType t;");
10047   verifyFormat("void f() {\n"
10048                "  if (a) {\n"
10049                "    f();\n"
10050                "  }\n"
10051                "}\n"
10052                "SomeType t;");
10053 
10054   // In combination with BinPackArguments = false.
10055   FormatStyle NoBinPacking = getLLVMStyle();
10056   NoBinPacking.BinPackArguments = false;
10057   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
10058                "                      bbbbb,\n"
10059                "                      ccccc,\n"
10060                "                      ddddd,\n"
10061                "                      eeeee,\n"
10062                "                      ffffff,\n"
10063                "                      ggggg,\n"
10064                "                      hhhhhh,\n"
10065                "                      iiiiii,\n"
10066                "                      jjjjjj,\n"
10067                "                      kkkkkk};",
10068                NoBinPacking);
10069   verifyFormat("const Aaaaaa aaaaa = {\n"
10070                "    aaaaa,\n"
10071                "    bbbbb,\n"
10072                "    ccccc,\n"
10073                "    ddddd,\n"
10074                "    eeeee,\n"
10075                "    ffffff,\n"
10076                "    ggggg,\n"
10077                "    hhhhhh,\n"
10078                "    iiiiii,\n"
10079                "    jjjjjj,\n"
10080                "    kkkkkk,\n"
10081                "};",
10082                NoBinPacking);
10083   verifyFormat(
10084       "const Aaaaaa aaaaa = {\n"
10085       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
10086       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
10087       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
10088       "};",
10089       NoBinPacking);
10090 
10091   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
10092   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
10093             "    CDDDP83848_BMCR_REGISTER,\n"
10094             "    CDDDP83848_BMSR_REGISTER,\n"
10095             "    CDDDP83848_RBR_REGISTER};",
10096             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
10097                    "                                CDDDP83848_BMSR_REGISTER,\n"
10098                    "                                CDDDP83848_RBR_REGISTER};",
10099                    NoBinPacking));
10100 
10101   // FIXME: The alignment of these trailing comments might be bad. Then again,
10102   // this might be utterly useless in real code.
10103   verifyFormat("Constructor::Constructor()\n"
10104                "    : some_value{         //\n"
10105                "                 aaaaaaa, //\n"
10106                "                 bbbbbbb} {}");
10107 
10108   // In braced lists, the first comment is always assumed to belong to the
10109   // first element. Thus, it can be moved to the next or previous line as
10110   // appropriate.
10111   EXPECT_EQ("function({// First element:\n"
10112             "          1,\n"
10113             "          // Second element:\n"
10114             "          2});",
10115             format("function({\n"
10116                    "    // First element:\n"
10117                    "    1,\n"
10118                    "    // Second element:\n"
10119                    "    2});"));
10120   EXPECT_EQ("std::vector<int> MyNumbers{\n"
10121             "    // First element:\n"
10122             "    1,\n"
10123             "    // Second element:\n"
10124             "    2};",
10125             format("std::vector<int> MyNumbers{// First element:\n"
10126                    "                           1,\n"
10127                    "                           // Second element:\n"
10128                    "                           2};",
10129                    getLLVMStyleWithColumns(30)));
10130   // A trailing comma should still lead to an enforced line break and no
10131   // binpacking.
10132   EXPECT_EQ("vector<int> SomeVector = {\n"
10133             "    // aaa\n"
10134             "    1,\n"
10135             "    2,\n"
10136             "};",
10137             format("vector<int> SomeVector = { // aaa\n"
10138                    "    1, 2, };"));
10139 
10140   // C++11 brace initializer list l-braces should not be treated any differently
10141   // when breaking before lambda bodies is enabled
10142   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
10143   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
10144   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
10145   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
10146   verifyFormat(
10147       "std::runtime_error{\n"
10148       "    \"Long string which will force a break onto the next line...\"};",
10149       BreakBeforeLambdaBody);
10150 
10151   FormatStyle ExtraSpaces = getLLVMStyle();
10152   ExtraSpaces.Cpp11BracedListStyle = false;
10153   ExtraSpaces.ColumnLimit = 75;
10154   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
10155   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
10156   verifyFormat("f({ 1, 2 });", ExtraSpaces);
10157   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
10158   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
10159   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
10160   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
10161   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
10162   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
10163   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
10164   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
10165   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
10166   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
10167   verifyFormat("class Class {\n"
10168                "  T member = { arg1, arg2 };\n"
10169                "};",
10170                ExtraSpaces);
10171   verifyFormat(
10172       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10173       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
10174       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
10175       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
10176       ExtraSpaces);
10177   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
10178   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
10179                ExtraSpaces);
10180   verifyFormat(
10181       "someFunction(OtherParam,\n"
10182       "             BracedList{ // comment 1 (Forcing interesting break)\n"
10183       "                         param1, param2,\n"
10184       "                         // comment 2\n"
10185       "                         param3, param4 });",
10186       ExtraSpaces);
10187   verifyFormat(
10188       "std::this_thread::sleep_for(\n"
10189       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
10190       ExtraSpaces);
10191   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
10192                "    aaaaaaa,\n"
10193                "    aaaaaaaaaa,\n"
10194                "    aaaaa,\n"
10195                "    aaaaaaaaaaaaaaa,\n"
10196                "    aaa,\n"
10197                "    aaaaaaaaaa,\n"
10198                "    a,\n"
10199                "    aaaaaaaaaaaaaaaaaaaaa,\n"
10200                "    aaaaaaaaaaaa,\n"
10201                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
10202                "    aaaaaaa,\n"
10203                "    a};");
10204   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
10205   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
10206   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
10207 
10208   // Avoid breaking between initializer/equal sign and opening brace
10209   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
10210   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
10211                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
10212                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
10213                "  { \"ccccccccccccccccccccc\", 2 }\n"
10214                "};",
10215                ExtraSpaces);
10216   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
10217                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
10218                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
10219                "  { \"ccccccccccccccccccccc\", 2 }\n"
10220                "};",
10221                ExtraSpaces);
10222 
10223   FormatStyle SpaceBeforeBrace = getLLVMStyle();
10224   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
10225   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
10226   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
10227 
10228   FormatStyle SpaceBetweenBraces = getLLVMStyle();
10229   SpaceBetweenBraces.SpacesInAngles = true;
10230   SpaceBetweenBraces.SpacesInParentheses = true;
10231   SpaceBetweenBraces.SpacesInSquareBrackets = true;
10232   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
10233   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
10234   verifyFormat("vector< int > x{ // comment 1\n"
10235                "                 1, 2, 3, 4 };",
10236                SpaceBetweenBraces);
10237   SpaceBetweenBraces.ColumnLimit = 20;
10238   EXPECT_EQ("vector< int > x{\n"
10239             "    1, 2, 3, 4 };",
10240             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
10241   SpaceBetweenBraces.ColumnLimit = 24;
10242   EXPECT_EQ("vector< int > x{ 1, 2,\n"
10243             "                 3, 4 };",
10244             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
10245   EXPECT_EQ("vector< int > x{\n"
10246             "    1,\n"
10247             "    2,\n"
10248             "    3,\n"
10249             "    4,\n"
10250             "};",
10251             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
10252   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
10253   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
10254   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
10255 }
10256 
10257 TEST_F(FormatTest, FormatSpacesInAngles) {
10258   FormatStyle SpaceInAngles = getLLVMStyle();
10259   SpaceInAngles.SpacesInAngles = true;
10260   verifyFormat("vector< ::std::string > x1;", SpaceInAngles);
10261   verifyFormat("Foo< int, Bar > x2;", SpaceInAngles);
10262   verifyFormat("Foo< ::int, ::Bar > x3;", SpaceInAngles);
10263 
10264   SpaceInAngles.SpacesInAngles = false;
10265   verifyFormat("vector<::std::string> x4;", SpaceInAngles);
10266   verifyFormat("vector<int> x5;", SpaceInAngles);
10267   verifyFormat("Foo<int, Bar> x6;", SpaceInAngles);
10268   verifyFormat("Foo<::int, ::Bar> x7;", SpaceInAngles);
10269 }
10270 
10271 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
10272   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10273                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10274                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10275                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10276                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10277                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
10278   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
10279                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10280                "                 1, 22, 333, 4444, 55555, //\n"
10281                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10282                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
10283   verifyFormat(
10284       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
10285       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
10286       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
10287       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
10288       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
10289       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
10290       "                 7777777};");
10291   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
10292                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
10293                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
10294   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
10295                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
10296                "    // Separating comment.\n"
10297                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
10298   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
10299                "    // Leading comment\n"
10300                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
10301                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
10302   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
10303                "                 1, 1, 1, 1};",
10304                getLLVMStyleWithColumns(39));
10305   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
10306                "                 1, 1, 1, 1};",
10307                getLLVMStyleWithColumns(38));
10308   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
10309                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
10310                getLLVMStyleWithColumns(43));
10311   verifyFormat(
10312       "static unsigned SomeValues[10][3] = {\n"
10313       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
10314       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
10315   verifyFormat("static auto fields = new vector<string>{\n"
10316                "    \"aaaaaaaaaaaaa\",\n"
10317                "    \"aaaaaaaaaaaaa\",\n"
10318                "    \"aaaaaaaaaaaa\",\n"
10319                "    \"aaaaaaaaaaaaaa\",\n"
10320                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
10321                "    \"aaaaaaaaaaaa\",\n"
10322                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
10323                "};");
10324   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
10325   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
10326                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
10327                "                 3, cccccccccccccccccccccc};",
10328                getLLVMStyleWithColumns(60));
10329 
10330   // Trailing commas.
10331   verifyFormat("vector<int> x = {\n"
10332                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
10333                "};",
10334                getLLVMStyleWithColumns(39));
10335   verifyFormat("vector<int> x = {\n"
10336                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
10337                "};",
10338                getLLVMStyleWithColumns(39));
10339   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
10340                "                 1, 1, 1, 1,\n"
10341                "                 /**/ /**/};",
10342                getLLVMStyleWithColumns(39));
10343 
10344   // Trailing comment in the first line.
10345   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
10346                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
10347                "    111111111,  222222222,  3333333333,  444444444,  //\n"
10348                "    11111111,   22222222,   333333333,   44444444};");
10349   // Trailing comment in the last line.
10350   verifyFormat("int aaaaa[] = {\n"
10351                "    1, 2, 3, // comment\n"
10352                "    4, 5, 6  // comment\n"
10353                "};");
10354 
10355   // With nested lists, we should either format one item per line or all nested
10356   // lists one on line.
10357   // FIXME: For some nested lists, we can do better.
10358   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
10359                "        {aaaaaaaaaaaaaaaaaaa},\n"
10360                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
10361                "        {aaaaaaaaaaaaaaaaa}};",
10362                getLLVMStyleWithColumns(60));
10363   verifyFormat(
10364       "SomeStruct my_struct_array = {\n"
10365       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
10366       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
10367       "    {aaa, aaa},\n"
10368       "    {aaa, aaa},\n"
10369       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
10370       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
10371       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
10372 
10373   // No column layout should be used here.
10374   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
10375                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
10376 
10377   verifyNoCrash("a<,");
10378 
10379   // No braced initializer here.
10380   verifyFormat("void f() {\n"
10381                "  struct Dummy {};\n"
10382                "  f(v);\n"
10383                "}");
10384 
10385   // Long lists should be formatted in columns even if they are nested.
10386   verifyFormat(
10387       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10388       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10389       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10390       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10391       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10392       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
10393 
10394   // Allow "single-column" layout even if that violates the column limit. There
10395   // isn't going to be a better way.
10396   verifyFormat("std::vector<int> a = {\n"
10397                "    aaaaaaaa,\n"
10398                "    aaaaaaaa,\n"
10399                "    aaaaaaaa,\n"
10400                "    aaaaaaaa,\n"
10401                "    aaaaaaaaaa,\n"
10402                "    aaaaaaaa,\n"
10403                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
10404                getLLVMStyleWithColumns(30));
10405   verifyFormat("vector<int> aaaa = {\n"
10406                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10407                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10408                "    aaaaaa.aaaaaaa,\n"
10409                "    aaaaaa.aaaaaaa,\n"
10410                "    aaaaaa.aaaaaaa,\n"
10411                "    aaaaaa.aaaaaaa,\n"
10412                "};");
10413 
10414   // Don't create hanging lists.
10415   verifyFormat("someFunction(Param, {List1, List2,\n"
10416                "                     List3});",
10417                getLLVMStyleWithColumns(35));
10418   verifyFormat("someFunction(Param, Param,\n"
10419                "             {List1, List2,\n"
10420                "              List3});",
10421                getLLVMStyleWithColumns(35));
10422   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
10423                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
10424 }
10425 
10426 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
10427   FormatStyle DoNotMerge = getLLVMStyle();
10428   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10429 
10430   verifyFormat("void f() { return 42; }");
10431   verifyFormat("void f() {\n"
10432                "  return 42;\n"
10433                "}",
10434                DoNotMerge);
10435   verifyFormat("void f() {\n"
10436                "  // Comment\n"
10437                "}");
10438   verifyFormat("{\n"
10439                "#error {\n"
10440                "  int a;\n"
10441                "}");
10442   verifyFormat("{\n"
10443                "  int a;\n"
10444                "#error {\n"
10445                "}");
10446   verifyFormat("void f() {} // comment");
10447   verifyFormat("void f() { int a; } // comment");
10448   verifyFormat("void f() {\n"
10449                "} // comment",
10450                DoNotMerge);
10451   verifyFormat("void f() {\n"
10452                "  int a;\n"
10453                "} // comment",
10454                DoNotMerge);
10455   verifyFormat("void f() {\n"
10456                "} // comment",
10457                getLLVMStyleWithColumns(15));
10458 
10459   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
10460   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
10461 
10462   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
10463   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
10464   verifyFormat("class C {\n"
10465                "  C()\n"
10466                "      : iiiiiiii(nullptr),\n"
10467                "        kkkkkkk(nullptr),\n"
10468                "        mmmmmmm(nullptr),\n"
10469                "        nnnnnnn(nullptr) {}\n"
10470                "};",
10471                getGoogleStyle());
10472 
10473   FormatStyle NoColumnLimit = getLLVMStyle();
10474   NoColumnLimit.ColumnLimit = 0;
10475   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
10476   EXPECT_EQ("class C {\n"
10477             "  A() : b(0) {}\n"
10478             "};",
10479             format("class C{A():b(0){}};", NoColumnLimit));
10480   EXPECT_EQ("A()\n"
10481             "    : b(0) {\n"
10482             "}",
10483             format("A()\n:b(0)\n{\n}", NoColumnLimit));
10484 
10485   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
10486   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
10487       FormatStyle::SFS_None;
10488   EXPECT_EQ("A()\n"
10489             "    : b(0) {\n"
10490             "}",
10491             format("A():b(0){}", DoNotMergeNoColumnLimit));
10492   EXPECT_EQ("A()\n"
10493             "    : b(0) {\n"
10494             "}",
10495             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
10496 
10497   verifyFormat("#define A          \\\n"
10498                "  void f() {       \\\n"
10499                "    int i;         \\\n"
10500                "  }",
10501                getLLVMStyleWithColumns(20));
10502   verifyFormat("#define A           \\\n"
10503                "  void f() { int i; }",
10504                getLLVMStyleWithColumns(21));
10505   verifyFormat("#define A            \\\n"
10506                "  void f() {         \\\n"
10507                "    int i;           \\\n"
10508                "  }                  \\\n"
10509                "  int j;",
10510                getLLVMStyleWithColumns(22));
10511   verifyFormat("#define A             \\\n"
10512                "  void f() { int i; } \\\n"
10513                "  int j;",
10514                getLLVMStyleWithColumns(23));
10515 }
10516 
10517 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
10518   FormatStyle MergeEmptyOnly = getLLVMStyle();
10519   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
10520   verifyFormat("class C {\n"
10521                "  int f() {}\n"
10522                "};",
10523                MergeEmptyOnly);
10524   verifyFormat("class C {\n"
10525                "  int f() {\n"
10526                "    return 42;\n"
10527                "  }\n"
10528                "};",
10529                MergeEmptyOnly);
10530   verifyFormat("int f() {}", MergeEmptyOnly);
10531   verifyFormat("int f() {\n"
10532                "  return 42;\n"
10533                "}",
10534                MergeEmptyOnly);
10535 
10536   // Also verify behavior when BraceWrapping.AfterFunction = true
10537   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
10538   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
10539   verifyFormat("int f() {}", MergeEmptyOnly);
10540   verifyFormat("class C {\n"
10541                "  int f() {}\n"
10542                "};",
10543                MergeEmptyOnly);
10544 }
10545 
10546 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
10547   FormatStyle MergeInlineOnly = getLLVMStyle();
10548   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
10549   verifyFormat("class C {\n"
10550                "  int f() { return 42; }\n"
10551                "};",
10552                MergeInlineOnly);
10553   verifyFormat("int f() {\n"
10554                "  return 42;\n"
10555                "}",
10556                MergeInlineOnly);
10557 
10558   // SFS_Inline implies SFS_Empty
10559   verifyFormat("class C {\n"
10560                "  int f() {}\n"
10561                "};",
10562                MergeInlineOnly);
10563   verifyFormat("int f() {}", MergeInlineOnly);
10564 
10565   // Also verify behavior when BraceWrapping.AfterFunction = true
10566   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
10567   MergeInlineOnly.BraceWrapping.AfterFunction = true;
10568   verifyFormat("class C {\n"
10569                "  int f() { return 42; }\n"
10570                "};",
10571                MergeInlineOnly);
10572   verifyFormat("int f()\n"
10573                "{\n"
10574                "  return 42;\n"
10575                "}",
10576                MergeInlineOnly);
10577 
10578   // SFS_Inline implies SFS_Empty
10579   verifyFormat("int f() {}", MergeInlineOnly);
10580   verifyFormat("class C {\n"
10581                "  int f() {}\n"
10582                "};",
10583                MergeInlineOnly);
10584 }
10585 
10586 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
10587   FormatStyle MergeInlineOnly = getLLVMStyle();
10588   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
10589       FormatStyle::SFS_InlineOnly;
10590   verifyFormat("class C {\n"
10591                "  int f() { return 42; }\n"
10592                "};",
10593                MergeInlineOnly);
10594   verifyFormat("int f() {\n"
10595                "  return 42;\n"
10596                "}",
10597                MergeInlineOnly);
10598 
10599   // SFS_InlineOnly does not imply SFS_Empty
10600   verifyFormat("class C {\n"
10601                "  int f() {}\n"
10602                "};",
10603                MergeInlineOnly);
10604   verifyFormat("int f() {\n"
10605                "}",
10606                MergeInlineOnly);
10607 
10608   // Also verify behavior when BraceWrapping.AfterFunction = true
10609   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
10610   MergeInlineOnly.BraceWrapping.AfterFunction = true;
10611   verifyFormat("class C {\n"
10612                "  int f() { return 42; }\n"
10613                "};",
10614                MergeInlineOnly);
10615   verifyFormat("int f()\n"
10616                "{\n"
10617                "  return 42;\n"
10618                "}",
10619                MergeInlineOnly);
10620 
10621   // SFS_InlineOnly does not imply SFS_Empty
10622   verifyFormat("int f()\n"
10623                "{\n"
10624                "}",
10625                MergeInlineOnly);
10626   verifyFormat("class C {\n"
10627                "  int f() {}\n"
10628                "};",
10629                MergeInlineOnly);
10630 }
10631 
10632 TEST_F(FormatTest, SplitEmptyFunction) {
10633   FormatStyle Style = getLLVMStyle();
10634   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10635   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10636   Style.BraceWrapping.AfterFunction = true;
10637   Style.BraceWrapping.SplitEmptyFunction = false;
10638   Style.ColumnLimit = 40;
10639 
10640   verifyFormat("int f()\n"
10641                "{}",
10642                Style);
10643   verifyFormat("int f()\n"
10644                "{\n"
10645                "  return 42;\n"
10646                "}",
10647                Style);
10648   verifyFormat("int f()\n"
10649                "{\n"
10650                "  // some comment\n"
10651                "}",
10652                Style);
10653 
10654   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
10655   verifyFormat("int f() {}", Style);
10656   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10657                "{}",
10658                Style);
10659   verifyFormat("int f()\n"
10660                "{\n"
10661                "  return 0;\n"
10662                "}",
10663                Style);
10664 
10665   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
10666   verifyFormat("class Foo {\n"
10667                "  int f() {}\n"
10668                "};\n",
10669                Style);
10670   verifyFormat("class Foo {\n"
10671                "  int f() { return 0; }\n"
10672                "};\n",
10673                Style);
10674   verifyFormat("class Foo {\n"
10675                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10676                "  {}\n"
10677                "};\n",
10678                Style);
10679   verifyFormat("class Foo {\n"
10680                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10681                "  {\n"
10682                "    return 0;\n"
10683                "  }\n"
10684                "};\n",
10685                Style);
10686 
10687   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
10688   verifyFormat("int f() {}", Style);
10689   verifyFormat("int f() { return 0; }", Style);
10690   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10691                "{}",
10692                Style);
10693   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10694                "{\n"
10695                "  return 0;\n"
10696                "}",
10697                Style);
10698 }
10699 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
10700   FormatStyle Style = getLLVMStyle();
10701   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
10702   verifyFormat("#ifdef A\n"
10703                "int f() {}\n"
10704                "#else\n"
10705                "int g() {}\n"
10706                "#endif",
10707                Style);
10708 }
10709 
10710 TEST_F(FormatTest, SplitEmptyClass) {
10711   FormatStyle Style = getLLVMStyle();
10712   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10713   Style.BraceWrapping.AfterClass = true;
10714   Style.BraceWrapping.SplitEmptyRecord = false;
10715 
10716   verifyFormat("class Foo\n"
10717                "{};",
10718                Style);
10719   verifyFormat("/* something */ class Foo\n"
10720                "{};",
10721                Style);
10722   verifyFormat("template <typename X> class Foo\n"
10723                "{};",
10724                Style);
10725   verifyFormat("class Foo\n"
10726                "{\n"
10727                "  Foo();\n"
10728                "};",
10729                Style);
10730   verifyFormat("typedef class Foo\n"
10731                "{\n"
10732                "} Foo_t;",
10733                Style);
10734 
10735   Style.BraceWrapping.SplitEmptyRecord = true;
10736   Style.BraceWrapping.AfterStruct = true;
10737   verifyFormat("class rep\n"
10738                "{\n"
10739                "};",
10740                Style);
10741   verifyFormat("struct rep\n"
10742                "{\n"
10743                "};",
10744                Style);
10745   verifyFormat("template <typename T> class rep\n"
10746                "{\n"
10747                "};",
10748                Style);
10749   verifyFormat("template <typename T> struct rep\n"
10750                "{\n"
10751                "};",
10752                Style);
10753   verifyFormat("class rep\n"
10754                "{\n"
10755                "  int x;\n"
10756                "};",
10757                Style);
10758   verifyFormat("struct rep\n"
10759                "{\n"
10760                "  int x;\n"
10761                "};",
10762                Style);
10763   verifyFormat("template <typename T> class rep\n"
10764                "{\n"
10765                "  int x;\n"
10766                "};",
10767                Style);
10768   verifyFormat("template <typename T> struct rep\n"
10769                "{\n"
10770                "  int x;\n"
10771                "};",
10772                Style);
10773   verifyFormat("template <typename T> class rep // Foo\n"
10774                "{\n"
10775                "  int x;\n"
10776                "};",
10777                Style);
10778   verifyFormat("template <typename T> struct rep // Bar\n"
10779                "{\n"
10780                "  int x;\n"
10781                "};",
10782                Style);
10783 
10784   verifyFormat("template <typename T> class rep<T>\n"
10785                "{\n"
10786                "  int x;\n"
10787                "};",
10788                Style);
10789 
10790   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
10791                "{\n"
10792                "  int x;\n"
10793                "};",
10794                Style);
10795   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
10796                "{\n"
10797                "};",
10798                Style);
10799 
10800   verifyFormat("#include \"stdint.h\"\n"
10801                "namespace rep {}",
10802                Style);
10803   verifyFormat("#include <stdint.h>\n"
10804                "namespace rep {}",
10805                Style);
10806   verifyFormat("#include <stdint.h>\n"
10807                "namespace rep {}",
10808                "#include <stdint.h>\n"
10809                "namespace rep {\n"
10810                "\n"
10811                "\n"
10812                "}",
10813                Style);
10814 }
10815 
10816 TEST_F(FormatTest, SplitEmptyStruct) {
10817   FormatStyle Style = getLLVMStyle();
10818   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10819   Style.BraceWrapping.AfterStruct = true;
10820   Style.BraceWrapping.SplitEmptyRecord = false;
10821 
10822   verifyFormat("struct Foo\n"
10823                "{};",
10824                Style);
10825   verifyFormat("/* something */ struct Foo\n"
10826                "{};",
10827                Style);
10828   verifyFormat("template <typename X> struct Foo\n"
10829                "{};",
10830                Style);
10831   verifyFormat("struct Foo\n"
10832                "{\n"
10833                "  Foo();\n"
10834                "};",
10835                Style);
10836   verifyFormat("typedef struct Foo\n"
10837                "{\n"
10838                "} Foo_t;",
10839                Style);
10840   // typedef struct Bar {} Bar_t;
10841 }
10842 
10843 TEST_F(FormatTest, SplitEmptyUnion) {
10844   FormatStyle Style = getLLVMStyle();
10845   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10846   Style.BraceWrapping.AfterUnion = true;
10847   Style.BraceWrapping.SplitEmptyRecord = false;
10848 
10849   verifyFormat("union Foo\n"
10850                "{};",
10851                Style);
10852   verifyFormat("/* something */ union Foo\n"
10853                "{};",
10854                Style);
10855   verifyFormat("union Foo\n"
10856                "{\n"
10857                "  A,\n"
10858                "};",
10859                Style);
10860   verifyFormat("typedef union Foo\n"
10861                "{\n"
10862                "} Foo_t;",
10863                Style);
10864 }
10865 
10866 TEST_F(FormatTest, SplitEmptyNamespace) {
10867   FormatStyle Style = getLLVMStyle();
10868   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10869   Style.BraceWrapping.AfterNamespace = true;
10870   Style.BraceWrapping.SplitEmptyNamespace = false;
10871 
10872   verifyFormat("namespace Foo\n"
10873                "{};",
10874                Style);
10875   verifyFormat("/* something */ namespace Foo\n"
10876                "{};",
10877                Style);
10878   verifyFormat("inline namespace Foo\n"
10879                "{};",
10880                Style);
10881   verifyFormat("/* something */ inline namespace Foo\n"
10882                "{};",
10883                Style);
10884   verifyFormat("export namespace Foo\n"
10885                "{};",
10886                Style);
10887   verifyFormat("namespace Foo\n"
10888                "{\n"
10889                "void Bar();\n"
10890                "};",
10891                Style);
10892 }
10893 
10894 TEST_F(FormatTest, NeverMergeShortRecords) {
10895   FormatStyle Style = getLLVMStyle();
10896 
10897   verifyFormat("class Foo {\n"
10898                "  Foo();\n"
10899                "};",
10900                Style);
10901   verifyFormat("typedef class Foo {\n"
10902                "  Foo();\n"
10903                "} Foo_t;",
10904                Style);
10905   verifyFormat("struct Foo {\n"
10906                "  Foo();\n"
10907                "};",
10908                Style);
10909   verifyFormat("typedef struct Foo {\n"
10910                "  Foo();\n"
10911                "} Foo_t;",
10912                Style);
10913   verifyFormat("union Foo {\n"
10914                "  A,\n"
10915                "};",
10916                Style);
10917   verifyFormat("typedef union Foo {\n"
10918                "  A,\n"
10919                "} Foo_t;",
10920                Style);
10921   verifyFormat("namespace Foo {\n"
10922                "void Bar();\n"
10923                "};",
10924                Style);
10925 
10926   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10927   Style.BraceWrapping.AfterClass = true;
10928   Style.BraceWrapping.AfterStruct = true;
10929   Style.BraceWrapping.AfterUnion = true;
10930   Style.BraceWrapping.AfterNamespace = true;
10931   verifyFormat("class Foo\n"
10932                "{\n"
10933                "  Foo();\n"
10934                "};",
10935                Style);
10936   verifyFormat("typedef class Foo\n"
10937                "{\n"
10938                "  Foo();\n"
10939                "} Foo_t;",
10940                Style);
10941   verifyFormat("struct Foo\n"
10942                "{\n"
10943                "  Foo();\n"
10944                "};",
10945                Style);
10946   verifyFormat("typedef struct Foo\n"
10947                "{\n"
10948                "  Foo();\n"
10949                "} Foo_t;",
10950                Style);
10951   verifyFormat("union Foo\n"
10952                "{\n"
10953                "  A,\n"
10954                "};",
10955                Style);
10956   verifyFormat("typedef union Foo\n"
10957                "{\n"
10958                "  A,\n"
10959                "} Foo_t;",
10960                Style);
10961   verifyFormat("namespace Foo\n"
10962                "{\n"
10963                "void Bar();\n"
10964                "};",
10965                Style);
10966 }
10967 
10968 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
10969   // Elaborate type variable declarations.
10970   verifyFormat("struct foo a = {bar};\nint n;");
10971   verifyFormat("class foo a = {bar};\nint n;");
10972   verifyFormat("union foo a = {bar};\nint n;");
10973 
10974   // Elaborate types inside function definitions.
10975   verifyFormat("struct foo f() {}\nint n;");
10976   verifyFormat("class foo f() {}\nint n;");
10977   verifyFormat("union foo f() {}\nint n;");
10978 
10979   // Templates.
10980   verifyFormat("template <class X> void f() {}\nint n;");
10981   verifyFormat("template <struct X> void f() {}\nint n;");
10982   verifyFormat("template <union X> void f() {}\nint n;");
10983 
10984   // Actual definitions...
10985   verifyFormat("struct {\n} n;");
10986   verifyFormat(
10987       "template <template <class T, class Y>, class Z> class X {\n} n;");
10988   verifyFormat("union Z {\n  int n;\n} x;");
10989   verifyFormat("class MACRO Z {\n} n;");
10990   verifyFormat("class MACRO(X) Z {\n} n;");
10991   verifyFormat("class __attribute__(X) Z {\n} n;");
10992   verifyFormat("class __declspec(X) Z {\n} n;");
10993   verifyFormat("class A##B##C {\n} n;");
10994   verifyFormat("class alignas(16) Z {\n} n;");
10995   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
10996   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
10997 
10998   // Redefinition from nested context:
10999   verifyFormat("class A::B::C {\n} n;");
11000 
11001   // Template definitions.
11002   verifyFormat(
11003       "template <typename F>\n"
11004       "Matcher(const Matcher<F> &Other,\n"
11005       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
11006       "                             !is_same<F, T>::value>::type * = 0)\n"
11007       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
11008 
11009   // FIXME: This is still incorrectly handled at the formatter side.
11010   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
11011   verifyFormat("int i = SomeFunction(a<b, a> b);");
11012 
11013   // FIXME:
11014   // This now gets parsed incorrectly as class definition.
11015   // verifyFormat("class A<int> f() {\n}\nint n;");
11016 
11017   // Elaborate types where incorrectly parsing the structural element would
11018   // break the indent.
11019   verifyFormat("if (true)\n"
11020                "  class X x;\n"
11021                "else\n"
11022                "  f();\n");
11023 
11024   // This is simply incomplete. Formatting is not important, but must not crash.
11025   verifyFormat("class A:");
11026 }
11027 
11028 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
11029   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
11030             format("#error Leave     all         white!!!!! space* alone!\n"));
11031   EXPECT_EQ(
11032       "#warning Leave     all         white!!!!! space* alone!\n",
11033       format("#warning Leave     all         white!!!!! space* alone!\n"));
11034   EXPECT_EQ("#error 1", format("  #  error   1"));
11035   EXPECT_EQ("#warning 1", format("  #  warning 1"));
11036 }
11037 
11038 TEST_F(FormatTest, FormatHashIfExpressions) {
11039   verifyFormat("#if AAAA && BBBB");
11040   verifyFormat("#if (AAAA && BBBB)");
11041   verifyFormat("#elif (AAAA && BBBB)");
11042   // FIXME: Come up with a better indentation for #elif.
11043   verifyFormat(
11044       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
11045       "    defined(BBBBBBBB)\n"
11046       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
11047       "    defined(BBBBBBBB)\n"
11048       "#endif",
11049       getLLVMStyleWithColumns(65));
11050 }
11051 
11052 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
11053   FormatStyle AllowsMergedIf = getGoogleStyle();
11054   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
11055       FormatStyle::SIS_WithoutElse;
11056   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
11057   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
11058   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
11059   EXPECT_EQ("if (true) return 42;",
11060             format("if (true)\nreturn 42;", AllowsMergedIf));
11061   FormatStyle ShortMergedIf = AllowsMergedIf;
11062   ShortMergedIf.ColumnLimit = 25;
11063   verifyFormat("#define A \\\n"
11064                "  if (true) return 42;",
11065                ShortMergedIf);
11066   verifyFormat("#define A \\\n"
11067                "  f();    \\\n"
11068                "  if (true)\n"
11069                "#define B",
11070                ShortMergedIf);
11071   verifyFormat("#define A \\\n"
11072                "  f();    \\\n"
11073                "  if (true)\n"
11074                "g();",
11075                ShortMergedIf);
11076   verifyFormat("{\n"
11077                "#ifdef A\n"
11078                "  // Comment\n"
11079                "  if (true) continue;\n"
11080                "#endif\n"
11081                "  // Comment\n"
11082                "  if (true) continue;\n"
11083                "}",
11084                ShortMergedIf);
11085   ShortMergedIf.ColumnLimit = 33;
11086   verifyFormat("#define A \\\n"
11087                "  if constexpr (true) return 42;",
11088                ShortMergedIf);
11089   verifyFormat("#define A \\\n"
11090                "  if CONSTEXPR (true) return 42;",
11091                ShortMergedIf);
11092   ShortMergedIf.ColumnLimit = 29;
11093   verifyFormat("#define A                   \\\n"
11094                "  if (aaaaaaaaaa) return 1; \\\n"
11095                "  return 2;",
11096                ShortMergedIf);
11097   ShortMergedIf.ColumnLimit = 28;
11098   verifyFormat("#define A         \\\n"
11099                "  if (aaaaaaaaaa) \\\n"
11100                "    return 1;     \\\n"
11101                "  return 2;",
11102                ShortMergedIf);
11103   verifyFormat("#define A                \\\n"
11104                "  if constexpr (aaaaaaa) \\\n"
11105                "    return 1;            \\\n"
11106                "  return 2;",
11107                ShortMergedIf);
11108   verifyFormat("#define A                \\\n"
11109                "  if CONSTEXPR (aaaaaaa) \\\n"
11110                "    return 1;            \\\n"
11111                "  return 2;",
11112                ShortMergedIf);
11113 }
11114 
11115 TEST_F(FormatTest, FormatStarDependingOnContext) {
11116   verifyFormat("void f(int *a);");
11117   verifyFormat("void f() { f(fint * b); }");
11118   verifyFormat("class A {\n  void f(int *a);\n};");
11119   verifyFormat("class A {\n  int *a;\n};");
11120   verifyFormat("namespace a {\n"
11121                "namespace b {\n"
11122                "class A {\n"
11123                "  void f() {}\n"
11124                "  int *a;\n"
11125                "};\n"
11126                "} // namespace b\n"
11127                "} // namespace a");
11128 }
11129 
11130 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
11131   verifyFormat("while");
11132   verifyFormat("operator");
11133 }
11134 
11135 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
11136   // This code would be painfully slow to format if we didn't skip it.
11137   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
11138                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11139                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11140                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11141                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11142                    "A(1, 1)\n"
11143                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
11144                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11145                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11146                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11147                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11148                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11149                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11150                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11151                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11152                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
11153   // Deeply nested part is untouched, rest is formatted.
11154   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
11155             format(std::string("int    i;\n") + Code + "int    j;\n",
11156                    getLLVMStyle(), SC_ExpectIncomplete));
11157 }
11158 
11159 //===----------------------------------------------------------------------===//
11160 // Objective-C tests.
11161 //===----------------------------------------------------------------------===//
11162 
11163 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
11164   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
11165   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
11166             format("-(NSUInteger)indexOfObject:(id)anObject;"));
11167   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
11168   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
11169   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
11170             format("-(NSInteger)Method3:(id)anObject;"));
11171   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
11172             format("-(NSInteger)Method4:(id)anObject;"));
11173   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
11174             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
11175   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
11176             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
11177   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
11178             "forAllCells:(BOOL)flag;",
11179             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
11180                    "forAllCells:(BOOL)flag;"));
11181 
11182   // Very long objectiveC method declaration.
11183   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
11184                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
11185   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
11186                "                    inRange:(NSRange)range\n"
11187                "                   outRange:(NSRange)out_range\n"
11188                "                  outRange1:(NSRange)out_range1\n"
11189                "                  outRange2:(NSRange)out_range2\n"
11190                "                  outRange3:(NSRange)out_range3\n"
11191                "                  outRange4:(NSRange)out_range4\n"
11192                "                  outRange5:(NSRange)out_range5\n"
11193                "                  outRange6:(NSRange)out_range6\n"
11194                "                  outRange7:(NSRange)out_range7\n"
11195                "                  outRange8:(NSRange)out_range8\n"
11196                "                  outRange9:(NSRange)out_range9;");
11197 
11198   // When the function name has to be wrapped.
11199   FormatStyle Style = getLLVMStyle();
11200   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
11201   // and always indents instead.
11202   Style.IndentWrappedFunctionNames = false;
11203   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
11204                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
11205                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
11206                "}",
11207                Style);
11208   Style.IndentWrappedFunctionNames = true;
11209   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
11210                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
11211                "               anotherName:(NSString)dddddddddddddd {\n"
11212                "}",
11213                Style);
11214 
11215   verifyFormat("- (int)sum:(vector<int>)numbers;");
11216   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
11217   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
11218   // protocol lists (but not for template classes):
11219   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
11220 
11221   verifyFormat("- (int (*)())foo:(int (*)())f;");
11222   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
11223 
11224   // If there's no return type (very rare in practice!), LLVM and Google style
11225   // agree.
11226   verifyFormat("- foo;");
11227   verifyFormat("- foo:(int)f;");
11228   verifyGoogleFormat("- foo:(int)foo;");
11229 }
11230 
11231 TEST_F(FormatTest, BreaksStringLiterals) {
11232   EXPECT_EQ("\"some text \"\n"
11233             "\"other\";",
11234             format("\"some text other\";", getLLVMStyleWithColumns(12)));
11235   EXPECT_EQ("\"some text \"\n"
11236             "\"other\";",
11237             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
11238   EXPECT_EQ(
11239       "#define A  \\\n"
11240       "  \"some \"  \\\n"
11241       "  \"text \"  \\\n"
11242       "  \"other\";",
11243       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
11244   EXPECT_EQ(
11245       "#define A  \\\n"
11246       "  \"so \"    \\\n"
11247       "  \"text \"  \\\n"
11248       "  \"other\";",
11249       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
11250 
11251   EXPECT_EQ("\"some text\"",
11252             format("\"some text\"", getLLVMStyleWithColumns(1)));
11253   EXPECT_EQ("\"some text\"",
11254             format("\"some text\"", getLLVMStyleWithColumns(11)));
11255   EXPECT_EQ("\"some \"\n"
11256             "\"text\"",
11257             format("\"some text\"", getLLVMStyleWithColumns(10)));
11258   EXPECT_EQ("\"some \"\n"
11259             "\"text\"",
11260             format("\"some text\"", getLLVMStyleWithColumns(7)));
11261   EXPECT_EQ("\"some\"\n"
11262             "\" tex\"\n"
11263             "\"t\"",
11264             format("\"some text\"", getLLVMStyleWithColumns(6)));
11265   EXPECT_EQ("\"some\"\n"
11266             "\" tex\"\n"
11267             "\" and\"",
11268             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
11269   EXPECT_EQ("\"some\"\n"
11270             "\"/tex\"\n"
11271             "\"/and\"",
11272             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
11273 
11274   EXPECT_EQ("variable =\n"
11275             "    \"long string \"\n"
11276             "    \"literal\";",
11277             format("variable = \"long string literal\";",
11278                    getLLVMStyleWithColumns(20)));
11279 
11280   EXPECT_EQ("variable = f(\n"
11281             "    \"long string \"\n"
11282             "    \"literal\",\n"
11283             "    short,\n"
11284             "    loooooooooooooooooooong);",
11285             format("variable = f(\"long string literal\", short, "
11286                    "loooooooooooooooooooong);",
11287                    getLLVMStyleWithColumns(20)));
11288 
11289   EXPECT_EQ(
11290       "f(g(\"long string \"\n"
11291       "    \"literal\"),\n"
11292       "  b);",
11293       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
11294   EXPECT_EQ("f(g(\"long string \"\n"
11295             "    \"literal\",\n"
11296             "    a),\n"
11297             "  b);",
11298             format("f(g(\"long string literal\", a), b);",
11299                    getLLVMStyleWithColumns(20)));
11300   EXPECT_EQ(
11301       "f(\"one two\".split(\n"
11302       "    variable));",
11303       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
11304   EXPECT_EQ("f(\"one two three four five six \"\n"
11305             "  \"seven\".split(\n"
11306             "      really_looooong_variable));",
11307             format("f(\"one two three four five six seven\"."
11308                    "split(really_looooong_variable));",
11309                    getLLVMStyleWithColumns(33)));
11310 
11311   EXPECT_EQ("f(\"some \"\n"
11312             "  \"text\",\n"
11313             "  other);",
11314             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
11315 
11316   // Only break as a last resort.
11317   verifyFormat(
11318       "aaaaaaaaaaaaaaaaaaaa(\n"
11319       "    aaaaaaaaaaaaaaaaaaaa,\n"
11320       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
11321 
11322   EXPECT_EQ("\"splitmea\"\n"
11323             "\"trandomp\"\n"
11324             "\"oint\"",
11325             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
11326 
11327   EXPECT_EQ("\"split/\"\n"
11328             "\"pathat/\"\n"
11329             "\"slashes\"",
11330             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
11331 
11332   EXPECT_EQ("\"split/\"\n"
11333             "\"pathat/\"\n"
11334             "\"slashes\"",
11335             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
11336   EXPECT_EQ("\"split at \"\n"
11337             "\"spaces/at/\"\n"
11338             "\"slashes.at.any$\"\n"
11339             "\"non-alphanumeric%\"\n"
11340             "\"1111111111characte\"\n"
11341             "\"rs\"",
11342             format("\"split at "
11343                    "spaces/at/"
11344                    "slashes.at."
11345                    "any$non-"
11346                    "alphanumeric%"
11347                    "1111111111characte"
11348                    "rs\"",
11349                    getLLVMStyleWithColumns(20)));
11350 
11351   // Verify that splitting the strings understands
11352   // Style::AlwaysBreakBeforeMultilineStrings.
11353   EXPECT_EQ("aaaaaaaaaaaa(\n"
11354             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
11355             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
11356             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
11357                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
11358                    "aaaaaaaaaaaaaaaaaaaaaa\");",
11359                    getGoogleStyle()));
11360   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
11361             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
11362             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
11363                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
11364                    "aaaaaaaaaaaaaaaaaaaaaa\";",
11365                    getGoogleStyle()));
11366   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
11367             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
11368             format("llvm::outs() << "
11369                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
11370                    "aaaaaaaaaaaaaaaaaaa\";"));
11371   EXPECT_EQ("ffff(\n"
11372             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
11373             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
11374             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
11375                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
11376                    getGoogleStyle()));
11377 
11378   FormatStyle Style = getLLVMStyleWithColumns(12);
11379   Style.BreakStringLiterals = false;
11380   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
11381 
11382   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
11383   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
11384   EXPECT_EQ("#define A \\\n"
11385             "  \"some \" \\\n"
11386             "  \"text \" \\\n"
11387             "  \"other\";",
11388             format("#define A \"some text other\";", AlignLeft));
11389 }
11390 
11391 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
11392   EXPECT_EQ("C a = \"some more \"\n"
11393             "      \"text\";",
11394             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
11395 }
11396 
11397 TEST_F(FormatTest, FullyRemoveEmptyLines) {
11398   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
11399   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11400   EXPECT_EQ("int i = a(b());",
11401             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
11402 }
11403 
11404 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
11405   EXPECT_EQ(
11406       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
11407       "(\n"
11408       "    \"x\t\");",
11409       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
11410              "aaaaaaa("
11411              "\"x\t\");"));
11412 }
11413 
11414 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
11415   EXPECT_EQ(
11416       "u8\"utf8 string \"\n"
11417       "u8\"literal\";",
11418       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
11419   EXPECT_EQ(
11420       "u\"utf16 string \"\n"
11421       "u\"literal\";",
11422       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
11423   EXPECT_EQ(
11424       "U\"utf32 string \"\n"
11425       "U\"literal\";",
11426       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
11427   EXPECT_EQ("L\"wide string \"\n"
11428             "L\"literal\";",
11429             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
11430   EXPECT_EQ("@\"NSString \"\n"
11431             "@\"literal\";",
11432             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
11433   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
11434 
11435   // This input makes clang-format try to split the incomplete unicode escape
11436   // sequence, which used to lead to a crasher.
11437   verifyNoCrash(
11438       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
11439       getLLVMStyleWithColumns(60));
11440 }
11441 
11442 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
11443   FormatStyle Style = getGoogleStyleWithColumns(15);
11444   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
11445   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
11446   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
11447   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
11448   EXPECT_EQ("u8R\"x(raw literal)x\";",
11449             format("u8R\"x(raw literal)x\";", Style));
11450 }
11451 
11452 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
11453   FormatStyle Style = getLLVMStyleWithColumns(20);
11454   EXPECT_EQ(
11455       "_T(\"aaaaaaaaaaaaaa\")\n"
11456       "_T(\"aaaaaaaaaaaaaa\")\n"
11457       "_T(\"aaaaaaaaaaaa\")",
11458       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
11459   EXPECT_EQ("f(x,\n"
11460             "  _T(\"aaaaaaaaaaaa\")\n"
11461             "  _T(\"aaa\"),\n"
11462             "  z);",
11463             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
11464 
11465   // FIXME: Handle embedded spaces in one iteration.
11466   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
11467   //            "_T(\"aaaaaaaaaaaaa\")\n"
11468   //            "_T(\"aaaaaaaaaaaaa\")\n"
11469   //            "_T(\"a\")",
11470   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
11471   //                   getLLVMStyleWithColumns(20)));
11472   EXPECT_EQ(
11473       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
11474       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
11475   EXPECT_EQ("f(\n"
11476             "#if !TEST\n"
11477             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
11478             "#endif\n"
11479             ");",
11480             format("f(\n"
11481                    "#if !TEST\n"
11482                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
11483                    "#endif\n"
11484                    ");"));
11485   EXPECT_EQ("f(\n"
11486             "\n"
11487             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
11488             format("f(\n"
11489                    "\n"
11490                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
11491 }
11492 
11493 TEST_F(FormatTest, BreaksStringLiteralOperands) {
11494   // In a function call with two operands, the second can be broken with no line
11495   // break before it.
11496   EXPECT_EQ(
11497       "func(a, \"long long \"\n"
11498       "        \"long long\");",
11499       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
11500   // In a function call with three operands, the second must be broken with a
11501   // line break before it.
11502   EXPECT_EQ("func(a,\n"
11503             "     \"long long long \"\n"
11504             "     \"long\",\n"
11505             "     c);",
11506             format("func(a, \"long long long long\", c);",
11507                    getLLVMStyleWithColumns(24)));
11508   // In a function call with three operands, the third must be broken with a
11509   // line break before it.
11510   EXPECT_EQ("func(a, b,\n"
11511             "     \"long long long \"\n"
11512             "     \"long\");",
11513             format("func(a, b, \"long long long long\");",
11514                    getLLVMStyleWithColumns(24)));
11515   // In a function call with three operands, both the second and the third must
11516   // be broken with a line break before them.
11517   EXPECT_EQ("func(a,\n"
11518             "     \"long long long \"\n"
11519             "     \"long\",\n"
11520             "     \"long long long \"\n"
11521             "     \"long\");",
11522             format("func(a, \"long long long long\", \"long long long long\");",
11523                    getLLVMStyleWithColumns(24)));
11524   // In a chain of << with two operands, the second can be broken with no line
11525   // break before it.
11526   EXPECT_EQ("a << \"line line \"\n"
11527             "     \"line\";",
11528             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
11529   // In a chain of << with three operands, the second can be broken with no line
11530   // break before it.
11531   EXPECT_EQ(
11532       "abcde << \"line \"\n"
11533       "         \"line line\"\n"
11534       "      << c;",
11535       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
11536   // In a chain of << with three operands, the third must be broken with a line
11537   // break before it.
11538   EXPECT_EQ(
11539       "a << b\n"
11540       "  << \"line line \"\n"
11541       "     \"line\";",
11542       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
11543   // In a chain of << with three operands, the second can be broken with no line
11544   // break before it and the third must be broken with a line break before it.
11545   EXPECT_EQ("abcd << \"line line \"\n"
11546             "        \"line\"\n"
11547             "     << \"line line \"\n"
11548             "        \"line\";",
11549             format("abcd << \"line line line\" << \"line line line\";",
11550                    getLLVMStyleWithColumns(20)));
11551   // In a chain of binary operators with two operands, the second can be broken
11552   // with no line break before it.
11553   EXPECT_EQ(
11554       "abcd + \"line line \"\n"
11555       "       \"line line\";",
11556       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
11557   // In a chain of binary operators with three operands, the second must be
11558   // broken with a line break before it.
11559   EXPECT_EQ("abcd +\n"
11560             "    \"line line \"\n"
11561             "    \"line line\" +\n"
11562             "    e;",
11563             format("abcd + \"line line line line\" + e;",
11564                    getLLVMStyleWithColumns(20)));
11565   // In a function call with two operands, with AlignAfterOpenBracket enabled,
11566   // the first must be broken with a line break before it.
11567   FormatStyle Style = getLLVMStyleWithColumns(25);
11568   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
11569   EXPECT_EQ("someFunction(\n"
11570             "    \"long long long \"\n"
11571             "    \"long\",\n"
11572             "    a);",
11573             format("someFunction(\"long long long long\", a);", Style));
11574 }
11575 
11576 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
11577   EXPECT_EQ(
11578       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11579       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11580       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
11581       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11582              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11583              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
11584 }
11585 
11586 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
11587   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
11588             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
11589   EXPECT_EQ("fffffffffff(g(R\"x(\n"
11590             "multiline raw string literal xxxxxxxxxxxxxx\n"
11591             ")x\",\n"
11592             "              a),\n"
11593             "            b);",
11594             format("fffffffffff(g(R\"x(\n"
11595                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11596                    ")x\", a), b);",
11597                    getGoogleStyleWithColumns(20)));
11598   EXPECT_EQ("fffffffffff(\n"
11599             "    g(R\"x(qqq\n"
11600             "multiline raw string literal xxxxxxxxxxxxxx\n"
11601             ")x\",\n"
11602             "      a),\n"
11603             "    b);",
11604             format("fffffffffff(g(R\"x(qqq\n"
11605                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11606                    ")x\", a), b);",
11607                    getGoogleStyleWithColumns(20)));
11608 
11609   EXPECT_EQ("fffffffffff(R\"x(\n"
11610             "multiline raw string literal xxxxxxxxxxxxxx\n"
11611             ")x\");",
11612             format("fffffffffff(R\"x(\n"
11613                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11614                    ")x\");",
11615                    getGoogleStyleWithColumns(20)));
11616   EXPECT_EQ("fffffffffff(R\"x(\n"
11617             "multiline raw string literal xxxxxxxxxxxxxx\n"
11618             ")x\" + bbbbbb);",
11619             format("fffffffffff(R\"x(\n"
11620                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11621                    ")x\" +   bbbbbb);",
11622                    getGoogleStyleWithColumns(20)));
11623   EXPECT_EQ("fffffffffff(\n"
11624             "    R\"x(\n"
11625             "multiline raw string literal xxxxxxxxxxxxxx\n"
11626             ")x\" +\n"
11627             "    bbbbbb);",
11628             format("fffffffffff(\n"
11629                    " R\"x(\n"
11630                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11631                    ")x\" + bbbbbb);",
11632                    getGoogleStyleWithColumns(20)));
11633   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
11634             format("fffffffffff(\n"
11635                    " R\"(single line raw string)\" + bbbbbb);"));
11636 }
11637 
11638 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
11639   verifyFormat("string a = \"unterminated;");
11640   EXPECT_EQ("function(\"unterminated,\n"
11641             "         OtherParameter);",
11642             format("function(  \"unterminated,\n"
11643                    "    OtherParameter);"));
11644 }
11645 
11646 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
11647   FormatStyle Style = getLLVMStyle();
11648   Style.Standard = FormatStyle::LS_Cpp03;
11649   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
11650             format("#define x(_a) printf(\"foo\"_a);", Style));
11651 }
11652 
11653 TEST_F(FormatTest, CppLexVersion) {
11654   FormatStyle Style = getLLVMStyle();
11655   // Formatting of x * y differs if x is a type.
11656   verifyFormat("void foo() { MACRO(a * b); }", Style);
11657   verifyFormat("void foo() { MACRO(int *b); }", Style);
11658 
11659   // LLVM style uses latest lexer.
11660   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
11661   Style.Standard = FormatStyle::LS_Cpp17;
11662   // But in c++17, char8_t isn't a keyword.
11663   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
11664 }
11665 
11666 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
11667 
11668 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
11669   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
11670             "             \"ddeeefff\");",
11671             format("someFunction(\"aaabbbcccdddeeefff\");",
11672                    getLLVMStyleWithColumns(25)));
11673   EXPECT_EQ("someFunction1234567890(\n"
11674             "    \"aaabbbcccdddeeefff\");",
11675             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
11676                    getLLVMStyleWithColumns(26)));
11677   EXPECT_EQ("someFunction1234567890(\n"
11678             "    \"aaabbbcccdddeeeff\"\n"
11679             "    \"f\");",
11680             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
11681                    getLLVMStyleWithColumns(25)));
11682   EXPECT_EQ("someFunction1234567890(\n"
11683             "    \"aaabbbcccdddeeeff\"\n"
11684             "    \"f\");",
11685             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
11686                    getLLVMStyleWithColumns(24)));
11687   EXPECT_EQ("someFunction(\n"
11688             "    \"aaabbbcc ddde \"\n"
11689             "    \"efff\");",
11690             format("someFunction(\"aaabbbcc ddde efff\");",
11691                    getLLVMStyleWithColumns(25)));
11692   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
11693             "             \"ddeeefff\");",
11694             format("someFunction(\"aaabbbccc ddeeefff\");",
11695                    getLLVMStyleWithColumns(25)));
11696   EXPECT_EQ("someFunction1234567890(\n"
11697             "    \"aaabb \"\n"
11698             "    \"cccdddeeefff\");",
11699             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
11700                    getLLVMStyleWithColumns(25)));
11701   EXPECT_EQ("#define A          \\\n"
11702             "  string s =       \\\n"
11703             "      \"123456789\"  \\\n"
11704             "      \"0\";         \\\n"
11705             "  int i;",
11706             format("#define A string s = \"1234567890\"; int i;",
11707                    getLLVMStyleWithColumns(20)));
11708   EXPECT_EQ("someFunction(\n"
11709             "    \"aaabbbcc \"\n"
11710             "    \"dddeeefff\");",
11711             format("someFunction(\"aaabbbcc dddeeefff\");",
11712                    getLLVMStyleWithColumns(25)));
11713 }
11714 
11715 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
11716   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
11717   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
11718   EXPECT_EQ("\"test\"\n"
11719             "\"\\n\"",
11720             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
11721   EXPECT_EQ("\"tes\\\\\"\n"
11722             "\"n\"",
11723             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
11724   EXPECT_EQ("\"\\\\\\\\\"\n"
11725             "\"\\n\"",
11726             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
11727   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
11728   EXPECT_EQ("\"\\uff01\"\n"
11729             "\"test\"",
11730             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
11731   EXPECT_EQ("\"\\Uff01ff02\"",
11732             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
11733   EXPECT_EQ("\"\\x000000000001\"\n"
11734             "\"next\"",
11735             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
11736   EXPECT_EQ("\"\\x000000000001next\"",
11737             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
11738   EXPECT_EQ("\"\\x000000000001\"",
11739             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
11740   EXPECT_EQ("\"test\"\n"
11741             "\"\\000000\"\n"
11742             "\"000001\"",
11743             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
11744   EXPECT_EQ("\"test\\000\"\n"
11745             "\"00000000\"\n"
11746             "\"1\"",
11747             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
11748 }
11749 
11750 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
11751   verifyFormat("void f() {\n"
11752                "  return g() {}\n"
11753                "  void h() {}");
11754   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
11755                "g();\n"
11756                "}");
11757 }
11758 
11759 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
11760   verifyFormat(
11761       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
11762 }
11763 
11764 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
11765   verifyFormat("class X {\n"
11766                "  void f() {\n"
11767                "  }\n"
11768                "};",
11769                getLLVMStyleWithColumns(12));
11770 }
11771 
11772 TEST_F(FormatTest, ConfigurableIndentWidth) {
11773   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
11774   EightIndent.IndentWidth = 8;
11775   EightIndent.ContinuationIndentWidth = 8;
11776   verifyFormat("void f() {\n"
11777                "        someFunction();\n"
11778                "        if (true) {\n"
11779                "                f();\n"
11780                "        }\n"
11781                "}",
11782                EightIndent);
11783   verifyFormat("class X {\n"
11784                "        void f() {\n"
11785                "        }\n"
11786                "};",
11787                EightIndent);
11788   verifyFormat("int x[] = {\n"
11789                "        call(),\n"
11790                "        call()};",
11791                EightIndent);
11792 }
11793 
11794 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
11795   verifyFormat("double\n"
11796                "f();",
11797                getLLVMStyleWithColumns(8));
11798 }
11799 
11800 TEST_F(FormatTest, ConfigurableUseOfTab) {
11801   FormatStyle Tab = getLLVMStyleWithColumns(42);
11802   Tab.IndentWidth = 8;
11803   Tab.UseTab = FormatStyle::UT_Always;
11804   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
11805 
11806   EXPECT_EQ("if (aaaaaaaa && // q\n"
11807             "    bb)\t\t// w\n"
11808             "\t;",
11809             format("if (aaaaaaaa &&// q\n"
11810                    "bb)// w\n"
11811                    ";",
11812                    Tab));
11813   EXPECT_EQ("if (aaa && bbb) // w\n"
11814             "\t;",
11815             format("if(aaa&&bbb)// w\n"
11816                    ";",
11817                    Tab));
11818 
11819   verifyFormat("class X {\n"
11820                "\tvoid f() {\n"
11821                "\t\tsomeFunction(parameter1,\n"
11822                "\t\t\t     parameter2);\n"
11823                "\t}\n"
11824                "};",
11825                Tab);
11826   verifyFormat("#define A                        \\\n"
11827                "\tvoid f() {               \\\n"
11828                "\t\tsomeFunction(    \\\n"
11829                "\t\t    parameter1,  \\\n"
11830                "\t\t    parameter2); \\\n"
11831                "\t}",
11832                Tab);
11833   verifyFormat("int a;\t      // x\n"
11834                "int bbbbbbbb; // x\n",
11835                Tab);
11836 
11837   Tab.TabWidth = 4;
11838   Tab.IndentWidth = 8;
11839   verifyFormat("class TabWidth4Indent8 {\n"
11840                "\t\tvoid f() {\n"
11841                "\t\t\t\tsomeFunction(parameter1,\n"
11842                "\t\t\t\t\t\t\t parameter2);\n"
11843                "\t\t}\n"
11844                "};",
11845                Tab);
11846 
11847   Tab.TabWidth = 4;
11848   Tab.IndentWidth = 4;
11849   verifyFormat("class TabWidth4Indent4 {\n"
11850                "\tvoid f() {\n"
11851                "\t\tsomeFunction(parameter1,\n"
11852                "\t\t\t\t\t parameter2);\n"
11853                "\t}\n"
11854                "};",
11855                Tab);
11856 
11857   Tab.TabWidth = 8;
11858   Tab.IndentWidth = 4;
11859   verifyFormat("class TabWidth8Indent4 {\n"
11860                "    void f() {\n"
11861                "\tsomeFunction(parameter1,\n"
11862                "\t\t     parameter2);\n"
11863                "    }\n"
11864                "};",
11865                Tab);
11866 
11867   Tab.TabWidth = 8;
11868   Tab.IndentWidth = 8;
11869   EXPECT_EQ("/*\n"
11870             "\t      a\t\tcomment\n"
11871             "\t      in multiple lines\n"
11872             "       */",
11873             format("   /*\t \t \n"
11874                    " \t \t a\t\tcomment\t \t\n"
11875                    " \t \t in multiple lines\t\n"
11876                    " \t  */",
11877                    Tab));
11878 
11879   Tab.UseTab = FormatStyle::UT_ForIndentation;
11880   verifyFormat("{\n"
11881                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11882                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11883                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11884                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11885                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11886                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11887                "};",
11888                Tab);
11889   verifyFormat("enum AA {\n"
11890                "\ta1, // Force multiple lines\n"
11891                "\ta2,\n"
11892                "\ta3\n"
11893                "};",
11894                Tab);
11895   EXPECT_EQ("if (aaaaaaaa && // q\n"
11896             "    bb)         // w\n"
11897             "\t;",
11898             format("if (aaaaaaaa &&// q\n"
11899                    "bb)// w\n"
11900                    ";",
11901                    Tab));
11902   verifyFormat("class X {\n"
11903                "\tvoid f() {\n"
11904                "\t\tsomeFunction(parameter1,\n"
11905                "\t\t             parameter2);\n"
11906                "\t}\n"
11907                "};",
11908                Tab);
11909   verifyFormat("{\n"
11910                "\tQ(\n"
11911                "\t    {\n"
11912                "\t\t    int a;\n"
11913                "\t\t    someFunction(aaaaaaaa,\n"
11914                "\t\t                 bbbbbbb);\n"
11915                "\t    },\n"
11916                "\t    p);\n"
11917                "}",
11918                Tab);
11919   EXPECT_EQ("{\n"
11920             "\t/* aaaa\n"
11921             "\t   bbbb */\n"
11922             "}",
11923             format("{\n"
11924                    "/* aaaa\n"
11925                    "   bbbb */\n"
11926                    "}",
11927                    Tab));
11928   EXPECT_EQ("{\n"
11929             "\t/*\n"
11930             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11931             "\t  bbbbbbbbbbbbb\n"
11932             "\t*/\n"
11933             "}",
11934             format("{\n"
11935                    "/*\n"
11936                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11937                    "*/\n"
11938                    "}",
11939                    Tab));
11940   EXPECT_EQ("{\n"
11941             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11942             "\t// bbbbbbbbbbbbb\n"
11943             "}",
11944             format("{\n"
11945                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11946                    "}",
11947                    Tab));
11948   EXPECT_EQ("{\n"
11949             "\t/*\n"
11950             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11951             "\t  bbbbbbbbbbbbb\n"
11952             "\t*/\n"
11953             "}",
11954             format("{\n"
11955                    "\t/*\n"
11956                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11957                    "\t*/\n"
11958                    "}",
11959                    Tab));
11960   EXPECT_EQ("{\n"
11961             "\t/*\n"
11962             "\n"
11963             "\t*/\n"
11964             "}",
11965             format("{\n"
11966                    "\t/*\n"
11967                    "\n"
11968                    "\t*/\n"
11969                    "}",
11970                    Tab));
11971   EXPECT_EQ("{\n"
11972             "\t/*\n"
11973             " asdf\n"
11974             "\t*/\n"
11975             "}",
11976             format("{\n"
11977                    "\t/*\n"
11978                    " asdf\n"
11979                    "\t*/\n"
11980                    "}",
11981                    Tab));
11982 
11983   Tab.UseTab = FormatStyle::UT_Never;
11984   EXPECT_EQ("/*\n"
11985             "              a\t\tcomment\n"
11986             "              in multiple lines\n"
11987             "       */",
11988             format("   /*\t \t \n"
11989                    " \t \t a\t\tcomment\t \t\n"
11990                    " \t \t in multiple lines\t\n"
11991                    " \t  */",
11992                    Tab));
11993   EXPECT_EQ("/* some\n"
11994             "   comment */",
11995             format(" \t \t /* some\n"
11996                    " \t \t    comment */",
11997                    Tab));
11998   EXPECT_EQ("int a; /* some\n"
11999             "   comment */",
12000             format(" \t \t int a; /* some\n"
12001                    " \t \t    comment */",
12002                    Tab));
12003 
12004   EXPECT_EQ("int a; /* some\n"
12005             "comment */",
12006             format(" \t \t int\ta; /* some\n"
12007                    " \t \t    comment */",
12008                    Tab));
12009   EXPECT_EQ("f(\"\t\t\"); /* some\n"
12010             "    comment */",
12011             format(" \t \t f(\"\t\t\"); /* some\n"
12012                    " \t \t    comment */",
12013                    Tab));
12014   EXPECT_EQ("{\n"
12015             "        /*\n"
12016             "         * Comment\n"
12017             "         */\n"
12018             "        int i;\n"
12019             "}",
12020             format("{\n"
12021                    "\t/*\n"
12022                    "\t * Comment\n"
12023                    "\t */\n"
12024                    "\t int i;\n"
12025                    "}",
12026                    Tab));
12027 
12028   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
12029   Tab.TabWidth = 8;
12030   Tab.IndentWidth = 8;
12031   EXPECT_EQ("if (aaaaaaaa && // q\n"
12032             "    bb)         // w\n"
12033             "\t;",
12034             format("if (aaaaaaaa &&// q\n"
12035                    "bb)// w\n"
12036                    ";",
12037                    Tab));
12038   EXPECT_EQ("if (aaa && bbb) // w\n"
12039             "\t;",
12040             format("if(aaa&&bbb)// w\n"
12041                    ";",
12042                    Tab));
12043   verifyFormat("class X {\n"
12044                "\tvoid f() {\n"
12045                "\t\tsomeFunction(parameter1,\n"
12046                "\t\t\t     parameter2);\n"
12047                "\t}\n"
12048                "};",
12049                Tab);
12050   verifyFormat("#define A                        \\\n"
12051                "\tvoid f() {               \\\n"
12052                "\t\tsomeFunction(    \\\n"
12053                "\t\t    parameter1,  \\\n"
12054                "\t\t    parameter2); \\\n"
12055                "\t}",
12056                Tab);
12057   Tab.TabWidth = 4;
12058   Tab.IndentWidth = 8;
12059   verifyFormat("class TabWidth4Indent8 {\n"
12060                "\t\tvoid f() {\n"
12061                "\t\t\t\tsomeFunction(parameter1,\n"
12062                "\t\t\t\t\t\t\t parameter2);\n"
12063                "\t\t}\n"
12064                "};",
12065                Tab);
12066   Tab.TabWidth = 4;
12067   Tab.IndentWidth = 4;
12068   verifyFormat("class TabWidth4Indent4 {\n"
12069                "\tvoid f() {\n"
12070                "\t\tsomeFunction(parameter1,\n"
12071                "\t\t\t\t\t parameter2);\n"
12072                "\t}\n"
12073                "};",
12074                Tab);
12075   Tab.TabWidth = 8;
12076   Tab.IndentWidth = 4;
12077   verifyFormat("class TabWidth8Indent4 {\n"
12078                "    void f() {\n"
12079                "\tsomeFunction(parameter1,\n"
12080                "\t\t     parameter2);\n"
12081                "    }\n"
12082                "};",
12083                Tab);
12084   Tab.TabWidth = 8;
12085   Tab.IndentWidth = 8;
12086   EXPECT_EQ("/*\n"
12087             "\t      a\t\tcomment\n"
12088             "\t      in multiple lines\n"
12089             "       */",
12090             format("   /*\t \t \n"
12091                    " \t \t a\t\tcomment\t \t\n"
12092                    " \t \t in multiple lines\t\n"
12093                    " \t  */",
12094                    Tab));
12095   verifyFormat("{\n"
12096                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12097                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12098                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12099                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12100                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12101                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12102                "};",
12103                Tab);
12104   verifyFormat("enum AA {\n"
12105                "\ta1, // Force multiple lines\n"
12106                "\ta2,\n"
12107                "\ta3\n"
12108                "};",
12109                Tab);
12110   EXPECT_EQ("if (aaaaaaaa && // q\n"
12111             "    bb)         // w\n"
12112             "\t;",
12113             format("if (aaaaaaaa &&// q\n"
12114                    "bb)// w\n"
12115                    ";",
12116                    Tab));
12117   verifyFormat("class X {\n"
12118                "\tvoid f() {\n"
12119                "\t\tsomeFunction(parameter1,\n"
12120                "\t\t\t     parameter2);\n"
12121                "\t}\n"
12122                "};",
12123                Tab);
12124   verifyFormat("{\n"
12125                "\tQ(\n"
12126                "\t    {\n"
12127                "\t\t    int a;\n"
12128                "\t\t    someFunction(aaaaaaaa,\n"
12129                "\t\t\t\t bbbbbbb);\n"
12130                "\t    },\n"
12131                "\t    p);\n"
12132                "}",
12133                Tab);
12134   EXPECT_EQ("{\n"
12135             "\t/* aaaa\n"
12136             "\t   bbbb */\n"
12137             "}",
12138             format("{\n"
12139                    "/* aaaa\n"
12140                    "   bbbb */\n"
12141                    "}",
12142                    Tab));
12143   EXPECT_EQ("{\n"
12144             "\t/*\n"
12145             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12146             "\t  bbbbbbbbbbbbb\n"
12147             "\t*/\n"
12148             "}",
12149             format("{\n"
12150                    "/*\n"
12151                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12152                    "*/\n"
12153                    "}",
12154                    Tab));
12155   EXPECT_EQ("{\n"
12156             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12157             "\t// bbbbbbbbbbbbb\n"
12158             "}",
12159             format("{\n"
12160                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12161                    "}",
12162                    Tab));
12163   EXPECT_EQ("{\n"
12164             "\t/*\n"
12165             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12166             "\t  bbbbbbbbbbbbb\n"
12167             "\t*/\n"
12168             "}",
12169             format("{\n"
12170                    "\t/*\n"
12171                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12172                    "\t*/\n"
12173                    "}",
12174                    Tab));
12175   EXPECT_EQ("{\n"
12176             "\t/*\n"
12177             "\n"
12178             "\t*/\n"
12179             "}",
12180             format("{\n"
12181                    "\t/*\n"
12182                    "\n"
12183                    "\t*/\n"
12184                    "}",
12185                    Tab));
12186   EXPECT_EQ("{\n"
12187             "\t/*\n"
12188             " asdf\n"
12189             "\t*/\n"
12190             "}",
12191             format("{\n"
12192                    "\t/*\n"
12193                    " asdf\n"
12194                    "\t*/\n"
12195                    "}",
12196                    Tab));
12197   EXPECT_EQ("/* some\n"
12198             "   comment */",
12199             format(" \t \t /* some\n"
12200                    " \t \t    comment */",
12201                    Tab));
12202   EXPECT_EQ("int a; /* some\n"
12203             "   comment */",
12204             format(" \t \t int a; /* some\n"
12205                    " \t \t    comment */",
12206                    Tab));
12207   EXPECT_EQ("int a; /* some\n"
12208             "comment */",
12209             format(" \t \t int\ta; /* some\n"
12210                    " \t \t    comment */",
12211                    Tab));
12212   EXPECT_EQ("f(\"\t\t\"); /* some\n"
12213             "    comment */",
12214             format(" \t \t f(\"\t\t\"); /* some\n"
12215                    " \t \t    comment */",
12216                    Tab));
12217   EXPECT_EQ("{\n"
12218             "\t/*\n"
12219             "\t * Comment\n"
12220             "\t */\n"
12221             "\tint i;\n"
12222             "}",
12223             format("{\n"
12224                    "\t/*\n"
12225                    "\t * Comment\n"
12226                    "\t */\n"
12227                    "\t int i;\n"
12228                    "}",
12229                    Tab));
12230   Tab.TabWidth = 2;
12231   Tab.IndentWidth = 2;
12232   EXPECT_EQ("{\n"
12233             "\t/* aaaa\n"
12234             "\t\t bbbb */\n"
12235             "}",
12236             format("{\n"
12237                    "/* aaaa\n"
12238                    "\t bbbb */\n"
12239                    "}",
12240                    Tab));
12241   EXPECT_EQ("{\n"
12242             "\t/*\n"
12243             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12244             "\t\tbbbbbbbbbbbbb\n"
12245             "\t*/\n"
12246             "}",
12247             format("{\n"
12248                    "/*\n"
12249                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12250                    "*/\n"
12251                    "}",
12252                    Tab));
12253   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
12254   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
12255   Tab.TabWidth = 4;
12256   Tab.IndentWidth = 4;
12257   verifyFormat("class Assign {\n"
12258                "\tvoid f() {\n"
12259                "\t\tint         x      = 123;\n"
12260                "\t\tint         random = 4;\n"
12261                "\t\tstd::string alphabet =\n"
12262                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
12263                "\t}\n"
12264                "};",
12265                Tab);
12266 
12267   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
12268   Tab.TabWidth = 8;
12269   Tab.IndentWidth = 8;
12270   EXPECT_EQ("if (aaaaaaaa && // q\n"
12271             "    bb)         // w\n"
12272             "\t;",
12273             format("if (aaaaaaaa &&// q\n"
12274                    "bb)// w\n"
12275                    ";",
12276                    Tab));
12277   EXPECT_EQ("if (aaa && bbb) // w\n"
12278             "\t;",
12279             format("if(aaa&&bbb)// w\n"
12280                    ";",
12281                    Tab));
12282   verifyFormat("class X {\n"
12283                "\tvoid f() {\n"
12284                "\t\tsomeFunction(parameter1,\n"
12285                "\t\t             parameter2);\n"
12286                "\t}\n"
12287                "};",
12288                Tab);
12289   verifyFormat("#define A                        \\\n"
12290                "\tvoid f() {               \\\n"
12291                "\t\tsomeFunction(    \\\n"
12292                "\t\t    parameter1,  \\\n"
12293                "\t\t    parameter2); \\\n"
12294                "\t}",
12295                Tab);
12296   Tab.TabWidth = 4;
12297   Tab.IndentWidth = 8;
12298   verifyFormat("class TabWidth4Indent8 {\n"
12299                "\t\tvoid f() {\n"
12300                "\t\t\t\tsomeFunction(parameter1,\n"
12301                "\t\t\t\t             parameter2);\n"
12302                "\t\t}\n"
12303                "};",
12304                Tab);
12305   Tab.TabWidth = 4;
12306   Tab.IndentWidth = 4;
12307   verifyFormat("class TabWidth4Indent4 {\n"
12308                "\tvoid f() {\n"
12309                "\t\tsomeFunction(parameter1,\n"
12310                "\t\t             parameter2);\n"
12311                "\t}\n"
12312                "};",
12313                Tab);
12314   Tab.TabWidth = 8;
12315   Tab.IndentWidth = 4;
12316   verifyFormat("class TabWidth8Indent4 {\n"
12317                "    void f() {\n"
12318                "\tsomeFunction(parameter1,\n"
12319                "\t             parameter2);\n"
12320                "    }\n"
12321                "};",
12322                Tab);
12323   Tab.TabWidth = 8;
12324   Tab.IndentWidth = 8;
12325   EXPECT_EQ("/*\n"
12326             "              a\t\tcomment\n"
12327             "              in multiple lines\n"
12328             "       */",
12329             format("   /*\t \t \n"
12330                    " \t \t a\t\tcomment\t \t\n"
12331                    " \t \t in multiple lines\t\n"
12332                    " \t  */",
12333                    Tab));
12334   verifyFormat("{\n"
12335                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12336                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12337                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12338                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12339                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12340                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12341                "};",
12342                Tab);
12343   verifyFormat("enum AA {\n"
12344                "\ta1, // Force multiple lines\n"
12345                "\ta2,\n"
12346                "\ta3\n"
12347                "};",
12348                Tab);
12349   EXPECT_EQ("if (aaaaaaaa && // q\n"
12350             "    bb)         // w\n"
12351             "\t;",
12352             format("if (aaaaaaaa &&// q\n"
12353                    "bb)// w\n"
12354                    ";",
12355                    Tab));
12356   verifyFormat("class X {\n"
12357                "\tvoid f() {\n"
12358                "\t\tsomeFunction(parameter1,\n"
12359                "\t\t             parameter2);\n"
12360                "\t}\n"
12361                "};",
12362                Tab);
12363   verifyFormat("{\n"
12364                "\tQ(\n"
12365                "\t    {\n"
12366                "\t\t    int a;\n"
12367                "\t\t    someFunction(aaaaaaaa,\n"
12368                "\t\t                 bbbbbbb);\n"
12369                "\t    },\n"
12370                "\t    p);\n"
12371                "}",
12372                Tab);
12373   EXPECT_EQ("{\n"
12374             "\t/* aaaa\n"
12375             "\t   bbbb */\n"
12376             "}",
12377             format("{\n"
12378                    "/* aaaa\n"
12379                    "   bbbb */\n"
12380                    "}",
12381                    Tab));
12382   EXPECT_EQ("{\n"
12383             "\t/*\n"
12384             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12385             "\t  bbbbbbbbbbbbb\n"
12386             "\t*/\n"
12387             "}",
12388             format("{\n"
12389                    "/*\n"
12390                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12391                    "*/\n"
12392                    "}",
12393                    Tab));
12394   EXPECT_EQ("{\n"
12395             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12396             "\t// bbbbbbbbbbbbb\n"
12397             "}",
12398             format("{\n"
12399                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12400                    "}",
12401                    Tab));
12402   EXPECT_EQ("{\n"
12403             "\t/*\n"
12404             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12405             "\t  bbbbbbbbbbbbb\n"
12406             "\t*/\n"
12407             "}",
12408             format("{\n"
12409                    "\t/*\n"
12410                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12411                    "\t*/\n"
12412                    "}",
12413                    Tab));
12414   EXPECT_EQ("{\n"
12415             "\t/*\n"
12416             "\n"
12417             "\t*/\n"
12418             "}",
12419             format("{\n"
12420                    "\t/*\n"
12421                    "\n"
12422                    "\t*/\n"
12423                    "}",
12424                    Tab));
12425   EXPECT_EQ("{\n"
12426             "\t/*\n"
12427             " asdf\n"
12428             "\t*/\n"
12429             "}",
12430             format("{\n"
12431                    "\t/*\n"
12432                    " asdf\n"
12433                    "\t*/\n"
12434                    "}",
12435                    Tab));
12436   EXPECT_EQ("/* some\n"
12437             "   comment */",
12438             format(" \t \t /* some\n"
12439                    " \t \t    comment */",
12440                    Tab));
12441   EXPECT_EQ("int a; /* some\n"
12442             "   comment */",
12443             format(" \t \t int a; /* some\n"
12444                    " \t \t    comment */",
12445                    Tab));
12446   EXPECT_EQ("int a; /* some\n"
12447             "comment */",
12448             format(" \t \t int\ta; /* some\n"
12449                    " \t \t    comment */",
12450                    Tab));
12451   EXPECT_EQ("f(\"\t\t\"); /* some\n"
12452             "    comment */",
12453             format(" \t \t f(\"\t\t\"); /* some\n"
12454                    " \t \t    comment */",
12455                    Tab));
12456   EXPECT_EQ("{\n"
12457             "\t/*\n"
12458             "\t * Comment\n"
12459             "\t */\n"
12460             "\tint i;\n"
12461             "}",
12462             format("{\n"
12463                    "\t/*\n"
12464                    "\t * Comment\n"
12465                    "\t */\n"
12466                    "\t int i;\n"
12467                    "}",
12468                    Tab));
12469   Tab.TabWidth = 2;
12470   Tab.IndentWidth = 2;
12471   EXPECT_EQ("{\n"
12472             "\t/* aaaa\n"
12473             "\t   bbbb */\n"
12474             "}",
12475             format("{\n"
12476                    "/* aaaa\n"
12477                    "   bbbb */\n"
12478                    "}",
12479                    Tab));
12480   EXPECT_EQ("{\n"
12481             "\t/*\n"
12482             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12483             "\t  bbbbbbbbbbbbb\n"
12484             "\t*/\n"
12485             "}",
12486             format("{\n"
12487                    "/*\n"
12488                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12489                    "*/\n"
12490                    "}",
12491                    Tab));
12492   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
12493   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
12494   Tab.TabWidth = 4;
12495   Tab.IndentWidth = 4;
12496   verifyFormat("class Assign {\n"
12497                "\tvoid f() {\n"
12498                "\t\tint         x      = 123;\n"
12499                "\t\tint         random = 4;\n"
12500                "\t\tstd::string alphabet =\n"
12501                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
12502                "\t}\n"
12503                "};",
12504                Tab);
12505   Tab.AlignOperands = FormatStyle::OAS_Align;
12506   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
12507                "                 cccccccccccccccccccc;",
12508                Tab);
12509   // no alignment
12510   verifyFormat("int aaaaaaaaaa =\n"
12511                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
12512                Tab);
12513   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
12514                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
12515                "                        : 333333333333333;",
12516                Tab);
12517   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
12518   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
12519   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
12520                "               + cccccccccccccccccccc;",
12521                Tab);
12522 }
12523 
12524 TEST_F(FormatTest, ZeroTabWidth) {
12525   FormatStyle Tab = getLLVMStyleWithColumns(42);
12526   Tab.IndentWidth = 8;
12527   Tab.UseTab = FormatStyle::UT_Never;
12528   Tab.TabWidth = 0;
12529   EXPECT_EQ("void a(){\n"
12530             "    // line starts with '\t'\n"
12531             "};",
12532             format("void a(){\n"
12533                    "\t// line starts with '\t'\n"
12534                    "};",
12535                    Tab));
12536 
12537   EXPECT_EQ("void a(){\n"
12538             "    // line starts with '\t'\n"
12539             "};",
12540             format("void a(){\n"
12541                    "\t\t// line starts with '\t'\n"
12542                    "};",
12543                    Tab));
12544 
12545   Tab.UseTab = FormatStyle::UT_ForIndentation;
12546   EXPECT_EQ("void a(){\n"
12547             "    // line starts with '\t'\n"
12548             "};",
12549             format("void a(){\n"
12550                    "\t// line starts with '\t'\n"
12551                    "};",
12552                    Tab));
12553 
12554   EXPECT_EQ("void a(){\n"
12555             "    // line starts with '\t'\n"
12556             "};",
12557             format("void a(){\n"
12558                    "\t\t// line starts with '\t'\n"
12559                    "};",
12560                    Tab));
12561 
12562   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
12563   EXPECT_EQ("void a(){\n"
12564             "    // line starts with '\t'\n"
12565             "};",
12566             format("void a(){\n"
12567                    "\t// line starts with '\t'\n"
12568                    "};",
12569                    Tab));
12570 
12571   EXPECT_EQ("void a(){\n"
12572             "    // line starts with '\t'\n"
12573             "};",
12574             format("void a(){\n"
12575                    "\t\t// line starts with '\t'\n"
12576                    "};",
12577                    Tab));
12578 
12579   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
12580   EXPECT_EQ("void a(){\n"
12581             "    // line starts with '\t'\n"
12582             "};",
12583             format("void a(){\n"
12584                    "\t// line starts with '\t'\n"
12585                    "};",
12586                    Tab));
12587 
12588   EXPECT_EQ("void a(){\n"
12589             "    // line starts with '\t'\n"
12590             "};",
12591             format("void a(){\n"
12592                    "\t\t// line starts with '\t'\n"
12593                    "};",
12594                    Tab));
12595 
12596   Tab.UseTab = FormatStyle::UT_Always;
12597   EXPECT_EQ("void a(){\n"
12598             "// line starts with '\t'\n"
12599             "};",
12600             format("void a(){\n"
12601                    "\t// line starts with '\t'\n"
12602                    "};",
12603                    Tab));
12604 
12605   EXPECT_EQ("void a(){\n"
12606             "// line starts with '\t'\n"
12607             "};",
12608             format("void a(){\n"
12609                    "\t\t// line starts with '\t'\n"
12610                    "};",
12611                    Tab));
12612 }
12613 
12614 TEST_F(FormatTest, CalculatesOriginalColumn) {
12615   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12616             "q\"; /* some\n"
12617             "       comment */",
12618             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12619                    "q\"; /* some\n"
12620                    "       comment */",
12621                    getLLVMStyle()));
12622   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
12623             "/* some\n"
12624             "   comment */",
12625             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
12626                    " /* some\n"
12627                    "    comment */",
12628                    getLLVMStyle()));
12629   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12630             "qqq\n"
12631             "/* some\n"
12632             "   comment */",
12633             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12634                    "qqq\n"
12635                    " /* some\n"
12636                    "    comment */",
12637                    getLLVMStyle()));
12638   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12639             "wwww; /* some\n"
12640             "         comment */",
12641             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12642                    "wwww; /* some\n"
12643                    "         comment */",
12644                    getLLVMStyle()));
12645 }
12646 
12647 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
12648   FormatStyle NoSpace = getLLVMStyle();
12649   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
12650 
12651   verifyFormat("while(true)\n"
12652                "  continue;",
12653                NoSpace);
12654   verifyFormat("for(;;)\n"
12655                "  continue;",
12656                NoSpace);
12657   verifyFormat("if(true)\n"
12658                "  f();\n"
12659                "else if(true)\n"
12660                "  f();",
12661                NoSpace);
12662   verifyFormat("do {\n"
12663                "  do_something();\n"
12664                "} while(something());",
12665                NoSpace);
12666   verifyFormat("switch(x) {\n"
12667                "default:\n"
12668                "  break;\n"
12669                "}",
12670                NoSpace);
12671   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
12672   verifyFormat("size_t x = sizeof(x);", NoSpace);
12673   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
12674   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
12675   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
12676   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
12677   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
12678   verifyFormat("alignas(128) char a[128];", NoSpace);
12679   verifyFormat("size_t x = alignof(MyType);", NoSpace);
12680   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
12681   verifyFormat("int f() throw(Deprecated);", NoSpace);
12682   verifyFormat("typedef void (*cb)(int);", NoSpace);
12683   verifyFormat("T A::operator()();", NoSpace);
12684   verifyFormat("X A::operator++(T);", NoSpace);
12685   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
12686 
12687   FormatStyle Space = getLLVMStyle();
12688   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
12689 
12690   verifyFormat("int f ();", Space);
12691   verifyFormat("void f (int a, T b) {\n"
12692                "  while (true)\n"
12693                "    continue;\n"
12694                "}",
12695                Space);
12696   verifyFormat("if (true)\n"
12697                "  f ();\n"
12698                "else if (true)\n"
12699                "  f ();",
12700                Space);
12701   verifyFormat("do {\n"
12702                "  do_something ();\n"
12703                "} while (something ());",
12704                Space);
12705   verifyFormat("switch (x) {\n"
12706                "default:\n"
12707                "  break;\n"
12708                "}",
12709                Space);
12710   verifyFormat("A::A () : a (1) {}", Space);
12711   verifyFormat("void f () __attribute__ ((asdf));", Space);
12712   verifyFormat("*(&a + 1);\n"
12713                "&((&a)[1]);\n"
12714                "a[(b + c) * d];\n"
12715                "(((a + 1) * 2) + 3) * 4;",
12716                Space);
12717   verifyFormat("#define A(x) x", Space);
12718   verifyFormat("#define A (x) x", Space);
12719   verifyFormat("#if defined(x)\n"
12720                "#endif",
12721                Space);
12722   verifyFormat("auto i = std::make_unique<int> (5);", Space);
12723   verifyFormat("size_t x = sizeof (x);", Space);
12724   verifyFormat("auto f (int x) -> decltype (x);", Space);
12725   verifyFormat("auto f (int x) -> typeof (x);", Space);
12726   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
12727   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
12728   verifyFormat("int f (T x) noexcept (x.create ());", Space);
12729   verifyFormat("alignas (128) char a[128];", Space);
12730   verifyFormat("size_t x = alignof (MyType);", Space);
12731   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
12732   verifyFormat("int f () throw (Deprecated);", Space);
12733   verifyFormat("typedef void (*cb) (int);", Space);
12734   verifyFormat("T A::operator() ();", Space);
12735   verifyFormat("X A::operator++ (T);", Space);
12736   verifyFormat("auto lambda = [] () { return 0; };", Space);
12737   verifyFormat("int x = int (y);", Space);
12738 
12739   FormatStyle SomeSpace = getLLVMStyle();
12740   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
12741 
12742   verifyFormat("[]() -> float {}", SomeSpace);
12743   verifyFormat("[] (auto foo) {}", SomeSpace);
12744   verifyFormat("[foo]() -> int {}", SomeSpace);
12745   verifyFormat("int f();", SomeSpace);
12746   verifyFormat("void f (int a, T b) {\n"
12747                "  while (true)\n"
12748                "    continue;\n"
12749                "}",
12750                SomeSpace);
12751   verifyFormat("if (true)\n"
12752                "  f();\n"
12753                "else if (true)\n"
12754                "  f();",
12755                SomeSpace);
12756   verifyFormat("do {\n"
12757                "  do_something();\n"
12758                "} while (something());",
12759                SomeSpace);
12760   verifyFormat("switch (x) {\n"
12761                "default:\n"
12762                "  break;\n"
12763                "}",
12764                SomeSpace);
12765   verifyFormat("A::A() : a (1) {}", SomeSpace);
12766   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
12767   verifyFormat("*(&a + 1);\n"
12768                "&((&a)[1]);\n"
12769                "a[(b + c) * d];\n"
12770                "(((a + 1) * 2) + 3) * 4;",
12771                SomeSpace);
12772   verifyFormat("#define A(x) x", SomeSpace);
12773   verifyFormat("#define A (x) x", SomeSpace);
12774   verifyFormat("#if defined(x)\n"
12775                "#endif",
12776                SomeSpace);
12777   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
12778   verifyFormat("size_t x = sizeof (x);", SomeSpace);
12779   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
12780   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
12781   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
12782   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
12783   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
12784   verifyFormat("alignas (128) char a[128];", SomeSpace);
12785   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
12786   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
12787                SomeSpace);
12788   verifyFormat("int f() throw (Deprecated);", SomeSpace);
12789   verifyFormat("typedef void (*cb) (int);", SomeSpace);
12790   verifyFormat("T A::operator()();", SomeSpace);
12791   verifyFormat("X A::operator++ (T);", SomeSpace);
12792   verifyFormat("int x = int (y);", SomeSpace);
12793   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
12794 }
12795 
12796 TEST_F(FormatTest, SpaceAfterLogicalNot) {
12797   FormatStyle Spaces = getLLVMStyle();
12798   Spaces.SpaceAfterLogicalNot = true;
12799 
12800   verifyFormat("bool x = ! y", Spaces);
12801   verifyFormat("if (! isFailure())", Spaces);
12802   verifyFormat("if (! (a && b))", Spaces);
12803   verifyFormat("\"Error!\"", Spaces);
12804   verifyFormat("! ! x", Spaces);
12805 }
12806 
12807 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
12808   FormatStyle Spaces = getLLVMStyle();
12809 
12810   Spaces.SpacesInParentheses = true;
12811   verifyFormat("do_something( ::globalVar );", Spaces);
12812   verifyFormat("call( x, y, z );", Spaces);
12813   verifyFormat("call();", Spaces);
12814   verifyFormat("std::function<void( int, int )> callback;", Spaces);
12815   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
12816                Spaces);
12817   verifyFormat("while ( (bool)1 )\n"
12818                "  continue;",
12819                Spaces);
12820   verifyFormat("for ( ;; )\n"
12821                "  continue;",
12822                Spaces);
12823   verifyFormat("if ( true )\n"
12824                "  f();\n"
12825                "else if ( true )\n"
12826                "  f();",
12827                Spaces);
12828   verifyFormat("do {\n"
12829                "  do_something( (int)i );\n"
12830                "} while ( something() );",
12831                Spaces);
12832   verifyFormat("switch ( x ) {\n"
12833                "default:\n"
12834                "  break;\n"
12835                "}",
12836                Spaces);
12837 
12838   Spaces.SpacesInParentheses = false;
12839   Spaces.SpacesInCStyleCastParentheses = true;
12840   verifyFormat("Type *A = ( Type * )P;", Spaces);
12841   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
12842   verifyFormat("x = ( int32 )y;", Spaces);
12843   verifyFormat("int a = ( int )(2.0f);", Spaces);
12844   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
12845   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
12846   verifyFormat("#define x (( int )-1)", Spaces);
12847 
12848   // Run the first set of tests again with:
12849   Spaces.SpacesInParentheses = false;
12850   Spaces.SpaceInEmptyParentheses = true;
12851   Spaces.SpacesInCStyleCastParentheses = true;
12852   verifyFormat("call(x, y, z);", Spaces);
12853   verifyFormat("call( );", Spaces);
12854   verifyFormat("std::function<void(int, int)> callback;", Spaces);
12855   verifyFormat("while (( bool )1)\n"
12856                "  continue;",
12857                Spaces);
12858   verifyFormat("for (;;)\n"
12859                "  continue;",
12860                Spaces);
12861   verifyFormat("if (true)\n"
12862                "  f( );\n"
12863                "else if (true)\n"
12864                "  f( );",
12865                Spaces);
12866   verifyFormat("do {\n"
12867                "  do_something(( int )i);\n"
12868                "} while (something( ));",
12869                Spaces);
12870   verifyFormat("switch (x) {\n"
12871                "default:\n"
12872                "  break;\n"
12873                "}",
12874                Spaces);
12875 
12876   // Run the first set of tests again with:
12877   Spaces.SpaceAfterCStyleCast = true;
12878   verifyFormat("call(x, y, z);", Spaces);
12879   verifyFormat("call( );", Spaces);
12880   verifyFormat("std::function<void(int, int)> callback;", Spaces);
12881   verifyFormat("while (( bool ) 1)\n"
12882                "  continue;",
12883                Spaces);
12884   verifyFormat("for (;;)\n"
12885                "  continue;",
12886                Spaces);
12887   verifyFormat("if (true)\n"
12888                "  f( );\n"
12889                "else if (true)\n"
12890                "  f( );",
12891                Spaces);
12892   verifyFormat("do {\n"
12893                "  do_something(( int ) i);\n"
12894                "} while (something( ));",
12895                Spaces);
12896   verifyFormat("switch (x) {\n"
12897                "default:\n"
12898                "  break;\n"
12899                "}",
12900                Spaces);
12901 
12902   // Run subset of tests again with:
12903   Spaces.SpacesInCStyleCastParentheses = false;
12904   Spaces.SpaceAfterCStyleCast = true;
12905   verifyFormat("while ((bool) 1)\n"
12906                "  continue;",
12907                Spaces);
12908   verifyFormat("do {\n"
12909                "  do_something((int) i);\n"
12910                "} while (something( ));",
12911                Spaces);
12912 
12913   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
12914   verifyFormat("size_t idx = (size_t) a;", Spaces);
12915   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
12916   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
12917   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
12918   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
12919   Spaces.SpaceAfterCStyleCast = false;
12920   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
12921   verifyFormat("size_t idx = (size_t)a;", Spaces);
12922   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
12923   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
12924   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
12925   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
12926 }
12927 
12928 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
12929   verifyFormat("int a[5];");
12930   verifyFormat("a[3] += 42;");
12931 
12932   FormatStyle Spaces = getLLVMStyle();
12933   Spaces.SpacesInSquareBrackets = true;
12934   // Not lambdas.
12935   verifyFormat("int a[ 5 ];", Spaces);
12936   verifyFormat("a[ 3 ] += 42;", Spaces);
12937   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
12938   verifyFormat("double &operator[](int i) { return 0; }\n"
12939                "int i;",
12940                Spaces);
12941   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
12942   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
12943   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
12944   // Lambdas.
12945   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
12946   verifyFormat("return [ i, args... ] {};", Spaces);
12947   verifyFormat("int foo = [ &bar ]() {};", Spaces);
12948   verifyFormat("int foo = [ = ]() {};", Spaces);
12949   verifyFormat("int foo = [ & ]() {};", Spaces);
12950   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
12951   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
12952 }
12953 
12954 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
12955   FormatStyle NoSpaceStyle = getLLVMStyle();
12956   verifyFormat("int a[5];", NoSpaceStyle);
12957   verifyFormat("a[3] += 42;", NoSpaceStyle);
12958 
12959   verifyFormat("int a[1];", NoSpaceStyle);
12960   verifyFormat("int 1 [a];", NoSpaceStyle);
12961   verifyFormat("int a[1][2];", NoSpaceStyle);
12962   verifyFormat("a[7] = 5;", NoSpaceStyle);
12963   verifyFormat("int a = (f())[23];", NoSpaceStyle);
12964   verifyFormat("f([] {})", NoSpaceStyle);
12965 
12966   FormatStyle Space = getLLVMStyle();
12967   Space.SpaceBeforeSquareBrackets = true;
12968   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
12969   verifyFormat("return [i, args...] {};", Space);
12970 
12971   verifyFormat("int a [5];", Space);
12972   verifyFormat("a [3] += 42;", Space);
12973   verifyFormat("constexpr char hello []{\"hello\"};", Space);
12974   verifyFormat("double &operator[](int i) { return 0; }\n"
12975                "int i;",
12976                Space);
12977   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
12978   verifyFormat("int i = a [a][a]->f();", Space);
12979   verifyFormat("int i = (*b) [a]->f();", Space);
12980 
12981   verifyFormat("int a [1];", Space);
12982   verifyFormat("int 1 [a];", Space);
12983   verifyFormat("int a [1][2];", Space);
12984   verifyFormat("a [7] = 5;", Space);
12985   verifyFormat("int a = (f()) [23];", Space);
12986   verifyFormat("f([] {})", Space);
12987 }
12988 
12989 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
12990   verifyFormat("int a = 5;");
12991   verifyFormat("a += 42;");
12992   verifyFormat("a or_eq 8;");
12993 
12994   FormatStyle Spaces = getLLVMStyle();
12995   Spaces.SpaceBeforeAssignmentOperators = false;
12996   verifyFormat("int a= 5;", Spaces);
12997   verifyFormat("a+= 42;", Spaces);
12998   verifyFormat("a or_eq 8;", Spaces);
12999 }
13000 
13001 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
13002   verifyFormat("class Foo : public Bar {};");
13003   verifyFormat("Foo::Foo() : foo(1) {}");
13004   verifyFormat("for (auto a : b) {\n}");
13005   verifyFormat("int x = a ? b : c;");
13006   verifyFormat("{\n"
13007                "label0:\n"
13008                "  int x = 0;\n"
13009                "}");
13010   verifyFormat("switch (x) {\n"
13011                "case 1:\n"
13012                "default:\n"
13013                "}");
13014   verifyFormat("switch (allBraces) {\n"
13015                "case 1: {\n"
13016                "  break;\n"
13017                "}\n"
13018                "case 2: {\n"
13019                "  [[fallthrough]];\n"
13020                "}\n"
13021                "default: {\n"
13022                "  break;\n"
13023                "}\n"
13024                "}");
13025 
13026   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
13027   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
13028   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
13029   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
13030   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
13031   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
13032   verifyFormat("{\n"
13033                "label1:\n"
13034                "  int x = 0;\n"
13035                "}",
13036                CtorInitializerStyle);
13037   verifyFormat("switch (x) {\n"
13038                "case 1:\n"
13039                "default:\n"
13040                "}",
13041                CtorInitializerStyle);
13042   verifyFormat("switch (allBraces) {\n"
13043                "case 1: {\n"
13044                "  break;\n"
13045                "}\n"
13046                "case 2: {\n"
13047                "  [[fallthrough]];\n"
13048                "}\n"
13049                "default: {\n"
13050                "  break;\n"
13051                "}\n"
13052                "}",
13053                CtorInitializerStyle);
13054   CtorInitializerStyle.BreakConstructorInitializers =
13055       FormatStyle::BCIS_AfterColon;
13056   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
13057                "    aaaaaaaaaaaaaaaa(1),\n"
13058                "    bbbbbbbbbbbbbbbb(2) {}",
13059                CtorInitializerStyle);
13060   CtorInitializerStyle.BreakConstructorInitializers =
13061       FormatStyle::BCIS_BeforeComma;
13062   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
13063                "    : aaaaaaaaaaaaaaaa(1)\n"
13064                "    , bbbbbbbbbbbbbbbb(2) {}",
13065                CtorInitializerStyle);
13066   CtorInitializerStyle.BreakConstructorInitializers =
13067       FormatStyle::BCIS_BeforeColon;
13068   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
13069                "    : aaaaaaaaaaaaaaaa(1),\n"
13070                "      bbbbbbbbbbbbbbbb(2) {}",
13071                CtorInitializerStyle);
13072   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
13073   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
13074                ": aaaaaaaaaaaaaaaa(1),\n"
13075                "  bbbbbbbbbbbbbbbb(2) {}",
13076                CtorInitializerStyle);
13077 
13078   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
13079   InheritanceStyle.SpaceBeforeInheritanceColon = false;
13080   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
13081   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
13082   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
13083   verifyFormat("int x = a ? b : c;", InheritanceStyle);
13084   verifyFormat("{\n"
13085                "label2:\n"
13086                "  int x = 0;\n"
13087                "}",
13088                InheritanceStyle);
13089   verifyFormat("switch (x) {\n"
13090                "case 1:\n"
13091                "default:\n"
13092                "}",
13093                InheritanceStyle);
13094   verifyFormat("switch (allBraces) {\n"
13095                "case 1: {\n"
13096                "  break;\n"
13097                "}\n"
13098                "case 2: {\n"
13099                "  [[fallthrough]];\n"
13100                "}\n"
13101                "default: {\n"
13102                "  break;\n"
13103                "}\n"
13104                "}",
13105                InheritanceStyle);
13106   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
13107   verifyFormat("class Foooooooooooooooooooooo:\n"
13108                "    public aaaaaaaaaaaaaaaaaa,\n"
13109                "    public bbbbbbbbbbbbbbbbbb {\n"
13110                "}",
13111                InheritanceStyle);
13112   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
13113   verifyFormat("class Foooooooooooooooooooooo\n"
13114                "    : public aaaaaaaaaaaaaaaaaa\n"
13115                "    , public bbbbbbbbbbbbbbbbbb {\n"
13116                "}",
13117                InheritanceStyle);
13118   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
13119   verifyFormat("class Foooooooooooooooooooooo\n"
13120                "    : public aaaaaaaaaaaaaaaaaa,\n"
13121                "      public bbbbbbbbbbbbbbbbbb {\n"
13122                "}",
13123                InheritanceStyle);
13124   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
13125   verifyFormat("class Foooooooooooooooooooooo\n"
13126                ": public aaaaaaaaaaaaaaaaaa,\n"
13127                "  public bbbbbbbbbbbbbbbbbb {}",
13128                InheritanceStyle);
13129 
13130   FormatStyle ForLoopStyle = getLLVMStyle();
13131   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
13132   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
13133   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
13134   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
13135   verifyFormat("int x = a ? b : c;", ForLoopStyle);
13136   verifyFormat("{\n"
13137                "label2:\n"
13138                "  int x = 0;\n"
13139                "}",
13140                ForLoopStyle);
13141   verifyFormat("switch (x) {\n"
13142                "case 1:\n"
13143                "default:\n"
13144                "}",
13145                ForLoopStyle);
13146   verifyFormat("switch (allBraces) {\n"
13147                "case 1: {\n"
13148                "  break;\n"
13149                "}\n"
13150                "case 2: {\n"
13151                "  [[fallthrough]];\n"
13152                "}\n"
13153                "default: {\n"
13154                "  break;\n"
13155                "}\n"
13156                "}",
13157                ForLoopStyle);
13158 
13159   FormatStyle CaseStyle = getLLVMStyle();
13160   CaseStyle.SpaceBeforeCaseColon = true;
13161   verifyFormat("class Foo : public Bar {};", CaseStyle);
13162   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
13163   verifyFormat("for (auto a : b) {\n}", CaseStyle);
13164   verifyFormat("int x = a ? b : c;", CaseStyle);
13165   verifyFormat("switch (x) {\n"
13166                "case 1 :\n"
13167                "default :\n"
13168                "}",
13169                CaseStyle);
13170   verifyFormat("switch (allBraces) {\n"
13171                "case 1 : {\n"
13172                "  break;\n"
13173                "}\n"
13174                "case 2 : {\n"
13175                "  [[fallthrough]];\n"
13176                "}\n"
13177                "default : {\n"
13178                "  break;\n"
13179                "}\n"
13180                "}",
13181                CaseStyle);
13182 
13183   FormatStyle NoSpaceStyle = getLLVMStyle();
13184   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
13185   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
13186   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
13187   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
13188   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
13189   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
13190   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
13191   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
13192   verifyFormat("{\n"
13193                "label3:\n"
13194                "  int x = 0;\n"
13195                "}",
13196                NoSpaceStyle);
13197   verifyFormat("switch (x) {\n"
13198                "case 1:\n"
13199                "default:\n"
13200                "}",
13201                NoSpaceStyle);
13202   verifyFormat("switch (allBraces) {\n"
13203                "case 1: {\n"
13204                "  break;\n"
13205                "}\n"
13206                "case 2: {\n"
13207                "  [[fallthrough]];\n"
13208                "}\n"
13209                "default: {\n"
13210                "  break;\n"
13211                "}\n"
13212                "}",
13213                NoSpaceStyle);
13214 
13215   FormatStyle InvertedSpaceStyle = getLLVMStyle();
13216   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
13217   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
13218   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
13219   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
13220   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
13221   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
13222   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
13223   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
13224   verifyFormat("{\n"
13225                "label3:\n"
13226                "  int x = 0;\n"
13227                "}",
13228                InvertedSpaceStyle);
13229   verifyFormat("switch (x) {\n"
13230                "case 1 :\n"
13231                "case 2 : {\n"
13232                "  break;\n"
13233                "}\n"
13234                "default :\n"
13235                "  break;\n"
13236                "}",
13237                InvertedSpaceStyle);
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                InvertedSpaceStyle);
13250 }
13251 
13252 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
13253   FormatStyle Style = getLLVMStyle();
13254 
13255   Style.PointerAlignment = FormatStyle::PAS_Left;
13256   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
13257   verifyFormat("void* const* x = NULL;", Style);
13258 
13259 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
13260   do {                                                                         \
13261     Style.PointerAlignment = FormatStyle::Pointers;                            \
13262     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
13263     verifyFormat(Code, Style);                                                 \
13264   } while (false)
13265 
13266   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
13267   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
13268   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
13269 
13270   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
13271   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
13272   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
13273 
13274   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
13275   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
13276   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
13277 
13278   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
13279   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
13280   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
13281 
13282   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
13283   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
13284                         SAPQ_Default);
13285   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
13286                         SAPQ_Default);
13287 
13288   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
13289   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
13290                         SAPQ_Before);
13291   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
13292                         SAPQ_Before);
13293 
13294   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
13295   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
13296   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
13297                         SAPQ_After);
13298 
13299   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
13300   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
13301   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
13302 
13303 #undef verifyQualifierSpaces
13304 
13305   FormatStyle Spaces = getLLVMStyle();
13306   Spaces.AttributeMacros.push_back("qualified");
13307   Spaces.PointerAlignment = FormatStyle::PAS_Right;
13308   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
13309   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
13310   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
13311   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
13312   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
13313   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13314   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
13315   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
13316   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
13317   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
13318   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
13319   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13320 
13321   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
13322   Spaces.PointerAlignment = FormatStyle::PAS_Left;
13323   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
13324   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
13325   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
13326   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
13327   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
13328   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13329   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
13330   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
13331   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
13332   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
13333   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
13334   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
13335   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13336 
13337   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
13338   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
13339   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
13340   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
13341   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
13342   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
13343   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
13344   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13345 }
13346 
13347 TEST_F(FormatTest, AlignConsecutiveMacros) {
13348   FormatStyle Style = getLLVMStyle();
13349   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13350   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13351   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
13352 
13353   verifyFormat("#define a 3\n"
13354                "#define bbbb 4\n"
13355                "#define ccc (5)",
13356                Style);
13357 
13358   verifyFormat("#define f(x) (x * x)\n"
13359                "#define fff(x, y, z) (x * y + z)\n"
13360                "#define ffff(x, y) (x - y)",
13361                Style);
13362 
13363   verifyFormat("#define foo(x, y) (x + y)\n"
13364                "#define bar (5, 6)(2 + 2)",
13365                Style);
13366 
13367   verifyFormat("#define a 3\n"
13368                "#define bbbb 4\n"
13369                "#define ccc (5)\n"
13370                "#define f(x) (x * x)\n"
13371                "#define fff(x, y, z) (x * y + z)\n"
13372                "#define ffff(x, y) (x - y)",
13373                Style);
13374 
13375   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13376   verifyFormat("#define a    3\n"
13377                "#define bbbb 4\n"
13378                "#define ccc  (5)",
13379                Style);
13380 
13381   verifyFormat("#define f(x)         (x * x)\n"
13382                "#define fff(x, y, z) (x * y + z)\n"
13383                "#define ffff(x, y)   (x - y)",
13384                Style);
13385 
13386   verifyFormat("#define foo(x, y) (x + y)\n"
13387                "#define bar       (5, 6)(2 + 2)",
13388                Style);
13389 
13390   verifyFormat("#define a            3\n"
13391                "#define bbbb         4\n"
13392                "#define ccc          (5)\n"
13393                "#define f(x)         (x * x)\n"
13394                "#define fff(x, y, z) (x * y + z)\n"
13395                "#define ffff(x, y)   (x - y)",
13396                Style);
13397 
13398   verifyFormat("#define a         5\n"
13399                "#define foo(x, y) (x + y)\n"
13400                "#define CCC       (6)\n"
13401                "auto lambda = []() {\n"
13402                "  auto  ii = 0;\n"
13403                "  float j  = 0;\n"
13404                "  return 0;\n"
13405                "};\n"
13406                "int   i  = 0;\n"
13407                "float i2 = 0;\n"
13408                "auto  v  = type{\n"
13409                "    i = 1,   //\n"
13410                "    (i = 2), //\n"
13411                "    i = 3    //\n"
13412                "};",
13413                Style);
13414 
13415   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
13416   Style.ColumnLimit = 20;
13417 
13418   verifyFormat("#define a          \\\n"
13419                "  \"aabbbbbbbbbbbb\"\n"
13420                "#define D          \\\n"
13421                "  \"aabbbbbbbbbbbb\" \\\n"
13422                "  \"ccddeeeeeeeee\"\n"
13423                "#define B          \\\n"
13424                "  \"QQQQQQQQQQQQQ\"  \\\n"
13425                "  \"FFFFFFFFFFFFF\"  \\\n"
13426                "  \"LLLLLLLL\"\n",
13427                Style);
13428 
13429   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13430   verifyFormat("#define a          \\\n"
13431                "  \"aabbbbbbbbbbbb\"\n"
13432                "#define D          \\\n"
13433                "  \"aabbbbbbbbbbbb\" \\\n"
13434                "  \"ccddeeeeeeeee\"\n"
13435                "#define B          \\\n"
13436                "  \"QQQQQQQQQQQQQ\"  \\\n"
13437                "  \"FFFFFFFFFFFFF\"  \\\n"
13438                "  \"LLLLLLLL\"\n",
13439                Style);
13440 
13441   // Test across comments
13442   Style.MaxEmptyLinesToKeep = 10;
13443   Style.ReflowComments = false;
13444   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
13445   EXPECT_EQ("#define a    3\n"
13446             "// line comment\n"
13447             "#define bbbb 4\n"
13448             "#define ccc  (5)",
13449             format("#define a 3\n"
13450                    "// line comment\n"
13451                    "#define bbbb 4\n"
13452                    "#define ccc (5)",
13453                    Style));
13454 
13455   EXPECT_EQ("#define a    3\n"
13456             "/* block comment */\n"
13457             "#define bbbb 4\n"
13458             "#define ccc  (5)",
13459             format("#define a  3\n"
13460                    "/* block comment */\n"
13461                    "#define bbbb 4\n"
13462                    "#define ccc (5)",
13463                    Style));
13464 
13465   EXPECT_EQ("#define a    3\n"
13466             "/* multi-line *\n"
13467             " * block comment */\n"
13468             "#define bbbb 4\n"
13469             "#define ccc  (5)",
13470             format("#define a 3\n"
13471                    "/* multi-line *\n"
13472                    " * block comment */\n"
13473                    "#define bbbb 4\n"
13474                    "#define ccc (5)",
13475                    Style));
13476 
13477   EXPECT_EQ("#define a    3\n"
13478             "// multi-line line comment\n"
13479             "//\n"
13480             "#define bbbb 4\n"
13481             "#define ccc  (5)",
13482             format("#define a  3\n"
13483                    "// multi-line line comment\n"
13484                    "//\n"
13485                    "#define bbbb 4\n"
13486                    "#define ccc (5)",
13487                    Style));
13488 
13489   EXPECT_EQ("#define a 3\n"
13490             "// empty lines still break.\n"
13491             "\n"
13492             "#define bbbb 4\n"
13493             "#define ccc  (5)",
13494             format("#define a     3\n"
13495                    "// empty lines still break.\n"
13496                    "\n"
13497                    "#define bbbb     4\n"
13498                    "#define ccc  (5)",
13499                    Style));
13500 
13501   // Test across empty lines
13502   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
13503   EXPECT_EQ("#define a    3\n"
13504             "\n"
13505             "#define bbbb 4\n"
13506             "#define ccc  (5)",
13507             format("#define a 3\n"
13508                    "\n"
13509                    "#define bbbb 4\n"
13510                    "#define ccc (5)",
13511                    Style));
13512 
13513   EXPECT_EQ("#define a    3\n"
13514             "\n"
13515             "\n"
13516             "\n"
13517             "#define bbbb 4\n"
13518             "#define ccc  (5)",
13519             format("#define a        3\n"
13520                    "\n"
13521                    "\n"
13522                    "\n"
13523                    "#define bbbb 4\n"
13524                    "#define ccc (5)",
13525                    Style));
13526 
13527   EXPECT_EQ("#define a 3\n"
13528             "// comments should break alignment\n"
13529             "//\n"
13530             "#define bbbb 4\n"
13531             "#define ccc  (5)",
13532             format("#define a        3\n"
13533                    "// comments should break alignment\n"
13534                    "//\n"
13535                    "#define bbbb 4\n"
13536                    "#define ccc (5)",
13537                    Style));
13538 
13539   // Test across empty lines and comments
13540   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
13541   verifyFormat("#define a    3\n"
13542                "\n"
13543                "// line comment\n"
13544                "#define bbbb 4\n"
13545                "#define ccc  (5)",
13546                Style);
13547 
13548   EXPECT_EQ("#define a    3\n"
13549             "\n"
13550             "\n"
13551             "/* multi-line *\n"
13552             " * block comment */\n"
13553             "\n"
13554             "\n"
13555             "#define bbbb 4\n"
13556             "#define ccc  (5)",
13557             format("#define a 3\n"
13558                    "\n"
13559                    "\n"
13560                    "/* multi-line *\n"
13561                    " * block comment */\n"
13562                    "\n"
13563                    "\n"
13564                    "#define bbbb 4\n"
13565                    "#define ccc (5)",
13566                    Style));
13567 
13568   EXPECT_EQ("#define a    3\n"
13569             "\n"
13570             "\n"
13571             "/* multi-line *\n"
13572             " * block comment */\n"
13573             "\n"
13574             "\n"
13575             "#define bbbb 4\n"
13576             "#define ccc  (5)",
13577             format("#define a 3\n"
13578                    "\n"
13579                    "\n"
13580                    "/* multi-line *\n"
13581                    " * block comment */\n"
13582                    "\n"
13583                    "\n"
13584                    "#define bbbb 4\n"
13585                    "#define ccc       (5)",
13586                    Style));
13587 }
13588 
13589 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
13590   FormatStyle Alignment = getLLVMStyle();
13591   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13592   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
13593 
13594   Alignment.MaxEmptyLinesToKeep = 10;
13595   /* Test alignment across empty lines */
13596   EXPECT_EQ("int a           = 5;\n"
13597             "\n"
13598             "int oneTwoThree = 123;",
13599             format("int a       = 5;\n"
13600                    "\n"
13601                    "int oneTwoThree= 123;",
13602                    Alignment));
13603   EXPECT_EQ("int a           = 5;\n"
13604             "int one         = 1;\n"
13605             "\n"
13606             "int oneTwoThree = 123;",
13607             format("int a = 5;\n"
13608                    "int one = 1;\n"
13609                    "\n"
13610                    "int oneTwoThree = 123;",
13611                    Alignment));
13612   EXPECT_EQ("int a           = 5;\n"
13613             "int one         = 1;\n"
13614             "\n"
13615             "int oneTwoThree = 123;\n"
13616             "int oneTwo      = 12;",
13617             format("int a = 5;\n"
13618                    "int one = 1;\n"
13619                    "\n"
13620                    "int oneTwoThree = 123;\n"
13621                    "int oneTwo = 12;",
13622                    Alignment));
13623 
13624   /* Test across comments */
13625   EXPECT_EQ("int a = 5;\n"
13626             "/* block comment */\n"
13627             "int oneTwoThree = 123;",
13628             format("int a = 5;\n"
13629                    "/* block comment */\n"
13630                    "int oneTwoThree=123;",
13631                    Alignment));
13632 
13633   EXPECT_EQ("int a = 5;\n"
13634             "// line comment\n"
13635             "int oneTwoThree = 123;",
13636             format("int a = 5;\n"
13637                    "// line comment\n"
13638                    "int oneTwoThree=123;",
13639                    Alignment));
13640 
13641   /* Test across comments and newlines */
13642   EXPECT_EQ("int a = 5;\n"
13643             "\n"
13644             "/* block comment */\n"
13645             "int oneTwoThree = 123;",
13646             format("int a = 5;\n"
13647                    "\n"
13648                    "/* block comment */\n"
13649                    "int oneTwoThree=123;",
13650                    Alignment));
13651 
13652   EXPECT_EQ("int a = 5;\n"
13653             "\n"
13654             "// line comment\n"
13655             "int oneTwoThree = 123;",
13656             format("int a = 5;\n"
13657                    "\n"
13658                    "// line comment\n"
13659                    "int oneTwoThree=123;",
13660                    Alignment));
13661 }
13662 
13663 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
13664   FormatStyle Alignment = getLLVMStyle();
13665   Alignment.AlignConsecutiveDeclarations =
13666       FormatStyle::ACS_AcrossEmptyLinesAndComments;
13667   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
13668 
13669   Alignment.MaxEmptyLinesToKeep = 10;
13670   /* Test alignment across empty lines */
13671   EXPECT_EQ("int         a = 5;\n"
13672             "\n"
13673             "float const oneTwoThree = 123;",
13674             format("int a = 5;\n"
13675                    "\n"
13676                    "float const oneTwoThree = 123;",
13677                    Alignment));
13678   EXPECT_EQ("int         a = 5;\n"
13679             "float const one = 1;\n"
13680             "\n"
13681             "int         oneTwoThree = 123;",
13682             format("int a = 5;\n"
13683                    "float const one = 1;\n"
13684                    "\n"
13685                    "int oneTwoThree = 123;",
13686                    Alignment));
13687 
13688   /* Test across comments */
13689   EXPECT_EQ("float const a = 5;\n"
13690             "/* block comment */\n"
13691             "int         oneTwoThree = 123;",
13692             format("float const a = 5;\n"
13693                    "/* block comment */\n"
13694                    "int oneTwoThree=123;",
13695                    Alignment));
13696 
13697   EXPECT_EQ("float const a = 5;\n"
13698             "// line comment\n"
13699             "int         oneTwoThree = 123;",
13700             format("float const a = 5;\n"
13701                    "// line comment\n"
13702                    "int oneTwoThree=123;",
13703                    Alignment));
13704 
13705   /* Test across comments and newlines */
13706   EXPECT_EQ("float const a = 5;\n"
13707             "\n"
13708             "/* block comment */\n"
13709             "int         oneTwoThree = 123;",
13710             format("float const a = 5;\n"
13711                    "\n"
13712                    "/* block comment */\n"
13713                    "int         oneTwoThree=123;",
13714                    Alignment));
13715 
13716   EXPECT_EQ("float const a = 5;\n"
13717             "\n"
13718             "// line comment\n"
13719             "int         oneTwoThree = 123;",
13720             format("float const a = 5;\n"
13721                    "\n"
13722                    "// line comment\n"
13723                    "int oneTwoThree=123;",
13724                    Alignment));
13725 }
13726 
13727 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
13728   FormatStyle Alignment = getLLVMStyle();
13729   Alignment.AlignConsecutiveBitFields =
13730       FormatStyle::ACS_AcrossEmptyLinesAndComments;
13731 
13732   Alignment.MaxEmptyLinesToKeep = 10;
13733   /* Test alignment across empty lines */
13734   EXPECT_EQ("int a            : 5;\n"
13735             "\n"
13736             "int longbitfield : 6;",
13737             format("int a : 5;\n"
13738                    "\n"
13739                    "int longbitfield : 6;",
13740                    Alignment));
13741   EXPECT_EQ("int a            : 5;\n"
13742             "int one          : 1;\n"
13743             "\n"
13744             "int longbitfield : 6;",
13745             format("int a : 5;\n"
13746                    "int one : 1;\n"
13747                    "\n"
13748                    "int longbitfield : 6;",
13749                    Alignment));
13750 
13751   /* Test across comments */
13752   EXPECT_EQ("int a            : 5;\n"
13753             "/* block comment */\n"
13754             "int longbitfield : 6;",
13755             format("int a : 5;\n"
13756                    "/* block comment */\n"
13757                    "int longbitfield : 6;",
13758                    Alignment));
13759   EXPECT_EQ("int a            : 5;\n"
13760             "int one          : 1;\n"
13761             "// line comment\n"
13762             "int longbitfield : 6;",
13763             format("int a : 5;\n"
13764                    "int one : 1;\n"
13765                    "// line comment\n"
13766                    "int longbitfield : 6;",
13767                    Alignment));
13768 
13769   /* Test across comments and newlines */
13770   EXPECT_EQ("int a            : 5;\n"
13771             "/* block comment */\n"
13772             "\n"
13773             "int longbitfield : 6;",
13774             format("int a : 5;\n"
13775                    "/* block comment */\n"
13776                    "\n"
13777                    "int longbitfield : 6;",
13778                    Alignment));
13779   EXPECT_EQ("int a            : 5;\n"
13780             "int one          : 1;\n"
13781             "\n"
13782             "// line comment\n"
13783             "\n"
13784             "int longbitfield : 6;",
13785             format("int a : 5;\n"
13786                    "int one : 1;\n"
13787                    "\n"
13788                    "// line comment \n"
13789                    "\n"
13790                    "int longbitfield : 6;",
13791                    Alignment));
13792 }
13793 
13794 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
13795   FormatStyle Alignment = getLLVMStyle();
13796   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13797   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
13798 
13799   Alignment.MaxEmptyLinesToKeep = 10;
13800   /* Test alignment across empty lines */
13801   EXPECT_EQ("int a = 5;\n"
13802             "\n"
13803             "int oneTwoThree = 123;",
13804             format("int a       = 5;\n"
13805                    "\n"
13806                    "int oneTwoThree= 123;",
13807                    Alignment));
13808   EXPECT_EQ("int a   = 5;\n"
13809             "int one = 1;\n"
13810             "\n"
13811             "int oneTwoThree = 123;",
13812             format("int a = 5;\n"
13813                    "int one = 1;\n"
13814                    "\n"
13815                    "int oneTwoThree = 123;",
13816                    Alignment));
13817 
13818   /* Test across comments */
13819   EXPECT_EQ("int a           = 5;\n"
13820             "/* block comment */\n"
13821             "int oneTwoThree = 123;",
13822             format("int a = 5;\n"
13823                    "/* block comment */\n"
13824                    "int oneTwoThree=123;",
13825                    Alignment));
13826 
13827   EXPECT_EQ("int a           = 5;\n"
13828             "// line comment\n"
13829             "int oneTwoThree = 123;",
13830             format("int a = 5;\n"
13831                    "// line comment\n"
13832                    "int oneTwoThree=123;",
13833                    Alignment));
13834 
13835   EXPECT_EQ("int a           = 5;\n"
13836             "/*\n"
13837             " * multi-line block comment\n"
13838             " */\n"
13839             "int oneTwoThree = 123;",
13840             format("int a = 5;\n"
13841                    "/*\n"
13842                    " * multi-line block comment\n"
13843                    " */\n"
13844                    "int oneTwoThree=123;",
13845                    Alignment));
13846 
13847   EXPECT_EQ("int a           = 5;\n"
13848             "//\n"
13849             "// multi-line line comment\n"
13850             "//\n"
13851             "int oneTwoThree = 123;",
13852             format("int a = 5;\n"
13853                    "//\n"
13854                    "// multi-line line comment\n"
13855                    "//\n"
13856                    "int oneTwoThree=123;",
13857                    Alignment));
13858 
13859   /* Test across comments and newlines */
13860   EXPECT_EQ("int a = 5;\n"
13861             "\n"
13862             "/* block comment */\n"
13863             "int oneTwoThree = 123;",
13864             format("int a = 5;\n"
13865                    "\n"
13866                    "/* block comment */\n"
13867                    "int oneTwoThree=123;",
13868                    Alignment));
13869 
13870   EXPECT_EQ("int a = 5;\n"
13871             "\n"
13872             "// line comment\n"
13873             "int oneTwoThree = 123;",
13874             format("int a = 5;\n"
13875                    "\n"
13876                    "// line comment\n"
13877                    "int oneTwoThree=123;",
13878                    Alignment));
13879 }
13880 
13881 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
13882   FormatStyle Alignment = getLLVMStyle();
13883   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13884   Alignment.AlignConsecutiveAssignments =
13885       FormatStyle::ACS_AcrossEmptyLinesAndComments;
13886   verifyFormat("int a           = 5;\n"
13887                "int oneTwoThree = 123;",
13888                Alignment);
13889   verifyFormat("int a           = method();\n"
13890                "int oneTwoThree = 133;",
13891                Alignment);
13892   verifyFormat("a &= 5;\n"
13893                "bcd *= 5;\n"
13894                "ghtyf += 5;\n"
13895                "dvfvdb -= 5;\n"
13896                "a /= 5;\n"
13897                "vdsvsv %= 5;\n"
13898                "sfdbddfbdfbb ^= 5;\n"
13899                "dvsdsv |= 5;\n"
13900                "int dsvvdvsdvvv = 123;",
13901                Alignment);
13902   verifyFormat("int i = 1, j = 10;\n"
13903                "something = 2000;",
13904                Alignment);
13905   verifyFormat("something = 2000;\n"
13906                "int i = 1, j = 10;\n",
13907                Alignment);
13908   verifyFormat("something = 2000;\n"
13909                "another   = 911;\n"
13910                "int i = 1, j = 10;\n"
13911                "oneMore = 1;\n"
13912                "i       = 2;",
13913                Alignment);
13914   verifyFormat("int a   = 5;\n"
13915                "int one = 1;\n"
13916                "method();\n"
13917                "int oneTwoThree = 123;\n"
13918                "int oneTwo      = 12;",
13919                Alignment);
13920   verifyFormat("int oneTwoThree = 123;\n"
13921                "int oneTwo      = 12;\n"
13922                "method();\n",
13923                Alignment);
13924   verifyFormat("int oneTwoThree = 123; // comment\n"
13925                "int oneTwo      = 12;  // comment",
13926                Alignment);
13927 
13928   // Bug 25167
13929   /* Uncomment when fixed
13930     verifyFormat("#if A\n"
13931                  "#else\n"
13932                  "int aaaaaaaa = 12;\n"
13933                  "#endif\n"
13934                  "#if B\n"
13935                  "#else\n"
13936                  "int a = 12;\n"
13937                  "#endif\n",
13938                  Alignment);
13939     verifyFormat("enum foo {\n"
13940                  "#if A\n"
13941                  "#else\n"
13942                  "  aaaaaaaa = 12;\n"
13943                  "#endif\n"
13944                  "#if B\n"
13945                  "#else\n"
13946                  "  a = 12;\n"
13947                  "#endif\n"
13948                  "};\n",
13949                  Alignment);
13950   */
13951 
13952   Alignment.MaxEmptyLinesToKeep = 10;
13953   /* Test alignment across empty lines */
13954   EXPECT_EQ("int a           = 5;\n"
13955             "\n"
13956             "int oneTwoThree = 123;",
13957             format("int a       = 5;\n"
13958                    "\n"
13959                    "int oneTwoThree= 123;",
13960                    Alignment));
13961   EXPECT_EQ("int a           = 5;\n"
13962             "int one         = 1;\n"
13963             "\n"
13964             "int oneTwoThree = 123;",
13965             format("int a = 5;\n"
13966                    "int one = 1;\n"
13967                    "\n"
13968                    "int oneTwoThree = 123;",
13969                    Alignment));
13970   EXPECT_EQ("int a           = 5;\n"
13971             "int one         = 1;\n"
13972             "\n"
13973             "int oneTwoThree = 123;\n"
13974             "int oneTwo      = 12;",
13975             format("int a = 5;\n"
13976                    "int one = 1;\n"
13977                    "\n"
13978                    "int oneTwoThree = 123;\n"
13979                    "int oneTwo = 12;",
13980                    Alignment));
13981 
13982   /* Test across comments */
13983   EXPECT_EQ("int a           = 5;\n"
13984             "/* block comment */\n"
13985             "int oneTwoThree = 123;",
13986             format("int a = 5;\n"
13987                    "/* block comment */\n"
13988                    "int oneTwoThree=123;",
13989                    Alignment));
13990 
13991   EXPECT_EQ("int a           = 5;\n"
13992             "// line comment\n"
13993             "int oneTwoThree = 123;",
13994             format("int a = 5;\n"
13995                    "// line comment\n"
13996                    "int oneTwoThree=123;",
13997                    Alignment));
13998 
13999   /* Test across comments and newlines */
14000   EXPECT_EQ("int a           = 5;\n"
14001             "\n"
14002             "/* block comment */\n"
14003             "int oneTwoThree = 123;",
14004             format("int a = 5;\n"
14005                    "\n"
14006                    "/* block comment */\n"
14007                    "int oneTwoThree=123;",
14008                    Alignment));
14009 
14010   EXPECT_EQ("int a           = 5;\n"
14011             "\n"
14012             "// line comment\n"
14013             "int oneTwoThree = 123;",
14014             format("int a = 5;\n"
14015                    "\n"
14016                    "// line comment\n"
14017                    "int oneTwoThree=123;",
14018                    Alignment));
14019 
14020   EXPECT_EQ("int a           = 5;\n"
14021             "//\n"
14022             "// multi-line line comment\n"
14023             "//\n"
14024             "int oneTwoThree = 123;",
14025             format("int a = 5;\n"
14026                    "//\n"
14027                    "// multi-line line comment\n"
14028                    "//\n"
14029                    "int oneTwoThree=123;",
14030                    Alignment));
14031 
14032   EXPECT_EQ("int a           = 5;\n"
14033             "/*\n"
14034             " *  multi-line block comment\n"
14035             " */\n"
14036             "int oneTwoThree = 123;",
14037             format("int a = 5;\n"
14038                    "/*\n"
14039                    " *  multi-line block comment\n"
14040                    " */\n"
14041                    "int oneTwoThree=123;",
14042                    Alignment));
14043 
14044   EXPECT_EQ("int a           = 5;\n"
14045             "\n"
14046             "/* block comment */\n"
14047             "\n"
14048             "\n"
14049             "\n"
14050             "int oneTwoThree = 123;",
14051             format("int a = 5;\n"
14052                    "\n"
14053                    "/* block comment */\n"
14054                    "\n"
14055                    "\n"
14056                    "\n"
14057                    "int oneTwoThree=123;",
14058                    Alignment));
14059 
14060   EXPECT_EQ("int a           = 5;\n"
14061             "\n"
14062             "// line comment\n"
14063             "\n"
14064             "\n"
14065             "\n"
14066             "int oneTwoThree = 123;",
14067             format("int a = 5;\n"
14068                    "\n"
14069                    "// line comment\n"
14070                    "\n"
14071                    "\n"
14072                    "\n"
14073                    "int oneTwoThree=123;",
14074                    Alignment));
14075 
14076   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
14077   verifyFormat("#define A \\\n"
14078                "  int aaaa       = 12; \\\n"
14079                "  int b          = 23; \\\n"
14080                "  int ccc        = 234; \\\n"
14081                "  int dddddddddd = 2345;",
14082                Alignment);
14083   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14084   verifyFormat("#define A               \\\n"
14085                "  int aaaa       = 12;  \\\n"
14086                "  int b          = 23;  \\\n"
14087                "  int ccc        = 234; \\\n"
14088                "  int dddddddddd = 2345;",
14089                Alignment);
14090   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
14091   verifyFormat("#define A                                                      "
14092                "                \\\n"
14093                "  int aaaa       = 12;                                         "
14094                "                \\\n"
14095                "  int b          = 23;                                         "
14096                "                \\\n"
14097                "  int ccc        = 234;                                        "
14098                "                \\\n"
14099                "  int dddddddddd = 2345;",
14100                Alignment);
14101   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
14102                "k = 4, int l = 5,\n"
14103                "                  int m = 6) {\n"
14104                "  int j      = 10;\n"
14105                "  otherThing = 1;\n"
14106                "}",
14107                Alignment);
14108   verifyFormat("void SomeFunction(int parameter = 0) {\n"
14109                "  int i   = 1;\n"
14110                "  int j   = 2;\n"
14111                "  int big = 10000;\n"
14112                "}",
14113                Alignment);
14114   verifyFormat("class C {\n"
14115                "public:\n"
14116                "  int i            = 1;\n"
14117                "  virtual void f() = 0;\n"
14118                "};",
14119                Alignment);
14120   verifyFormat("int i = 1;\n"
14121                "if (SomeType t = getSomething()) {\n"
14122                "}\n"
14123                "int j   = 2;\n"
14124                "int big = 10000;",
14125                Alignment);
14126   verifyFormat("int j = 7;\n"
14127                "for (int k = 0; k < N; ++k) {\n"
14128                "}\n"
14129                "int j   = 2;\n"
14130                "int big = 10000;\n"
14131                "}",
14132                Alignment);
14133   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14134   verifyFormat("int i = 1;\n"
14135                "LooooooooooongType loooooooooooooooooooooongVariable\n"
14136                "    = someLooooooooooooooooongFunction();\n"
14137                "int j = 2;",
14138                Alignment);
14139   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
14140   verifyFormat("int i = 1;\n"
14141                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
14142                "    someLooooooooooooooooongFunction();\n"
14143                "int j = 2;",
14144                Alignment);
14145 
14146   verifyFormat("auto lambda = []() {\n"
14147                "  auto i = 0;\n"
14148                "  return 0;\n"
14149                "};\n"
14150                "int i  = 0;\n"
14151                "auto v = type{\n"
14152                "    i = 1,   //\n"
14153                "    (i = 2), //\n"
14154                "    i = 3    //\n"
14155                "};",
14156                Alignment);
14157 
14158   verifyFormat(
14159       "int i      = 1;\n"
14160       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
14161       "                          loooooooooooooooooooooongParameterB);\n"
14162       "int j      = 2;",
14163       Alignment);
14164 
14165   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
14166                "          typename B   = very_long_type_name_1,\n"
14167                "          typename T_2 = very_long_type_name_2>\n"
14168                "auto foo() {}\n",
14169                Alignment);
14170   verifyFormat("int a, b = 1;\n"
14171                "int c  = 2;\n"
14172                "int dd = 3;\n",
14173                Alignment);
14174   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
14175                "float b[1][] = {{3.f}};\n",
14176                Alignment);
14177   verifyFormat("for (int i = 0; i < 1; i++)\n"
14178                "  int x = 1;\n",
14179                Alignment);
14180   verifyFormat("for (i = 0; i < 1; i++)\n"
14181                "  x = 1;\n"
14182                "y = 1;\n",
14183                Alignment);
14184 
14185   Alignment.ReflowComments = true;
14186   Alignment.ColumnLimit = 50;
14187   EXPECT_EQ("int x   = 0;\n"
14188             "int yy  = 1; /// specificlennospace\n"
14189             "int zzz = 2;\n",
14190             format("int x   = 0;\n"
14191                    "int yy  = 1; ///specificlennospace\n"
14192                    "int zzz = 2;\n",
14193                    Alignment));
14194 }
14195 
14196 TEST_F(FormatTest, AlignConsecutiveAssignments) {
14197   FormatStyle Alignment = getLLVMStyle();
14198   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14199   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14200   verifyFormat("int a = 5;\n"
14201                "int oneTwoThree = 123;",
14202                Alignment);
14203   verifyFormat("int a = 5;\n"
14204                "int oneTwoThree = 123;",
14205                Alignment);
14206 
14207   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14208   verifyFormat("int a           = 5;\n"
14209                "int oneTwoThree = 123;",
14210                Alignment);
14211   verifyFormat("int a           = method();\n"
14212                "int oneTwoThree = 133;",
14213                Alignment);
14214   verifyFormat("a &= 5;\n"
14215                "bcd *= 5;\n"
14216                "ghtyf += 5;\n"
14217                "dvfvdb -= 5;\n"
14218                "a /= 5;\n"
14219                "vdsvsv %= 5;\n"
14220                "sfdbddfbdfbb ^= 5;\n"
14221                "dvsdsv |= 5;\n"
14222                "int dsvvdvsdvvv = 123;",
14223                Alignment);
14224   verifyFormat("int i = 1, j = 10;\n"
14225                "something = 2000;",
14226                Alignment);
14227   verifyFormat("something = 2000;\n"
14228                "int i = 1, j = 10;\n",
14229                Alignment);
14230   verifyFormat("something = 2000;\n"
14231                "another   = 911;\n"
14232                "int i = 1, j = 10;\n"
14233                "oneMore = 1;\n"
14234                "i       = 2;",
14235                Alignment);
14236   verifyFormat("int a   = 5;\n"
14237                "int one = 1;\n"
14238                "method();\n"
14239                "int oneTwoThree = 123;\n"
14240                "int oneTwo      = 12;",
14241                Alignment);
14242   verifyFormat("int oneTwoThree = 123;\n"
14243                "int oneTwo      = 12;\n"
14244                "method();\n",
14245                Alignment);
14246   verifyFormat("int oneTwoThree = 123; // comment\n"
14247                "int oneTwo      = 12;  // comment",
14248                Alignment);
14249 
14250   // Bug 25167
14251   /* Uncomment when fixed
14252     verifyFormat("#if A\n"
14253                  "#else\n"
14254                  "int aaaaaaaa = 12;\n"
14255                  "#endif\n"
14256                  "#if B\n"
14257                  "#else\n"
14258                  "int a = 12;\n"
14259                  "#endif\n",
14260                  Alignment);
14261     verifyFormat("enum foo {\n"
14262                  "#if A\n"
14263                  "#else\n"
14264                  "  aaaaaaaa = 12;\n"
14265                  "#endif\n"
14266                  "#if B\n"
14267                  "#else\n"
14268                  "  a = 12;\n"
14269                  "#endif\n"
14270                  "};\n",
14271                  Alignment);
14272   */
14273 
14274   EXPECT_EQ("int a = 5;\n"
14275             "\n"
14276             "int oneTwoThree = 123;",
14277             format("int a       = 5;\n"
14278                    "\n"
14279                    "int oneTwoThree= 123;",
14280                    Alignment));
14281   EXPECT_EQ("int a   = 5;\n"
14282             "int one = 1;\n"
14283             "\n"
14284             "int oneTwoThree = 123;",
14285             format("int a = 5;\n"
14286                    "int one = 1;\n"
14287                    "\n"
14288                    "int oneTwoThree = 123;",
14289                    Alignment));
14290   EXPECT_EQ("int a   = 5;\n"
14291             "int one = 1;\n"
14292             "\n"
14293             "int oneTwoThree = 123;\n"
14294             "int oneTwo      = 12;",
14295             format("int a = 5;\n"
14296                    "int one = 1;\n"
14297                    "\n"
14298                    "int oneTwoThree = 123;\n"
14299                    "int oneTwo = 12;",
14300                    Alignment));
14301   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
14302   verifyFormat("#define A \\\n"
14303                "  int aaaa       = 12; \\\n"
14304                "  int b          = 23; \\\n"
14305                "  int ccc        = 234; \\\n"
14306                "  int dddddddddd = 2345;",
14307                Alignment);
14308   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14309   verifyFormat("#define A               \\\n"
14310                "  int aaaa       = 12;  \\\n"
14311                "  int b          = 23;  \\\n"
14312                "  int ccc        = 234; \\\n"
14313                "  int dddddddddd = 2345;",
14314                Alignment);
14315   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
14316   verifyFormat("#define A                                                      "
14317                "                \\\n"
14318                "  int aaaa       = 12;                                         "
14319                "                \\\n"
14320                "  int b          = 23;                                         "
14321                "                \\\n"
14322                "  int ccc        = 234;                                        "
14323                "                \\\n"
14324                "  int dddddddddd = 2345;",
14325                Alignment);
14326   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
14327                "k = 4, int l = 5,\n"
14328                "                  int m = 6) {\n"
14329                "  int j      = 10;\n"
14330                "  otherThing = 1;\n"
14331                "}",
14332                Alignment);
14333   verifyFormat("void SomeFunction(int parameter = 0) {\n"
14334                "  int i   = 1;\n"
14335                "  int j   = 2;\n"
14336                "  int big = 10000;\n"
14337                "}",
14338                Alignment);
14339   verifyFormat("class C {\n"
14340                "public:\n"
14341                "  int i            = 1;\n"
14342                "  virtual void f() = 0;\n"
14343                "};",
14344                Alignment);
14345   verifyFormat("int i = 1;\n"
14346                "if (SomeType t = getSomething()) {\n"
14347                "}\n"
14348                "int j   = 2;\n"
14349                "int big = 10000;",
14350                Alignment);
14351   verifyFormat("int j = 7;\n"
14352                "for (int k = 0; k < N; ++k) {\n"
14353                "}\n"
14354                "int j   = 2;\n"
14355                "int big = 10000;\n"
14356                "}",
14357                Alignment);
14358   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14359   verifyFormat("int i = 1;\n"
14360                "LooooooooooongType loooooooooooooooooooooongVariable\n"
14361                "    = someLooooooooooooooooongFunction();\n"
14362                "int j = 2;",
14363                Alignment);
14364   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
14365   verifyFormat("int i = 1;\n"
14366                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
14367                "    someLooooooooooooooooongFunction();\n"
14368                "int j = 2;",
14369                Alignment);
14370 
14371   verifyFormat("auto lambda = []() {\n"
14372                "  auto i = 0;\n"
14373                "  return 0;\n"
14374                "};\n"
14375                "int i  = 0;\n"
14376                "auto v = type{\n"
14377                "    i = 1,   //\n"
14378                "    (i = 2), //\n"
14379                "    i = 3    //\n"
14380                "};",
14381                Alignment);
14382 
14383   verifyFormat(
14384       "int i      = 1;\n"
14385       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
14386       "                          loooooooooooooooooooooongParameterB);\n"
14387       "int j      = 2;",
14388       Alignment);
14389 
14390   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
14391                "          typename B   = very_long_type_name_1,\n"
14392                "          typename T_2 = very_long_type_name_2>\n"
14393                "auto foo() {}\n",
14394                Alignment);
14395   verifyFormat("int a, b = 1;\n"
14396                "int c  = 2;\n"
14397                "int dd = 3;\n",
14398                Alignment);
14399   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
14400                "float b[1][] = {{3.f}};\n",
14401                Alignment);
14402   verifyFormat("for (int i = 0; i < 1; i++)\n"
14403                "  int x = 1;\n",
14404                Alignment);
14405   verifyFormat("for (i = 0; i < 1; i++)\n"
14406                "  x = 1;\n"
14407                "y = 1;\n",
14408                Alignment);
14409 
14410   Alignment.ReflowComments = true;
14411   Alignment.ColumnLimit = 50;
14412   EXPECT_EQ("int x   = 0;\n"
14413             "int yy  = 1; /// specificlennospace\n"
14414             "int zzz = 2;\n",
14415             format("int x   = 0;\n"
14416                    "int yy  = 1; ///specificlennospace\n"
14417                    "int zzz = 2;\n",
14418                    Alignment));
14419 }
14420 
14421 TEST_F(FormatTest, AlignConsecutiveBitFields) {
14422   FormatStyle Alignment = getLLVMStyle();
14423   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
14424   verifyFormat("int const a     : 5;\n"
14425                "int oneTwoThree : 23;",
14426                Alignment);
14427 
14428   // Initializers are allowed starting with c++2a
14429   verifyFormat("int const a     : 5 = 1;\n"
14430                "int oneTwoThree : 23 = 0;",
14431                Alignment);
14432 
14433   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14434   verifyFormat("int const a           : 5;\n"
14435                "int       oneTwoThree : 23;",
14436                Alignment);
14437 
14438   verifyFormat("int const a           : 5;  // comment\n"
14439                "int       oneTwoThree : 23; // comment",
14440                Alignment);
14441 
14442   verifyFormat("int const a           : 5 = 1;\n"
14443                "int       oneTwoThree : 23 = 0;",
14444                Alignment);
14445 
14446   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14447   verifyFormat("int const a           : 5  = 1;\n"
14448                "int       oneTwoThree : 23 = 0;",
14449                Alignment);
14450   verifyFormat("int const a           : 5  = {1};\n"
14451                "int       oneTwoThree : 23 = 0;",
14452                Alignment);
14453 
14454   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
14455   verifyFormat("int const a          :5;\n"
14456                "int       oneTwoThree:23;",
14457                Alignment);
14458 
14459   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
14460   verifyFormat("int const a           :5;\n"
14461                "int       oneTwoThree :23;",
14462                Alignment);
14463 
14464   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
14465   verifyFormat("int const a          : 5;\n"
14466                "int       oneTwoThree: 23;",
14467                Alignment);
14468 
14469   // Known limitations: ':' is only recognized as a bitfield colon when
14470   // followed by a number.
14471   /*
14472   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
14473                "int a           : 5;",
14474                Alignment);
14475   */
14476 }
14477 
14478 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
14479   FormatStyle Alignment = getLLVMStyle();
14480   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14481   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
14482   verifyFormat("float const a = 5;\n"
14483                "int oneTwoThree = 123;",
14484                Alignment);
14485   verifyFormat("int a = 5;\n"
14486                "float const oneTwoThree = 123;",
14487                Alignment);
14488 
14489   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14490   verifyFormat("float const a = 5;\n"
14491                "int         oneTwoThree = 123;",
14492                Alignment);
14493   verifyFormat("int         a = method();\n"
14494                "float const oneTwoThree = 133;",
14495                Alignment);
14496   verifyFormat("int i = 1, j = 10;\n"
14497                "something = 2000;",
14498                Alignment);
14499   verifyFormat("something = 2000;\n"
14500                "int i = 1, j = 10;\n",
14501                Alignment);
14502   verifyFormat("float      something = 2000;\n"
14503                "double     another = 911;\n"
14504                "int        i = 1, j = 10;\n"
14505                "const int *oneMore = 1;\n"
14506                "unsigned   i = 2;",
14507                Alignment);
14508   verifyFormat("float a = 5;\n"
14509                "int   one = 1;\n"
14510                "method();\n"
14511                "const double       oneTwoThree = 123;\n"
14512                "const unsigned int oneTwo = 12;",
14513                Alignment);
14514   verifyFormat("int      oneTwoThree{0}; // comment\n"
14515                "unsigned oneTwo;         // comment",
14516                Alignment);
14517   verifyFormat("unsigned int *      a;\n"
14518                "int *               b;\n"
14519                "unsigned int Const *c;\n"
14520                "unsigned int const *d;\n"
14521                "unsigned int Const &e;\n"
14522                "unsigned int const &f;",
14523                Alignment);
14524   verifyFormat("Const unsigned int *c;\n"
14525                "const unsigned int *d;\n"
14526                "Const unsigned int &e;\n"
14527                "const unsigned int &f;\n"
14528                "const unsigned      g;\n"
14529                "Const unsigned      h;",
14530                Alignment);
14531   EXPECT_EQ("float const a = 5;\n"
14532             "\n"
14533             "int oneTwoThree = 123;",
14534             format("float const   a = 5;\n"
14535                    "\n"
14536                    "int           oneTwoThree= 123;",
14537                    Alignment));
14538   EXPECT_EQ("float a = 5;\n"
14539             "int   one = 1;\n"
14540             "\n"
14541             "unsigned oneTwoThree = 123;",
14542             format("float    a = 5;\n"
14543                    "int      one = 1;\n"
14544                    "\n"
14545                    "unsigned oneTwoThree = 123;",
14546                    Alignment));
14547   EXPECT_EQ("float a = 5;\n"
14548             "int   one = 1;\n"
14549             "\n"
14550             "unsigned oneTwoThree = 123;\n"
14551             "int      oneTwo = 12;",
14552             format("float    a = 5;\n"
14553                    "int one = 1;\n"
14554                    "\n"
14555                    "unsigned oneTwoThree = 123;\n"
14556                    "int oneTwo = 12;",
14557                    Alignment));
14558   // Function prototype alignment
14559   verifyFormat("int    a();\n"
14560                "double b();",
14561                Alignment);
14562   verifyFormat("int    a(int x);\n"
14563                "double b();",
14564                Alignment);
14565   unsigned OldColumnLimit = Alignment.ColumnLimit;
14566   // We need to set ColumnLimit to zero, in order to stress nested alignments,
14567   // otherwise the function parameters will be re-flowed onto a single line.
14568   Alignment.ColumnLimit = 0;
14569   EXPECT_EQ("int    a(int   x,\n"
14570             "         float y);\n"
14571             "double b(int    x,\n"
14572             "         double y);",
14573             format("int a(int x,\n"
14574                    " float y);\n"
14575                    "double b(int x,\n"
14576                    " double y);",
14577                    Alignment));
14578   // This ensures that function parameters of function declarations are
14579   // correctly indented when their owning functions are indented.
14580   // The failure case here is for 'double y' to not be indented enough.
14581   EXPECT_EQ("double a(int x);\n"
14582             "int    b(int    y,\n"
14583             "         double z);",
14584             format("double a(int x);\n"
14585                    "int b(int y,\n"
14586                    " double z);",
14587                    Alignment));
14588   // Set ColumnLimit low so that we induce wrapping immediately after
14589   // the function name and opening paren.
14590   Alignment.ColumnLimit = 13;
14591   verifyFormat("int function(\n"
14592                "    int  x,\n"
14593                "    bool y);",
14594                Alignment);
14595   Alignment.ColumnLimit = OldColumnLimit;
14596   // Ensure function pointers don't screw up recursive alignment
14597   verifyFormat("int    a(int x, void (*fp)(int y));\n"
14598                "double b();",
14599                Alignment);
14600   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14601   // Ensure recursive alignment is broken by function braces, so that the
14602   // "a = 1" does not align with subsequent assignments inside the function
14603   // body.
14604   verifyFormat("int func(int a = 1) {\n"
14605                "  int b  = 2;\n"
14606                "  int cc = 3;\n"
14607                "}",
14608                Alignment);
14609   verifyFormat("float      something = 2000;\n"
14610                "double     another   = 911;\n"
14611                "int        i = 1, j = 10;\n"
14612                "const int *oneMore = 1;\n"
14613                "unsigned   i       = 2;",
14614                Alignment);
14615   verifyFormat("int      oneTwoThree = {0}; // comment\n"
14616                "unsigned oneTwo      = 0;   // comment",
14617                Alignment);
14618   // Make sure that scope is correctly tracked, in the absence of braces
14619   verifyFormat("for (int i = 0; i < n; i++)\n"
14620                "  j = i;\n"
14621                "double x = 1;\n",
14622                Alignment);
14623   verifyFormat("if (int i = 0)\n"
14624                "  j = i;\n"
14625                "double x = 1;\n",
14626                Alignment);
14627   // Ensure operator[] and operator() are comprehended
14628   verifyFormat("struct test {\n"
14629                "  long long int foo();\n"
14630                "  int           operator[](int a);\n"
14631                "  double        bar();\n"
14632                "};\n",
14633                Alignment);
14634   verifyFormat("struct test {\n"
14635                "  long long int foo();\n"
14636                "  int           operator()(int a);\n"
14637                "  double        bar();\n"
14638                "};\n",
14639                Alignment);
14640   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
14641             "  int const i   = 1;\n"
14642             "  int *     j   = 2;\n"
14643             "  int       big = 10000;\n"
14644             "\n"
14645             "  unsigned oneTwoThree = 123;\n"
14646             "  int      oneTwo      = 12;\n"
14647             "  method();\n"
14648             "  float k  = 2;\n"
14649             "  int   ll = 10000;\n"
14650             "}",
14651             format("void SomeFunction(int parameter= 0) {\n"
14652                    " int const  i= 1;\n"
14653                    "  int *j=2;\n"
14654                    " int big  =  10000;\n"
14655                    "\n"
14656                    "unsigned oneTwoThree  =123;\n"
14657                    "int oneTwo = 12;\n"
14658                    "  method();\n"
14659                    "float k= 2;\n"
14660                    "int ll=10000;\n"
14661                    "}",
14662                    Alignment));
14663   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14664   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
14665   verifyFormat("#define A \\\n"
14666                "  int       aaaa = 12; \\\n"
14667                "  float     b = 23; \\\n"
14668                "  const int ccc = 234; \\\n"
14669                "  unsigned  dddddddddd = 2345;",
14670                Alignment);
14671   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14672   verifyFormat("#define A              \\\n"
14673                "  int       aaaa = 12; \\\n"
14674                "  float     b = 23;    \\\n"
14675                "  const int ccc = 234; \\\n"
14676                "  unsigned  dddddddddd = 2345;",
14677                Alignment);
14678   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
14679   Alignment.ColumnLimit = 30;
14680   verifyFormat("#define A                    \\\n"
14681                "  int       aaaa = 12;       \\\n"
14682                "  float     b = 23;          \\\n"
14683                "  const int ccc = 234;       \\\n"
14684                "  int       dddddddddd = 2345;",
14685                Alignment);
14686   Alignment.ColumnLimit = 80;
14687   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
14688                "k = 4, int l = 5,\n"
14689                "                  int m = 6) {\n"
14690                "  const int j = 10;\n"
14691                "  otherThing = 1;\n"
14692                "}",
14693                Alignment);
14694   verifyFormat("void SomeFunction(int parameter = 0) {\n"
14695                "  int const i = 1;\n"
14696                "  int *     j = 2;\n"
14697                "  int       big = 10000;\n"
14698                "}",
14699                Alignment);
14700   verifyFormat("class C {\n"
14701                "public:\n"
14702                "  int          i = 1;\n"
14703                "  virtual void f() = 0;\n"
14704                "};",
14705                Alignment);
14706   verifyFormat("float i = 1;\n"
14707                "if (SomeType t = getSomething()) {\n"
14708                "}\n"
14709                "const unsigned j = 2;\n"
14710                "int            big = 10000;",
14711                Alignment);
14712   verifyFormat("float j = 7;\n"
14713                "for (int k = 0; k < N; ++k) {\n"
14714                "}\n"
14715                "unsigned j = 2;\n"
14716                "int      big = 10000;\n"
14717                "}",
14718                Alignment);
14719   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14720   verifyFormat("float              i = 1;\n"
14721                "LooooooooooongType loooooooooooooooooooooongVariable\n"
14722                "    = someLooooooooooooooooongFunction();\n"
14723                "int j = 2;",
14724                Alignment);
14725   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
14726   verifyFormat("int                i = 1;\n"
14727                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
14728                "    someLooooooooooooooooongFunction();\n"
14729                "int j = 2;",
14730                Alignment);
14731 
14732   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14733   verifyFormat("auto lambda = []() {\n"
14734                "  auto  ii = 0;\n"
14735                "  float j  = 0;\n"
14736                "  return 0;\n"
14737                "};\n"
14738                "int   i  = 0;\n"
14739                "float i2 = 0;\n"
14740                "auto  v  = type{\n"
14741                "    i = 1,   //\n"
14742                "    (i = 2), //\n"
14743                "    i = 3    //\n"
14744                "};",
14745                Alignment);
14746   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14747 
14748   verifyFormat(
14749       "int      i = 1;\n"
14750       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
14751       "                          loooooooooooooooooooooongParameterB);\n"
14752       "int      j = 2;",
14753       Alignment);
14754 
14755   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
14756   // We expect declarations and assignments to align, as long as it doesn't
14757   // exceed the column limit, starting a new alignment sequence whenever it
14758   // happens.
14759   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14760   Alignment.ColumnLimit = 30;
14761   verifyFormat("float    ii              = 1;\n"
14762                "unsigned j               = 2;\n"
14763                "int someVerylongVariable = 1;\n"
14764                "AnotherLongType  ll = 123456;\n"
14765                "VeryVeryLongType k  = 2;\n"
14766                "int              myvar = 1;",
14767                Alignment);
14768   Alignment.ColumnLimit = 80;
14769   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14770 
14771   verifyFormat(
14772       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
14773       "          typename LongType, typename B>\n"
14774       "auto foo() {}\n",
14775       Alignment);
14776   verifyFormat("float a, b = 1;\n"
14777                "int   c = 2;\n"
14778                "int   dd = 3;\n",
14779                Alignment);
14780   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
14781                "float b[1][] = {{3.f}};\n",
14782                Alignment);
14783   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14784   verifyFormat("float a, b = 1;\n"
14785                "int   c  = 2;\n"
14786                "int   dd = 3;\n",
14787                Alignment);
14788   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
14789                "float b[1][] = {{3.f}};\n",
14790                Alignment);
14791   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14792 
14793   Alignment.ColumnLimit = 30;
14794   Alignment.BinPackParameters = false;
14795   verifyFormat("void foo(float     a,\n"
14796                "         float     b,\n"
14797                "         int       c,\n"
14798                "         uint32_t *d) {\n"
14799                "  int *  e = 0;\n"
14800                "  float  f = 0;\n"
14801                "  double g = 0;\n"
14802                "}\n"
14803                "void bar(ino_t     a,\n"
14804                "         int       b,\n"
14805                "         uint32_t *c,\n"
14806                "         bool      d) {}\n",
14807                Alignment);
14808   Alignment.BinPackParameters = true;
14809   Alignment.ColumnLimit = 80;
14810 
14811   // Bug 33507
14812   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
14813   verifyFormat(
14814       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
14815       "  static const Version verVs2017;\n"
14816       "  return true;\n"
14817       "});\n",
14818       Alignment);
14819   Alignment.PointerAlignment = FormatStyle::PAS_Right;
14820 
14821   // See llvm.org/PR35641
14822   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14823   verifyFormat("int func() { //\n"
14824                "  int      b;\n"
14825                "  unsigned c;\n"
14826                "}",
14827                Alignment);
14828 
14829   // See PR37175
14830   FormatStyle Style = getMozillaStyle();
14831   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14832   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
14833             "foo(int a);",
14834             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
14835 
14836   Alignment.PointerAlignment = FormatStyle::PAS_Left;
14837   verifyFormat("unsigned int*       a;\n"
14838                "int*                b;\n"
14839                "unsigned int Const* c;\n"
14840                "unsigned int const* d;\n"
14841                "unsigned int Const& e;\n"
14842                "unsigned int const& f;",
14843                Alignment);
14844   verifyFormat("Const unsigned int* c;\n"
14845                "const unsigned int* d;\n"
14846                "Const unsigned int& e;\n"
14847                "const unsigned int& f;\n"
14848                "const unsigned      g;\n"
14849                "Const unsigned      h;",
14850                Alignment);
14851 
14852   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
14853   verifyFormat("unsigned int *       a;\n"
14854                "int *                b;\n"
14855                "unsigned int Const * c;\n"
14856                "unsigned int const * d;\n"
14857                "unsigned int Const & e;\n"
14858                "unsigned int const & f;",
14859                Alignment);
14860   verifyFormat("Const unsigned int * c;\n"
14861                "const unsigned int * d;\n"
14862                "Const unsigned int & e;\n"
14863                "const unsigned int & f;\n"
14864                "const unsigned       g;\n"
14865                "Const unsigned       h;",
14866                Alignment);
14867 }
14868 
14869 TEST_F(FormatTest, AlignWithLineBreaks) {
14870   auto Style = getLLVMStyleWithColumns(120);
14871 
14872   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
14873   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
14874   verifyFormat("void foo() {\n"
14875                "  int myVar = 5;\n"
14876                "  double x = 3.14;\n"
14877                "  auto str = \"Hello \"\n"
14878                "             \"World\";\n"
14879                "  auto s = \"Hello \"\n"
14880                "           \"Again\";\n"
14881                "}",
14882                Style);
14883 
14884   // clang-format off
14885   verifyFormat("void foo() {\n"
14886                "  const int capacityBefore = Entries.capacity();\n"
14887                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14888                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14889                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14890                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14891                "}",
14892                Style);
14893   // clang-format on
14894 
14895   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14896   verifyFormat("void foo() {\n"
14897                "  int myVar = 5;\n"
14898                "  double x  = 3.14;\n"
14899                "  auto str  = \"Hello \"\n"
14900                "              \"World\";\n"
14901                "  auto s    = \"Hello \"\n"
14902                "              \"Again\";\n"
14903                "}",
14904                Style);
14905 
14906   // clang-format off
14907   verifyFormat("void foo() {\n"
14908                "  const int capacityBefore = Entries.capacity();\n"
14909                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14910                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14911                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14912                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14913                "}",
14914                Style);
14915   // clang-format on
14916 
14917   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14918   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14919   verifyFormat("void foo() {\n"
14920                "  int    myVar = 5;\n"
14921                "  double x = 3.14;\n"
14922                "  auto   str = \"Hello \"\n"
14923                "               \"World\";\n"
14924                "  auto   s = \"Hello \"\n"
14925                "             \"Again\";\n"
14926                "}",
14927                Style);
14928 
14929   // clang-format off
14930   verifyFormat("void foo() {\n"
14931                "  const int  capacityBefore = Entries.capacity();\n"
14932                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14933                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14934                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14935                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14936                "}",
14937                Style);
14938   // clang-format on
14939 
14940   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14941   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14942 
14943   verifyFormat("void foo() {\n"
14944                "  int    myVar = 5;\n"
14945                "  double x     = 3.14;\n"
14946                "  auto   str   = \"Hello \"\n"
14947                "                 \"World\";\n"
14948                "  auto   s     = \"Hello \"\n"
14949                "                 \"Again\";\n"
14950                "}",
14951                Style);
14952 
14953   // clang-format off
14954   verifyFormat("void foo() {\n"
14955                "  const int  capacityBefore = Entries.capacity();\n"
14956                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14957                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14958                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14959                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14960                "}",
14961                Style);
14962   // clang-format on
14963 }
14964 
14965 TEST_F(FormatTest, LinuxBraceBreaking) {
14966   FormatStyle LinuxBraceStyle = getLLVMStyle();
14967   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
14968   verifyFormat("namespace a\n"
14969                "{\n"
14970                "class A\n"
14971                "{\n"
14972                "  void f()\n"
14973                "  {\n"
14974                "    if (true) {\n"
14975                "      a();\n"
14976                "      b();\n"
14977                "    } else {\n"
14978                "      a();\n"
14979                "    }\n"
14980                "  }\n"
14981                "  void g() { return; }\n"
14982                "};\n"
14983                "struct B {\n"
14984                "  int x;\n"
14985                "};\n"
14986                "} // namespace a\n",
14987                LinuxBraceStyle);
14988   verifyFormat("enum X {\n"
14989                "  Y = 0,\n"
14990                "}\n",
14991                LinuxBraceStyle);
14992   verifyFormat("struct S {\n"
14993                "  int Type;\n"
14994                "  union {\n"
14995                "    int x;\n"
14996                "    double y;\n"
14997                "  } Value;\n"
14998                "  class C\n"
14999                "  {\n"
15000                "    MyFavoriteType Value;\n"
15001                "  } Class;\n"
15002                "}\n",
15003                LinuxBraceStyle);
15004 }
15005 
15006 TEST_F(FormatTest, MozillaBraceBreaking) {
15007   FormatStyle MozillaBraceStyle = getLLVMStyle();
15008   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
15009   MozillaBraceStyle.FixNamespaceComments = false;
15010   verifyFormat("namespace a {\n"
15011                "class A\n"
15012                "{\n"
15013                "  void f()\n"
15014                "  {\n"
15015                "    if (true) {\n"
15016                "      a();\n"
15017                "      b();\n"
15018                "    }\n"
15019                "  }\n"
15020                "  void g() { return; }\n"
15021                "};\n"
15022                "enum E\n"
15023                "{\n"
15024                "  A,\n"
15025                "  // foo\n"
15026                "  B,\n"
15027                "  C\n"
15028                "};\n"
15029                "struct B\n"
15030                "{\n"
15031                "  int x;\n"
15032                "};\n"
15033                "}\n",
15034                MozillaBraceStyle);
15035   verifyFormat("struct S\n"
15036                "{\n"
15037                "  int Type;\n"
15038                "  union\n"
15039                "  {\n"
15040                "    int x;\n"
15041                "    double y;\n"
15042                "  } Value;\n"
15043                "  class C\n"
15044                "  {\n"
15045                "    MyFavoriteType Value;\n"
15046                "  } Class;\n"
15047                "}\n",
15048                MozillaBraceStyle);
15049 }
15050 
15051 TEST_F(FormatTest, StroustrupBraceBreaking) {
15052   FormatStyle StroustrupBraceStyle = getLLVMStyle();
15053   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
15054   verifyFormat("namespace a {\n"
15055                "class A {\n"
15056                "  void f()\n"
15057                "  {\n"
15058                "    if (true) {\n"
15059                "      a();\n"
15060                "      b();\n"
15061                "    }\n"
15062                "  }\n"
15063                "  void g() { return; }\n"
15064                "};\n"
15065                "struct B {\n"
15066                "  int x;\n"
15067                "};\n"
15068                "} // namespace a\n",
15069                StroustrupBraceStyle);
15070 
15071   verifyFormat("void foo()\n"
15072                "{\n"
15073                "  if (a) {\n"
15074                "    a();\n"
15075                "  }\n"
15076                "  else {\n"
15077                "    b();\n"
15078                "  }\n"
15079                "}\n",
15080                StroustrupBraceStyle);
15081 
15082   verifyFormat("#ifdef _DEBUG\n"
15083                "int foo(int i = 0)\n"
15084                "#else\n"
15085                "int foo(int i = 5)\n"
15086                "#endif\n"
15087                "{\n"
15088                "  return i;\n"
15089                "}",
15090                StroustrupBraceStyle);
15091 
15092   verifyFormat("void foo() {}\n"
15093                "void bar()\n"
15094                "#ifdef _DEBUG\n"
15095                "{\n"
15096                "  foo();\n"
15097                "}\n"
15098                "#else\n"
15099                "{\n"
15100                "}\n"
15101                "#endif",
15102                StroustrupBraceStyle);
15103 
15104   verifyFormat("void foobar() { int i = 5; }\n"
15105                "#ifdef _DEBUG\n"
15106                "void bar() {}\n"
15107                "#else\n"
15108                "void bar() { foobar(); }\n"
15109                "#endif",
15110                StroustrupBraceStyle);
15111 }
15112 
15113 TEST_F(FormatTest, AllmanBraceBreaking) {
15114   FormatStyle AllmanBraceStyle = getLLVMStyle();
15115   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
15116 
15117   EXPECT_EQ("namespace a\n"
15118             "{\n"
15119             "void f();\n"
15120             "void g();\n"
15121             "} // namespace a\n",
15122             format("namespace a\n"
15123                    "{\n"
15124                    "void f();\n"
15125                    "void g();\n"
15126                    "}\n",
15127                    AllmanBraceStyle));
15128 
15129   verifyFormat("namespace a\n"
15130                "{\n"
15131                "class A\n"
15132                "{\n"
15133                "  void f()\n"
15134                "  {\n"
15135                "    if (true)\n"
15136                "    {\n"
15137                "      a();\n"
15138                "      b();\n"
15139                "    }\n"
15140                "  }\n"
15141                "  void g() { return; }\n"
15142                "};\n"
15143                "struct B\n"
15144                "{\n"
15145                "  int x;\n"
15146                "};\n"
15147                "union C\n"
15148                "{\n"
15149                "};\n"
15150                "} // namespace a",
15151                AllmanBraceStyle);
15152 
15153   verifyFormat("void f()\n"
15154                "{\n"
15155                "  if (true)\n"
15156                "  {\n"
15157                "    a();\n"
15158                "  }\n"
15159                "  else if (false)\n"
15160                "  {\n"
15161                "    b();\n"
15162                "  }\n"
15163                "  else\n"
15164                "  {\n"
15165                "    c();\n"
15166                "  }\n"
15167                "}\n",
15168                AllmanBraceStyle);
15169 
15170   verifyFormat("void f()\n"
15171                "{\n"
15172                "  for (int i = 0; i < 10; ++i)\n"
15173                "  {\n"
15174                "    a();\n"
15175                "  }\n"
15176                "  while (false)\n"
15177                "  {\n"
15178                "    b();\n"
15179                "  }\n"
15180                "  do\n"
15181                "  {\n"
15182                "    c();\n"
15183                "  } while (false)\n"
15184                "}\n",
15185                AllmanBraceStyle);
15186 
15187   verifyFormat("void f(int a)\n"
15188                "{\n"
15189                "  switch (a)\n"
15190                "  {\n"
15191                "  case 0:\n"
15192                "    break;\n"
15193                "  case 1:\n"
15194                "  {\n"
15195                "    break;\n"
15196                "  }\n"
15197                "  case 2:\n"
15198                "  {\n"
15199                "  }\n"
15200                "  break;\n"
15201                "  default:\n"
15202                "    break;\n"
15203                "  }\n"
15204                "}\n",
15205                AllmanBraceStyle);
15206 
15207   verifyFormat("enum X\n"
15208                "{\n"
15209                "  Y = 0,\n"
15210                "}\n",
15211                AllmanBraceStyle);
15212   verifyFormat("enum X\n"
15213                "{\n"
15214                "  Y = 0\n"
15215                "}\n",
15216                AllmanBraceStyle);
15217 
15218   verifyFormat("@interface BSApplicationController ()\n"
15219                "{\n"
15220                "@private\n"
15221                "  id _extraIvar;\n"
15222                "}\n"
15223                "@end\n",
15224                AllmanBraceStyle);
15225 
15226   verifyFormat("#ifdef _DEBUG\n"
15227                "int foo(int i = 0)\n"
15228                "#else\n"
15229                "int foo(int i = 5)\n"
15230                "#endif\n"
15231                "{\n"
15232                "  return i;\n"
15233                "}",
15234                AllmanBraceStyle);
15235 
15236   verifyFormat("void foo() {}\n"
15237                "void bar()\n"
15238                "#ifdef _DEBUG\n"
15239                "{\n"
15240                "  foo();\n"
15241                "}\n"
15242                "#else\n"
15243                "{\n"
15244                "}\n"
15245                "#endif",
15246                AllmanBraceStyle);
15247 
15248   verifyFormat("void foobar() { int i = 5; }\n"
15249                "#ifdef _DEBUG\n"
15250                "void bar() {}\n"
15251                "#else\n"
15252                "void bar() { foobar(); }\n"
15253                "#endif",
15254                AllmanBraceStyle);
15255 
15256   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
15257             FormatStyle::SLS_All);
15258 
15259   verifyFormat("[](int i) { return i + 2; };\n"
15260                "[](int i, int j)\n"
15261                "{\n"
15262                "  auto x = i + j;\n"
15263                "  auto y = i * j;\n"
15264                "  return x ^ y;\n"
15265                "};\n"
15266                "void foo()\n"
15267                "{\n"
15268                "  auto shortLambda = [](int i) { return i + 2; };\n"
15269                "  auto longLambda = [](int i, int j)\n"
15270                "  {\n"
15271                "    auto x = i + j;\n"
15272                "    auto y = i * j;\n"
15273                "    return x ^ y;\n"
15274                "  };\n"
15275                "}",
15276                AllmanBraceStyle);
15277 
15278   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
15279 
15280   verifyFormat("[](int i)\n"
15281                "{\n"
15282                "  return i + 2;\n"
15283                "};\n"
15284                "[](int i, int j)\n"
15285                "{\n"
15286                "  auto x = i + j;\n"
15287                "  auto y = i * j;\n"
15288                "  return x ^ y;\n"
15289                "};\n"
15290                "void foo()\n"
15291                "{\n"
15292                "  auto shortLambda = [](int i)\n"
15293                "  {\n"
15294                "    return i + 2;\n"
15295                "  };\n"
15296                "  auto longLambda = [](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                "}",
15303                AllmanBraceStyle);
15304 
15305   // Reset
15306   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
15307 
15308   // This shouldn't affect ObjC blocks..
15309   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
15310                "  // ...\n"
15311                "  int i;\n"
15312                "}];",
15313                AllmanBraceStyle);
15314   verifyFormat("void (^block)(void) = ^{\n"
15315                "  // ...\n"
15316                "  int i;\n"
15317                "};",
15318                AllmanBraceStyle);
15319   // .. or dict literals.
15320   verifyFormat("void f()\n"
15321                "{\n"
15322                "  // ...\n"
15323                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
15324                "}",
15325                AllmanBraceStyle);
15326   verifyFormat("void f()\n"
15327                "{\n"
15328                "  // ...\n"
15329                "  [object someMethod:@{a : @\"b\"}];\n"
15330                "}",
15331                AllmanBraceStyle);
15332   verifyFormat("int f()\n"
15333                "{ // comment\n"
15334                "  return 42;\n"
15335                "}",
15336                AllmanBraceStyle);
15337 
15338   AllmanBraceStyle.ColumnLimit = 19;
15339   verifyFormat("void f() { int i; }", AllmanBraceStyle);
15340   AllmanBraceStyle.ColumnLimit = 18;
15341   verifyFormat("void f()\n"
15342                "{\n"
15343                "  int i;\n"
15344                "}",
15345                AllmanBraceStyle);
15346   AllmanBraceStyle.ColumnLimit = 80;
15347 
15348   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
15349   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
15350       FormatStyle::SIS_WithoutElse;
15351   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
15352   verifyFormat("void f(bool b)\n"
15353                "{\n"
15354                "  if (b)\n"
15355                "  {\n"
15356                "    return;\n"
15357                "  }\n"
15358                "}\n",
15359                BreakBeforeBraceShortIfs);
15360   verifyFormat("void f(bool b)\n"
15361                "{\n"
15362                "  if constexpr (b)\n"
15363                "  {\n"
15364                "    return;\n"
15365                "  }\n"
15366                "}\n",
15367                BreakBeforeBraceShortIfs);
15368   verifyFormat("void f(bool b)\n"
15369                "{\n"
15370                "  if CONSTEXPR (b)\n"
15371                "  {\n"
15372                "    return;\n"
15373                "  }\n"
15374                "}\n",
15375                BreakBeforeBraceShortIfs);
15376   verifyFormat("void f(bool b)\n"
15377                "{\n"
15378                "  if (b) return;\n"
15379                "}\n",
15380                BreakBeforeBraceShortIfs);
15381   verifyFormat("void f(bool b)\n"
15382                "{\n"
15383                "  if constexpr (b) return;\n"
15384                "}\n",
15385                BreakBeforeBraceShortIfs);
15386   verifyFormat("void f(bool b)\n"
15387                "{\n"
15388                "  if CONSTEXPR (b) return;\n"
15389                "}\n",
15390                BreakBeforeBraceShortIfs);
15391   verifyFormat("void f(bool b)\n"
15392                "{\n"
15393                "  while (b)\n"
15394                "  {\n"
15395                "    return;\n"
15396                "  }\n"
15397                "}\n",
15398                BreakBeforeBraceShortIfs);
15399 }
15400 
15401 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
15402   FormatStyle WhitesmithsBraceStyle = getLLVMStyle();
15403   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
15404 
15405   // Make a few changes to the style for testing purposes
15406   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
15407       FormatStyle::SFS_Empty;
15408   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
15409   WhitesmithsBraceStyle.ColumnLimit = 0;
15410 
15411   // FIXME: this test case can't decide whether there should be a blank line
15412   // after the ~D() line or not. It adds one if one doesn't exist in the test
15413   // and it removes the line if one exists.
15414   /*
15415   verifyFormat("class A;\n"
15416                "namespace B\n"
15417                "  {\n"
15418                "class C;\n"
15419                "// Comment\n"
15420                "class D\n"
15421                "  {\n"
15422                "public:\n"
15423                "  D();\n"
15424                "  ~D() {}\n"
15425                "private:\n"
15426                "  enum E\n"
15427                "    {\n"
15428                "    F\n"
15429                "    }\n"
15430                "  };\n"
15431                "  } // namespace B\n",
15432                WhitesmithsBraceStyle);
15433   */
15434 
15435   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
15436   verifyFormat("namespace a\n"
15437                "  {\n"
15438                "class A\n"
15439                "  {\n"
15440                "  void f()\n"
15441                "    {\n"
15442                "    if (true)\n"
15443                "      {\n"
15444                "      a();\n"
15445                "      b();\n"
15446                "      }\n"
15447                "    }\n"
15448                "  void g()\n"
15449                "    {\n"
15450                "    return;\n"
15451                "    }\n"
15452                "  };\n"
15453                "struct B\n"
15454                "  {\n"
15455                "  int x;\n"
15456                "  };\n"
15457                "  } // namespace a",
15458                WhitesmithsBraceStyle);
15459 
15460   verifyFormat("namespace a\n"
15461                "  {\n"
15462                "namespace b\n"
15463                "  {\n"
15464                "class A\n"
15465                "  {\n"
15466                "  void f()\n"
15467                "    {\n"
15468                "    if (true)\n"
15469                "      {\n"
15470                "      a();\n"
15471                "      b();\n"
15472                "      }\n"
15473                "    }\n"
15474                "  void g()\n"
15475                "    {\n"
15476                "    return;\n"
15477                "    }\n"
15478                "  };\n"
15479                "struct B\n"
15480                "  {\n"
15481                "  int x;\n"
15482                "  };\n"
15483                "  } // namespace b\n"
15484                "  } // namespace a",
15485                WhitesmithsBraceStyle);
15486 
15487   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
15488   verifyFormat("namespace a\n"
15489                "  {\n"
15490                "namespace b\n"
15491                "  {\n"
15492                "  class A\n"
15493                "    {\n"
15494                "    void f()\n"
15495                "      {\n"
15496                "      if (true)\n"
15497                "        {\n"
15498                "        a();\n"
15499                "        b();\n"
15500                "        }\n"
15501                "      }\n"
15502                "    void g()\n"
15503                "      {\n"
15504                "      return;\n"
15505                "      }\n"
15506                "    };\n"
15507                "  struct B\n"
15508                "    {\n"
15509                "    int x;\n"
15510                "    };\n"
15511                "  } // namespace b\n"
15512                "  } // namespace a",
15513                WhitesmithsBraceStyle);
15514 
15515   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
15516   verifyFormat("namespace a\n"
15517                "  {\n"
15518                "  namespace b\n"
15519                "    {\n"
15520                "    class A\n"
15521                "      {\n"
15522                "      void f()\n"
15523                "        {\n"
15524                "        if (true)\n"
15525                "          {\n"
15526                "          a();\n"
15527                "          b();\n"
15528                "          }\n"
15529                "        }\n"
15530                "      void g()\n"
15531                "        {\n"
15532                "        return;\n"
15533                "        }\n"
15534                "      };\n"
15535                "    struct B\n"
15536                "      {\n"
15537                "      int x;\n"
15538                "      };\n"
15539                "    } // namespace b\n"
15540                "  }   // namespace a",
15541                WhitesmithsBraceStyle);
15542 
15543   verifyFormat("void f()\n"
15544                "  {\n"
15545                "  if (true)\n"
15546                "    {\n"
15547                "    a();\n"
15548                "    }\n"
15549                "  else if (false)\n"
15550                "    {\n"
15551                "    b();\n"
15552                "    }\n"
15553                "  else\n"
15554                "    {\n"
15555                "    c();\n"
15556                "    }\n"
15557                "  }\n",
15558                WhitesmithsBraceStyle);
15559 
15560   verifyFormat("void f()\n"
15561                "  {\n"
15562                "  for (int i = 0; i < 10; ++i)\n"
15563                "    {\n"
15564                "    a();\n"
15565                "    }\n"
15566                "  while (false)\n"
15567                "    {\n"
15568                "    b();\n"
15569                "    }\n"
15570                "  do\n"
15571                "    {\n"
15572                "    c();\n"
15573                "    } while (false)\n"
15574                "  }\n",
15575                WhitesmithsBraceStyle);
15576 
15577   WhitesmithsBraceStyle.IndentCaseLabels = true;
15578   verifyFormat("void switchTest1(int a)\n"
15579                "  {\n"
15580                "  switch (a)\n"
15581                "    {\n"
15582                "    case 2:\n"
15583                "      {\n"
15584                "      }\n"
15585                "      break;\n"
15586                "    }\n"
15587                "  }\n",
15588                WhitesmithsBraceStyle);
15589 
15590   verifyFormat("void switchTest2(int a)\n"
15591                "  {\n"
15592                "  switch (a)\n"
15593                "    {\n"
15594                "    case 0:\n"
15595                "      break;\n"
15596                "    case 1:\n"
15597                "      {\n"
15598                "      break;\n"
15599                "      }\n"
15600                "    case 2:\n"
15601                "      {\n"
15602                "      }\n"
15603                "      break;\n"
15604                "    default:\n"
15605                "      break;\n"
15606                "    }\n"
15607                "  }\n",
15608                WhitesmithsBraceStyle);
15609 
15610   verifyFormat("void switchTest3(int a)\n"
15611                "  {\n"
15612                "  switch (a)\n"
15613                "    {\n"
15614                "    case 0:\n"
15615                "      {\n"
15616                "      foo(x);\n"
15617                "      }\n"
15618                "      break;\n"
15619                "    default:\n"
15620                "      {\n"
15621                "      foo(1);\n"
15622                "      }\n"
15623                "      break;\n"
15624                "    }\n"
15625                "  }\n",
15626                WhitesmithsBraceStyle);
15627 
15628   WhitesmithsBraceStyle.IndentCaseLabels = false;
15629 
15630   verifyFormat("void switchTest4(int a)\n"
15631                "  {\n"
15632                "  switch (a)\n"
15633                "    {\n"
15634                "  case 2:\n"
15635                "    {\n"
15636                "    }\n"
15637                "    break;\n"
15638                "    }\n"
15639                "  }\n",
15640                WhitesmithsBraceStyle);
15641 
15642   verifyFormat("void switchTest5(int a)\n"
15643                "  {\n"
15644                "  switch (a)\n"
15645                "    {\n"
15646                "  case 0:\n"
15647                "    break;\n"
15648                "  case 1:\n"
15649                "    {\n"
15650                "    foo();\n"
15651                "    break;\n"
15652                "    }\n"
15653                "  case 2:\n"
15654                "    {\n"
15655                "    }\n"
15656                "    break;\n"
15657                "  default:\n"
15658                "    break;\n"
15659                "    }\n"
15660                "  }\n",
15661                WhitesmithsBraceStyle);
15662 
15663   verifyFormat("void switchTest6(int a)\n"
15664                "  {\n"
15665                "  switch (a)\n"
15666                "    {\n"
15667                "  case 0:\n"
15668                "    {\n"
15669                "    foo(x);\n"
15670                "    }\n"
15671                "    break;\n"
15672                "  default:\n"
15673                "    {\n"
15674                "    foo(1);\n"
15675                "    }\n"
15676                "    break;\n"
15677                "    }\n"
15678                "  }\n",
15679                WhitesmithsBraceStyle);
15680 
15681   verifyFormat("enum X\n"
15682                "  {\n"
15683                "  Y = 0, // testing\n"
15684                "  }\n",
15685                WhitesmithsBraceStyle);
15686 
15687   verifyFormat("enum X\n"
15688                "  {\n"
15689                "  Y = 0\n"
15690                "  }\n",
15691                WhitesmithsBraceStyle);
15692   verifyFormat("enum X\n"
15693                "  {\n"
15694                "  Y = 0,\n"
15695                "  Z = 1\n"
15696                "  };\n",
15697                WhitesmithsBraceStyle);
15698 
15699   verifyFormat("@interface BSApplicationController ()\n"
15700                "  {\n"
15701                "@private\n"
15702                "  id _extraIvar;\n"
15703                "  }\n"
15704                "@end\n",
15705                WhitesmithsBraceStyle);
15706 
15707   verifyFormat("#ifdef _DEBUG\n"
15708                "int foo(int i = 0)\n"
15709                "#else\n"
15710                "int foo(int i = 5)\n"
15711                "#endif\n"
15712                "  {\n"
15713                "  return i;\n"
15714                "  }",
15715                WhitesmithsBraceStyle);
15716 
15717   verifyFormat("void foo() {}\n"
15718                "void bar()\n"
15719                "#ifdef _DEBUG\n"
15720                "  {\n"
15721                "  foo();\n"
15722                "  }\n"
15723                "#else\n"
15724                "  {\n"
15725                "  }\n"
15726                "#endif",
15727                WhitesmithsBraceStyle);
15728 
15729   verifyFormat("void foobar()\n"
15730                "  {\n"
15731                "  int i = 5;\n"
15732                "  }\n"
15733                "#ifdef _DEBUG\n"
15734                "void bar()\n"
15735                "  {\n"
15736                "  }\n"
15737                "#else\n"
15738                "void bar()\n"
15739                "  {\n"
15740                "  foobar();\n"
15741                "  }\n"
15742                "#endif",
15743                WhitesmithsBraceStyle);
15744 
15745   // This shouldn't affect ObjC blocks..
15746   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
15747                "  // ...\n"
15748                "  int i;\n"
15749                "}];",
15750                WhitesmithsBraceStyle);
15751   verifyFormat("void (^block)(void) = ^{\n"
15752                "  // ...\n"
15753                "  int i;\n"
15754                "};",
15755                WhitesmithsBraceStyle);
15756   // .. or dict literals.
15757   verifyFormat("void f()\n"
15758                "  {\n"
15759                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
15760                "  }",
15761                WhitesmithsBraceStyle);
15762 
15763   verifyFormat("int f()\n"
15764                "  { // comment\n"
15765                "  return 42;\n"
15766                "  }",
15767                WhitesmithsBraceStyle);
15768 
15769   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
15770   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
15771       FormatStyle::SIS_Always;
15772   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
15773   verifyFormat("void f(bool b)\n"
15774                "  {\n"
15775                "  if (b)\n"
15776                "    {\n"
15777                "    return;\n"
15778                "    }\n"
15779                "  }\n",
15780                BreakBeforeBraceShortIfs);
15781   verifyFormat("void f(bool b)\n"
15782                "  {\n"
15783                "  if (b) return;\n"
15784                "  }\n",
15785                BreakBeforeBraceShortIfs);
15786   verifyFormat("void f(bool b)\n"
15787                "  {\n"
15788                "  while (b)\n"
15789                "    {\n"
15790                "    return;\n"
15791                "    }\n"
15792                "  }\n",
15793                BreakBeforeBraceShortIfs);
15794 }
15795 
15796 TEST_F(FormatTest, GNUBraceBreaking) {
15797   FormatStyle GNUBraceStyle = getLLVMStyle();
15798   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
15799   verifyFormat("namespace a\n"
15800                "{\n"
15801                "class A\n"
15802                "{\n"
15803                "  void f()\n"
15804                "  {\n"
15805                "    int a;\n"
15806                "    {\n"
15807                "      int b;\n"
15808                "    }\n"
15809                "    if (true)\n"
15810                "      {\n"
15811                "        a();\n"
15812                "        b();\n"
15813                "      }\n"
15814                "  }\n"
15815                "  void g() { return; }\n"
15816                "}\n"
15817                "} // namespace a",
15818                GNUBraceStyle);
15819 
15820   verifyFormat("void f()\n"
15821                "{\n"
15822                "  if (true)\n"
15823                "    {\n"
15824                "      a();\n"
15825                "    }\n"
15826                "  else if (false)\n"
15827                "    {\n"
15828                "      b();\n"
15829                "    }\n"
15830                "  else\n"
15831                "    {\n"
15832                "      c();\n"
15833                "    }\n"
15834                "}\n",
15835                GNUBraceStyle);
15836 
15837   verifyFormat("void f()\n"
15838                "{\n"
15839                "  for (int i = 0; i < 10; ++i)\n"
15840                "    {\n"
15841                "      a();\n"
15842                "    }\n"
15843                "  while (false)\n"
15844                "    {\n"
15845                "      b();\n"
15846                "    }\n"
15847                "  do\n"
15848                "    {\n"
15849                "      c();\n"
15850                "    }\n"
15851                "  while (false);\n"
15852                "}\n",
15853                GNUBraceStyle);
15854 
15855   verifyFormat("void f(int a)\n"
15856                "{\n"
15857                "  switch (a)\n"
15858                "    {\n"
15859                "    case 0:\n"
15860                "      break;\n"
15861                "    case 1:\n"
15862                "      {\n"
15863                "        break;\n"
15864                "      }\n"
15865                "    case 2:\n"
15866                "      {\n"
15867                "      }\n"
15868                "      break;\n"
15869                "    default:\n"
15870                "      break;\n"
15871                "    }\n"
15872                "}\n",
15873                GNUBraceStyle);
15874 
15875   verifyFormat("enum X\n"
15876                "{\n"
15877                "  Y = 0,\n"
15878                "}\n",
15879                GNUBraceStyle);
15880 
15881   verifyFormat("@interface BSApplicationController ()\n"
15882                "{\n"
15883                "@private\n"
15884                "  id _extraIvar;\n"
15885                "}\n"
15886                "@end\n",
15887                GNUBraceStyle);
15888 
15889   verifyFormat("#ifdef _DEBUG\n"
15890                "int foo(int i = 0)\n"
15891                "#else\n"
15892                "int foo(int i = 5)\n"
15893                "#endif\n"
15894                "{\n"
15895                "  return i;\n"
15896                "}",
15897                GNUBraceStyle);
15898 
15899   verifyFormat("void foo() {}\n"
15900                "void bar()\n"
15901                "#ifdef _DEBUG\n"
15902                "{\n"
15903                "  foo();\n"
15904                "}\n"
15905                "#else\n"
15906                "{\n"
15907                "}\n"
15908                "#endif",
15909                GNUBraceStyle);
15910 
15911   verifyFormat("void foobar() { int i = 5; }\n"
15912                "#ifdef _DEBUG\n"
15913                "void bar() {}\n"
15914                "#else\n"
15915                "void bar() { foobar(); }\n"
15916                "#endif",
15917                GNUBraceStyle);
15918 }
15919 
15920 TEST_F(FormatTest, WebKitBraceBreaking) {
15921   FormatStyle WebKitBraceStyle = getLLVMStyle();
15922   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
15923   WebKitBraceStyle.FixNamespaceComments = false;
15924   verifyFormat("namespace a {\n"
15925                "class A {\n"
15926                "  void f()\n"
15927                "  {\n"
15928                "    if (true) {\n"
15929                "      a();\n"
15930                "      b();\n"
15931                "    }\n"
15932                "  }\n"
15933                "  void g() { return; }\n"
15934                "};\n"
15935                "enum E {\n"
15936                "  A,\n"
15937                "  // foo\n"
15938                "  B,\n"
15939                "  C\n"
15940                "};\n"
15941                "struct B {\n"
15942                "  int x;\n"
15943                "};\n"
15944                "}\n",
15945                WebKitBraceStyle);
15946   verifyFormat("struct S {\n"
15947                "  int Type;\n"
15948                "  union {\n"
15949                "    int x;\n"
15950                "    double y;\n"
15951                "  } Value;\n"
15952                "  class C {\n"
15953                "    MyFavoriteType Value;\n"
15954                "  } Class;\n"
15955                "};\n",
15956                WebKitBraceStyle);
15957 }
15958 
15959 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
15960   verifyFormat("void f() {\n"
15961                "  try {\n"
15962                "  } catch (const Exception &e) {\n"
15963                "  }\n"
15964                "}\n",
15965                getLLVMStyle());
15966 }
15967 
15968 TEST_F(FormatTest, UnderstandsPragmas) {
15969   verifyFormat("#pragma omp reduction(| : var)");
15970   verifyFormat("#pragma omp reduction(+ : var)");
15971 
15972   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
15973             "(including parentheses).",
15974             format("#pragma    mark   Any non-hyphenated or hyphenated string "
15975                    "(including parentheses)."));
15976 }
15977 
15978 TEST_F(FormatTest, UnderstandPragmaOption) {
15979   verifyFormat("#pragma option -C -A");
15980 
15981   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
15982 }
15983 
15984 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
15985   FormatStyle Style = getLLVMStyle();
15986   Style.ColumnLimit = 20;
15987 
15988   // See PR41213
15989   EXPECT_EQ("/*\n"
15990             " *\t9012345\n"
15991             " * /8901\n"
15992             " */",
15993             format("/*\n"
15994                    " *\t9012345 /8901\n"
15995                    " */",
15996                    Style));
15997   EXPECT_EQ("/*\n"
15998             " *345678\n"
15999             " *\t/8901\n"
16000             " */",
16001             format("/*\n"
16002                    " *345678\t/8901\n"
16003                    " */",
16004                    Style));
16005 
16006   verifyFormat("int a; // the\n"
16007                "       // comment",
16008                Style);
16009   EXPECT_EQ("int a; /* first line\n"
16010             "        * second\n"
16011             "        * line third\n"
16012             "        * line\n"
16013             "        */",
16014             format("int a; /* first line\n"
16015                    "        * second\n"
16016                    "        * line third\n"
16017                    "        * line\n"
16018                    "        */",
16019                    Style));
16020   EXPECT_EQ("int a; // first line\n"
16021             "       // second\n"
16022             "       // line third\n"
16023             "       // line",
16024             format("int a; // first line\n"
16025                    "       // second line\n"
16026                    "       // third line",
16027                    Style));
16028 
16029   Style.PenaltyExcessCharacter = 90;
16030   verifyFormat("int a; // the comment", Style);
16031   EXPECT_EQ("int a; // the comment\n"
16032             "       // aaa",
16033             format("int a; // the comment aaa", Style));
16034   EXPECT_EQ("int a; /* first line\n"
16035             "        * second line\n"
16036             "        * third line\n"
16037             "        */",
16038             format("int a; /* first line\n"
16039                    "        * second line\n"
16040                    "        * third line\n"
16041                    "        */",
16042                    Style));
16043   EXPECT_EQ("int a; // first line\n"
16044             "       // second line\n"
16045             "       // third line",
16046             format("int a; // first line\n"
16047                    "       // second line\n"
16048                    "       // third line",
16049                    Style));
16050   // FIXME: Investigate why this is not getting the same layout as the test
16051   // above.
16052   EXPECT_EQ("int a; /* first line\n"
16053             "        * second line\n"
16054             "        * third line\n"
16055             "        */",
16056             format("int a; /* first line second line third line"
16057                    "\n*/",
16058                    Style));
16059 
16060   EXPECT_EQ("// foo bar baz bazfoo\n"
16061             "// foo bar foo bar\n",
16062             format("// foo bar baz bazfoo\n"
16063                    "// foo bar foo           bar\n",
16064                    Style));
16065   EXPECT_EQ("// foo bar baz bazfoo\n"
16066             "// foo bar foo bar\n",
16067             format("// foo bar baz      bazfoo\n"
16068                    "// foo            bar foo bar\n",
16069                    Style));
16070 
16071   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
16072   // next one.
16073   EXPECT_EQ("// foo bar baz bazfoo\n"
16074             "// bar foo bar\n",
16075             format("// foo bar baz      bazfoo bar\n"
16076                    "// foo            bar\n",
16077                    Style));
16078 
16079   EXPECT_EQ("// foo bar baz bazfoo\n"
16080             "// foo bar baz bazfoo\n"
16081             "// bar foo bar\n",
16082             format("// foo bar baz      bazfoo\n"
16083                    "// foo bar baz      bazfoo bar\n"
16084                    "// foo bar\n",
16085                    Style));
16086 
16087   EXPECT_EQ("// foo bar baz bazfoo\n"
16088             "// foo bar baz bazfoo\n"
16089             "// bar foo bar\n",
16090             format("// foo bar baz      bazfoo\n"
16091                    "// foo bar baz      bazfoo bar\n"
16092                    "// foo           bar\n",
16093                    Style));
16094 
16095   // Make sure we do not keep protruding characters if strict mode reflow is
16096   // cheaper than keeping protruding characters.
16097   Style.ColumnLimit = 21;
16098   EXPECT_EQ(
16099       "// foo foo foo foo\n"
16100       "// foo foo foo foo\n"
16101       "// foo foo foo foo\n",
16102       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
16103 
16104   EXPECT_EQ("int a = /* long block\n"
16105             "           comment */\n"
16106             "    42;",
16107             format("int a = /* long block comment */ 42;", Style));
16108 }
16109 
16110 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
16111   for (size_t i = 1; i < Styles.size(); ++i)                                   \
16112   EXPECT_EQ(Styles[0], Styles[i])                                              \
16113       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
16114 
16115 TEST_F(FormatTest, GetsPredefinedStyleByName) {
16116   SmallVector<FormatStyle, 3> Styles;
16117   Styles.resize(3);
16118 
16119   Styles[0] = getLLVMStyle();
16120   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
16121   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
16122   EXPECT_ALL_STYLES_EQUAL(Styles);
16123 
16124   Styles[0] = getGoogleStyle();
16125   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
16126   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
16127   EXPECT_ALL_STYLES_EQUAL(Styles);
16128 
16129   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
16130   EXPECT_TRUE(
16131       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
16132   EXPECT_TRUE(
16133       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
16134   EXPECT_ALL_STYLES_EQUAL(Styles);
16135 
16136   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
16137   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
16138   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
16139   EXPECT_ALL_STYLES_EQUAL(Styles);
16140 
16141   Styles[0] = getMozillaStyle();
16142   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
16143   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
16144   EXPECT_ALL_STYLES_EQUAL(Styles);
16145 
16146   Styles[0] = getWebKitStyle();
16147   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
16148   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
16149   EXPECT_ALL_STYLES_EQUAL(Styles);
16150 
16151   Styles[0] = getGNUStyle();
16152   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
16153   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
16154   EXPECT_ALL_STYLES_EQUAL(Styles);
16155 
16156   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
16157 }
16158 
16159 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
16160   SmallVector<FormatStyle, 8> Styles;
16161   Styles.resize(2);
16162 
16163   Styles[0] = getGoogleStyle();
16164   Styles[1] = getLLVMStyle();
16165   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
16166   EXPECT_ALL_STYLES_EQUAL(Styles);
16167 
16168   Styles.resize(5);
16169   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
16170   Styles[1] = getLLVMStyle();
16171   Styles[1].Language = FormatStyle::LK_JavaScript;
16172   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
16173 
16174   Styles[2] = getLLVMStyle();
16175   Styles[2].Language = FormatStyle::LK_JavaScript;
16176   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
16177                                   "BasedOnStyle: Google",
16178                                   &Styles[2])
16179                    .value());
16180 
16181   Styles[3] = getLLVMStyle();
16182   Styles[3].Language = FormatStyle::LK_JavaScript;
16183   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
16184                                   "Language: JavaScript",
16185                                   &Styles[3])
16186                    .value());
16187 
16188   Styles[4] = getLLVMStyle();
16189   Styles[4].Language = FormatStyle::LK_JavaScript;
16190   EXPECT_EQ(0, parseConfiguration("---\n"
16191                                   "BasedOnStyle: LLVM\n"
16192                                   "IndentWidth: 123\n"
16193                                   "---\n"
16194                                   "BasedOnStyle: Google\n"
16195                                   "Language: JavaScript",
16196                                   &Styles[4])
16197                    .value());
16198   EXPECT_ALL_STYLES_EQUAL(Styles);
16199 }
16200 
16201 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
16202   Style.FIELD = false;                                                         \
16203   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
16204   EXPECT_TRUE(Style.FIELD);                                                    \
16205   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
16206   EXPECT_FALSE(Style.FIELD);
16207 
16208 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
16209 
16210 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
16211   Style.STRUCT.FIELD = false;                                                  \
16212   EXPECT_EQ(0,                                                                 \
16213             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
16214                 .value());                                                     \
16215   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
16216   EXPECT_EQ(0,                                                                 \
16217             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
16218                 .value());                                                     \
16219   EXPECT_FALSE(Style.STRUCT.FIELD);
16220 
16221 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
16222   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
16223 
16224 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
16225   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
16226   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
16227   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
16228 
16229 TEST_F(FormatTest, ParsesConfigurationBools) {
16230   FormatStyle Style = {};
16231   Style.Language = FormatStyle::LK_Cpp;
16232   CHECK_PARSE_BOOL(AlignTrailingComments);
16233   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
16234   CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine);
16235   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
16236   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
16237   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
16238   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
16239   CHECK_PARSE_BOOL(BinPackArguments);
16240   CHECK_PARSE_BOOL(BinPackParameters);
16241   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
16242   CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
16243   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
16244   CHECK_PARSE_BOOL(BreakStringLiterals);
16245   CHECK_PARSE_BOOL(CompactNamespaces);
16246   CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
16247   CHECK_PARSE_BOOL(DeriveLineEnding);
16248   CHECK_PARSE_BOOL(DerivePointerAlignment);
16249   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
16250   CHECK_PARSE_BOOL(DisableFormat);
16251   CHECK_PARSE_BOOL(IndentAccessModifiers);
16252   CHECK_PARSE_BOOL(IndentCaseLabels);
16253   CHECK_PARSE_BOOL(IndentCaseBlocks);
16254   CHECK_PARSE_BOOL(IndentGotoLabels);
16255   CHECK_PARSE_BOOL(IndentRequires);
16256   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
16257   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
16258   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
16259   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
16260   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
16261   CHECK_PARSE_BOOL(ReflowComments);
16262   CHECK_PARSE_BOOL(SortUsingDeclarations);
16263   CHECK_PARSE_BOOL(SpacesInParentheses);
16264   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
16265   CHECK_PARSE_BOOL(SpacesInAngles);
16266   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
16267   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
16268   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
16269   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
16270   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
16271   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
16272   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
16273   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
16274   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
16275   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
16276   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
16277   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
16278   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
16279   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
16280   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
16281   CHECK_PARSE_BOOL(UseCRLF);
16282 
16283   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
16284   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
16285   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
16286   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
16287   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
16288   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
16289   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
16290   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
16291   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
16292   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
16293   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
16294   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
16295   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
16296   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
16297   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
16298   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
16299   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
16300 }
16301 
16302 #undef CHECK_PARSE_BOOL
16303 
16304 TEST_F(FormatTest, ParsesConfiguration) {
16305   FormatStyle Style = {};
16306   Style.Language = FormatStyle::LK_Cpp;
16307   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
16308   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
16309               ConstructorInitializerIndentWidth, 1234u);
16310   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
16311   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
16312   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
16313   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
16314   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
16315               PenaltyBreakBeforeFirstCallParameter, 1234u);
16316   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
16317               PenaltyBreakTemplateDeclaration, 1234u);
16318   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
16319   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
16320               PenaltyReturnTypeOnItsOwnLine, 1234u);
16321   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
16322               SpacesBeforeTrailingComments, 1234u);
16323   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
16324   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
16325   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
16326 
16327   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16328   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
16329               FormatStyle::ACS_None);
16330   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
16331               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
16332   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
16333               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
16334   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
16335               AlignConsecutiveAssignments,
16336               FormatStyle::ACS_AcrossEmptyLinesAndComments);
16337   // For backwards compability, false / true should still parse
16338   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
16339               FormatStyle::ACS_None);
16340   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
16341               FormatStyle::ACS_Consecutive);
16342 
16343   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
16344   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
16345               FormatStyle::ACS_None);
16346   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
16347               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
16348   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
16349               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
16350   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
16351               AlignConsecutiveBitFields,
16352               FormatStyle::ACS_AcrossEmptyLinesAndComments);
16353   // For backwards compability, false / true should still parse
16354   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
16355               FormatStyle::ACS_None);
16356   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
16357               FormatStyle::ACS_Consecutive);
16358 
16359   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16360   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
16361               FormatStyle::ACS_None);
16362   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
16363               FormatStyle::ACS_Consecutive);
16364   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
16365               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
16366   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
16367               AlignConsecutiveMacros,
16368               FormatStyle::ACS_AcrossEmptyLinesAndComments);
16369   // For backwards compability, false / true should still parse
16370   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
16371               FormatStyle::ACS_None);
16372   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
16373               FormatStyle::ACS_Consecutive);
16374 
16375   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16376   CHECK_PARSE("AlignConsecutiveDeclarations: None",
16377               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
16378   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
16379               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
16380   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
16381               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
16382   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
16383               AlignConsecutiveDeclarations,
16384               FormatStyle::ACS_AcrossEmptyLinesAndComments);
16385   // For backwards compability, false / true should still parse
16386   CHECK_PARSE("AlignConsecutiveDeclarations: false",
16387               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
16388   CHECK_PARSE("AlignConsecutiveDeclarations: true",
16389               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
16390 
16391   Style.PointerAlignment = FormatStyle::PAS_Middle;
16392   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
16393               FormatStyle::PAS_Left);
16394   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
16395               FormatStyle::PAS_Right);
16396   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
16397               FormatStyle::PAS_Middle);
16398   // For backward compatibility:
16399   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
16400               FormatStyle::PAS_Left);
16401   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
16402               FormatStyle::PAS_Right);
16403   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
16404               FormatStyle::PAS_Middle);
16405 
16406   Style.Standard = FormatStyle::LS_Auto;
16407   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
16408   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
16409   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
16410   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
16411   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
16412   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
16413   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
16414   // Legacy aliases:
16415   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
16416   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
16417   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
16418   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
16419 
16420   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16421   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
16422               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
16423   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
16424               FormatStyle::BOS_None);
16425   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
16426               FormatStyle::BOS_All);
16427   // For backward compatibility:
16428   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
16429               FormatStyle::BOS_None);
16430   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
16431               FormatStyle::BOS_All);
16432 
16433   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
16434   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
16435               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
16436   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
16437               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
16438   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
16439               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
16440   // For backward compatibility:
16441   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
16442               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
16443 
16444   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
16445   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
16446               FormatStyle::BILS_BeforeComma);
16447   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
16448               FormatStyle::BILS_AfterColon);
16449   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
16450               FormatStyle::BILS_BeforeColon);
16451   // For backward compatibility:
16452   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
16453               FormatStyle::BILS_BeforeComma);
16454 
16455   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
16456   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
16457               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
16458   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
16459               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
16460   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
16461               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
16462   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
16463               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
16464 
16465   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
16466   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
16467               FormatStyle::BAS_Align);
16468   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
16469               FormatStyle::BAS_DontAlign);
16470   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
16471               FormatStyle::BAS_AlwaysBreak);
16472   // For backward compatibility:
16473   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
16474               FormatStyle::BAS_DontAlign);
16475   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
16476               FormatStyle::BAS_Align);
16477 
16478   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16479   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
16480               FormatStyle::ENAS_DontAlign);
16481   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
16482               FormatStyle::ENAS_Left);
16483   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
16484               FormatStyle::ENAS_Right);
16485   // For backward compatibility:
16486   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
16487               FormatStyle::ENAS_Left);
16488   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
16489               FormatStyle::ENAS_Right);
16490 
16491   Style.AlignOperands = FormatStyle::OAS_Align;
16492   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
16493               FormatStyle::OAS_DontAlign);
16494   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
16495   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
16496               FormatStyle::OAS_AlignAfterOperator);
16497   // For backward compatibility:
16498   CHECK_PARSE("AlignOperands: false", AlignOperands,
16499               FormatStyle::OAS_DontAlign);
16500   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
16501 
16502   Style.UseTab = FormatStyle::UT_ForIndentation;
16503   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
16504   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
16505   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
16506   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
16507               FormatStyle::UT_ForContinuationAndIndentation);
16508   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
16509               FormatStyle::UT_AlignWithSpaces);
16510   // For backward compatibility:
16511   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
16512   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
16513 
16514   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
16515   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
16516               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
16517   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
16518               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
16519   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
16520               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
16521   // For backward compatibility:
16522   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
16523               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
16524   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
16525               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
16526 
16527   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
16528   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
16529               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
16530   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
16531               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
16532   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
16533               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
16534   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
16535               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
16536   // For backward compatibility:
16537   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
16538               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
16539   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
16540               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
16541 
16542   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
16543   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
16544               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
16545   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
16546               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
16547   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
16548               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
16549   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
16550               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
16551 
16552   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
16553   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
16554               FormatStyle::SBPO_Never);
16555   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
16556               FormatStyle::SBPO_Always);
16557   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
16558               FormatStyle::SBPO_ControlStatements);
16559   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
16560               FormatStyle::SBPO_NonEmptyParentheses);
16561   // For backward compatibility:
16562   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
16563               FormatStyle::SBPO_Never);
16564   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
16565               FormatStyle::SBPO_ControlStatements);
16566 
16567   Style.ColumnLimit = 123;
16568   FormatStyle BaseStyle = getLLVMStyle();
16569   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
16570   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
16571 
16572   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
16573   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
16574               FormatStyle::BS_Attach);
16575   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
16576               FormatStyle::BS_Linux);
16577   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
16578               FormatStyle::BS_Mozilla);
16579   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
16580               FormatStyle::BS_Stroustrup);
16581   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
16582               FormatStyle::BS_Allman);
16583   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
16584               FormatStyle::BS_Whitesmiths);
16585   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
16586   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
16587               FormatStyle::BS_WebKit);
16588   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
16589               FormatStyle::BS_Custom);
16590 
16591   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
16592   CHECK_PARSE("BraceWrapping:\n"
16593               "  AfterControlStatement: MultiLine",
16594               BraceWrapping.AfterControlStatement,
16595               FormatStyle::BWACS_MultiLine);
16596   CHECK_PARSE("BraceWrapping:\n"
16597               "  AfterControlStatement: Always",
16598               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
16599   CHECK_PARSE("BraceWrapping:\n"
16600               "  AfterControlStatement: Never",
16601               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
16602   // For backward compatibility:
16603   CHECK_PARSE("BraceWrapping:\n"
16604               "  AfterControlStatement: true",
16605               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
16606   CHECK_PARSE("BraceWrapping:\n"
16607               "  AfterControlStatement: false",
16608               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
16609 
16610   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
16611   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
16612               FormatStyle::RTBS_None);
16613   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
16614               FormatStyle::RTBS_All);
16615   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
16616               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
16617   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
16618               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
16619   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
16620               AlwaysBreakAfterReturnType,
16621               FormatStyle::RTBS_TopLevelDefinitions);
16622 
16623   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
16624   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
16625               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
16626   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
16627               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
16628   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
16629               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
16630   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
16631               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
16632   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
16633               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
16634 
16635   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
16636   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
16637               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
16638   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
16639               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
16640   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
16641               AlwaysBreakAfterDefinitionReturnType,
16642               FormatStyle::DRTBS_TopLevel);
16643 
16644   Style.NamespaceIndentation = FormatStyle::NI_All;
16645   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
16646               FormatStyle::NI_None);
16647   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
16648               FormatStyle::NI_Inner);
16649   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
16650               FormatStyle::NI_All);
16651 
16652   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
16653   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
16654               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
16655   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
16656               AllowShortIfStatementsOnASingleLine,
16657               FormatStyle::SIS_WithoutElse);
16658   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
16659               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Always);
16660   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
16661               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
16662   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
16663               AllowShortIfStatementsOnASingleLine,
16664               FormatStyle::SIS_WithoutElse);
16665 
16666   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
16667   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
16668               FormatStyle::IEBS_AfterExternBlock);
16669   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
16670               FormatStyle::IEBS_Indent);
16671   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
16672               FormatStyle::IEBS_NoIndent);
16673   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
16674               FormatStyle::IEBS_Indent);
16675   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
16676               FormatStyle::IEBS_NoIndent);
16677 
16678   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
16679   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
16680               FormatStyle::BFCS_Both);
16681   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
16682               FormatStyle::BFCS_None);
16683   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
16684               FormatStyle::BFCS_Before);
16685   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
16686               FormatStyle::BFCS_After);
16687 
16688   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
16689   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
16690               FormatStyle::SJSIO_After);
16691   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
16692               FormatStyle::SJSIO_Before);
16693 
16694   // FIXME: This is required because parsing a configuration simply overwrites
16695   // the first N elements of the list instead of resetting it.
16696   Style.ForEachMacros.clear();
16697   std::vector<std::string> BoostForeach;
16698   BoostForeach.push_back("BOOST_FOREACH");
16699   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
16700   std::vector<std::string> BoostAndQForeach;
16701   BoostAndQForeach.push_back("BOOST_FOREACH");
16702   BoostAndQForeach.push_back("Q_FOREACH");
16703   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
16704               BoostAndQForeach);
16705 
16706   Style.AttributeMacros.clear();
16707   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
16708               std::vector<std::string>{"__capability"});
16709   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
16710               std::vector<std::string>({"attr1", "attr2"}));
16711 
16712   Style.StatementAttributeLikeMacros.clear();
16713   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
16714               StatementAttributeLikeMacros,
16715               std::vector<std::string>({"emit", "Q_EMIT"}));
16716 
16717   Style.StatementMacros.clear();
16718   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
16719               std::vector<std::string>{"QUNUSED"});
16720   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
16721               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
16722 
16723   Style.NamespaceMacros.clear();
16724   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
16725               std::vector<std::string>{"TESTSUITE"});
16726   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
16727               std::vector<std::string>({"TESTSUITE", "SUITE"}));
16728 
16729   Style.WhitespaceSensitiveMacros.clear();
16730   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
16731               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
16732   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
16733               WhitespaceSensitiveMacros,
16734               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
16735   Style.WhitespaceSensitiveMacros.clear();
16736   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
16737               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
16738   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
16739               WhitespaceSensitiveMacros,
16740               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
16741 
16742   Style.IncludeStyle.IncludeCategories.clear();
16743   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
16744       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
16745   CHECK_PARSE("IncludeCategories:\n"
16746               "  - Regex: abc/.*\n"
16747               "    Priority: 2\n"
16748               "  - Regex: .*\n"
16749               "    Priority: 1\n"
16750               "    CaseSensitive: true\n",
16751               IncludeStyle.IncludeCategories, ExpectedCategories);
16752   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
16753               "abc$");
16754   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
16755               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
16756 
16757   Style.SortIncludes = FormatStyle::SI_Never;
16758   CHECK_PARSE("SortIncludes: true", SortIncludes,
16759               FormatStyle::SI_CaseSensitive);
16760   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
16761   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
16762               FormatStyle::SI_CaseInsensitive);
16763   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
16764               FormatStyle::SI_CaseSensitive);
16765   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
16766 
16767   Style.RawStringFormats.clear();
16768   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
16769       {
16770           FormatStyle::LK_TextProto,
16771           {"pb", "proto"},
16772           {"PARSE_TEXT_PROTO"},
16773           /*CanonicalDelimiter=*/"",
16774           "llvm",
16775       },
16776       {
16777           FormatStyle::LK_Cpp,
16778           {"cc", "cpp"},
16779           {"C_CODEBLOCK", "CPPEVAL"},
16780           /*CanonicalDelimiter=*/"cc",
16781           /*BasedOnStyle=*/"",
16782       },
16783   };
16784 
16785   CHECK_PARSE("RawStringFormats:\n"
16786               "  - Language: TextProto\n"
16787               "    Delimiters:\n"
16788               "      - 'pb'\n"
16789               "      - 'proto'\n"
16790               "    EnclosingFunctions:\n"
16791               "      - 'PARSE_TEXT_PROTO'\n"
16792               "    BasedOnStyle: llvm\n"
16793               "  - Language: Cpp\n"
16794               "    Delimiters:\n"
16795               "      - 'cc'\n"
16796               "      - 'cpp'\n"
16797               "    EnclosingFunctions:\n"
16798               "      - 'C_CODEBLOCK'\n"
16799               "      - 'CPPEVAL'\n"
16800               "    CanonicalDelimiter: 'cc'",
16801               RawStringFormats, ExpectedRawStringFormats);
16802 
16803   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16804               "  Minimum: 0\n"
16805               "  Maximum: 0",
16806               SpacesInLineCommentPrefix.Minimum, 0u);
16807   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
16808   Style.SpacesInLineCommentPrefix.Minimum = 1;
16809   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16810               "  Minimum: 2",
16811               SpacesInLineCommentPrefix.Minimum, 0u);
16812   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16813               "  Maximum: -1",
16814               SpacesInLineCommentPrefix.Maximum, -1u);
16815   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16816               "  Minimum: 2",
16817               SpacesInLineCommentPrefix.Minimum, 2u);
16818   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16819               "  Maximum: 1",
16820               SpacesInLineCommentPrefix.Maximum, 1u);
16821   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
16822 }
16823 
16824 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
16825   FormatStyle Style = {};
16826   Style.Language = FormatStyle::LK_Cpp;
16827   CHECK_PARSE("Language: Cpp\n"
16828               "IndentWidth: 12",
16829               IndentWidth, 12u);
16830   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
16831                                "IndentWidth: 34",
16832                                &Style),
16833             ParseError::Unsuitable);
16834   FormatStyle BinPackedTCS = {};
16835   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
16836   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
16837                                "InsertTrailingCommas: Wrapped",
16838                                &BinPackedTCS),
16839             ParseError::BinPackTrailingCommaConflict);
16840   EXPECT_EQ(12u, Style.IndentWidth);
16841   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
16842   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
16843 
16844   Style.Language = FormatStyle::LK_JavaScript;
16845   CHECK_PARSE("Language: JavaScript\n"
16846               "IndentWidth: 12",
16847               IndentWidth, 12u);
16848   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
16849   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
16850                                "IndentWidth: 34",
16851                                &Style),
16852             ParseError::Unsuitable);
16853   EXPECT_EQ(23u, Style.IndentWidth);
16854   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
16855   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
16856 
16857   CHECK_PARSE("BasedOnStyle: LLVM\n"
16858               "IndentWidth: 67",
16859               IndentWidth, 67u);
16860 
16861   CHECK_PARSE("---\n"
16862               "Language: JavaScript\n"
16863               "IndentWidth: 12\n"
16864               "---\n"
16865               "Language: Cpp\n"
16866               "IndentWidth: 34\n"
16867               "...\n",
16868               IndentWidth, 12u);
16869 
16870   Style.Language = FormatStyle::LK_Cpp;
16871   CHECK_PARSE("---\n"
16872               "Language: JavaScript\n"
16873               "IndentWidth: 12\n"
16874               "---\n"
16875               "Language: Cpp\n"
16876               "IndentWidth: 34\n"
16877               "...\n",
16878               IndentWidth, 34u);
16879   CHECK_PARSE("---\n"
16880               "IndentWidth: 78\n"
16881               "---\n"
16882               "Language: JavaScript\n"
16883               "IndentWidth: 56\n"
16884               "...\n",
16885               IndentWidth, 78u);
16886 
16887   Style.ColumnLimit = 123;
16888   Style.IndentWidth = 234;
16889   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
16890   Style.TabWidth = 345;
16891   EXPECT_FALSE(parseConfiguration("---\n"
16892                                   "IndentWidth: 456\n"
16893                                   "BreakBeforeBraces: Allman\n"
16894                                   "---\n"
16895                                   "Language: JavaScript\n"
16896                                   "IndentWidth: 111\n"
16897                                   "TabWidth: 111\n"
16898                                   "---\n"
16899                                   "Language: Cpp\n"
16900                                   "BreakBeforeBraces: Stroustrup\n"
16901                                   "TabWidth: 789\n"
16902                                   "...\n",
16903                                   &Style));
16904   EXPECT_EQ(123u, Style.ColumnLimit);
16905   EXPECT_EQ(456u, Style.IndentWidth);
16906   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
16907   EXPECT_EQ(789u, Style.TabWidth);
16908 
16909   EXPECT_EQ(parseConfiguration("---\n"
16910                                "Language: JavaScript\n"
16911                                "IndentWidth: 56\n"
16912                                "---\n"
16913                                "IndentWidth: 78\n"
16914                                "...\n",
16915                                &Style),
16916             ParseError::Error);
16917   EXPECT_EQ(parseConfiguration("---\n"
16918                                "Language: JavaScript\n"
16919                                "IndentWidth: 56\n"
16920                                "---\n"
16921                                "Language: JavaScript\n"
16922                                "IndentWidth: 78\n"
16923                                "...\n",
16924                                &Style),
16925             ParseError::Error);
16926 
16927   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
16928 }
16929 
16930 #undef CHECK_PARSE
16931 
16932 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
16933   FormatStyle Style = {};
16934   Style.Language = FormatStyle::LK_JavaScript;
16935   Style.BreakBeforeTernaryOperators = true;
16936   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
16937   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
16938 
16939   Style.BreakBeforeTernaryOperators = true;
16940   EXPECT_EQ(0, parseConfiguration("---\n"
16941                                   "BasedOnStyle: Google\n"
16942                                   "---\n"
16943                                   "Language: JavaScript\n"
16944                                   "IndentWidth: 76\n"
16945                                   "...\n",
16946                                   &Style)
16947                    .value());
16948   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
16949   EXPECT_EQ(76u, Style.IndentWidth);
16950   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
16951 }
16952 
16953 TEST_F(FormatTest, ConfigurationRoundTripTest) {
16954   FormatStyle Style = getLLVMStyle();
16955   std::string YAML = configurationAsText(Style);
16956   FormatStyle ParsedStyle = {};
16957   ParsedStyle.Language = FormatStyle::LK_Cpp;
16958   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
16959   EXPECT_EQ(Style, ParsedStyle);
16960 }
16961 
16962 TEST_F(FormatTest, WorksFor8bitEncodings) {
16963   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
16964             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
16965             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
16966             "\"\xef\xee\xf0\xf3...\"",
16967             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
16968                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
16969                    "\xef\xee\xf0\xf3...\"",
16970                    getLLVMStyleWithColumns(12)));
16971 }
16972 
16973 TEST_F(FormatTest, HandlesUTF8BOM) {
16974   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
16975   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
16976             format("\xef\xbb\xbf#include <iostream>"));
16977   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
16978             format("\xef\xbb\xbf\n#include <iostream>"));
16979 }
16980 
16981 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
16982 #if !defined(_MSC_VER)
16983 
16984 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
16985   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
16986                getLLVMStyleWithColumns(35));
16987   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
16988                getLLVMStyleWithColumns(31));
16989   verifyFormat("// Однажды в студёную зимнюю пору...",
16990                getLLVMStyleWithColumns(36));
16991   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
16992   verifyFormat("/* Однажды в студёную зимнюю пору... */",
16993                getLLVMStyleWithColumns(39));
16994   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
16995                getLLVMStyleWithColumns(35));
16996 }
16997 
16998 TEST_F(FormatTest, SplitsUTF8Strings) {
16999   // Non-printable characters' width is currently considered to be the length in
17000   // bytes in UTF8. The characters can be displayed in very different manner
17001   // (zero-width, single width with a substitution glyph, expanded to their code
17002   // (e.g. "<8d>"), so there's no single correct way to handle them.
17003   EXPECT_EQ("\"aaaaÄ\"\n"
17004             "\"\xc2\x8d\";",
17005             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
17006   EXPECT_EQ("\"aaaaaaaÄ\"\n"
17007             "\"\xc2\x8d\";",
17008             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
17009   EXPECT_EQ("\"Однажды, в \"\n"
17010             "\"студёную \"\n"
17011             "\"зимнюю \"\n"
17012             "\"пору,\"",
17013             format("\"Однажды, в студёную зимнюю пору,\"",
17014                    getLLVMStyleWithColumns(13)));
17015   EXPECT_EQ(
17016       "\"一 二 三 \"\n"
17017       "\"四 五六 \"\n"
17018       "\"七 八 九 \"\n"
17019       "\"十\"",
17020       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
17021   EXPECT_EQ("\"一\t\"\n"
17022             "\"二 \t\"\n"
17023             "\"三 四 \"\n"
17024             "\"五\t\"\n"
17025             "\"六 \t\"\n"
17026             "\"七 \"\n"
17027             "\"八九十\tqq\"",
17028             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
17029                    getLLVMStyleWithColumns(11)));
17030 
17031   // UTF8 character in an escape sequence.
17032   EXPECT_EQ("\"aaaaaa\"\n"
17033             "\"\\\xC2\x8D\"",
17034             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
17035 }
17036 
17037 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
17038   EXPECT_EQ("const char *sssss =\n"
17039             "    \"一二三四五六七八\\\n"
17040             " 九 十\";",
17041             format("const char *sssss = \"一二三四五六七八\\\n"
17042                    " 九 十\";",
17043                    getLLVMStyleWithColumns(30)));
17044 }
17045 
17046 TEST_F(FormatTest, SplitsUTF8LineComments) {
17047   EXPECT_EQ("// aaaaÄ\xc2\x8d",
17048             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
17049   EXPECT_EQ("// Я из лесу\n"
17050             "// вышел; был\n"
17051             "// сильный\n"
17052             "// мороз.",
17053             format("// Я из лесу вышел; был сильный мороз.",
17054                    getLLVMStyleWithColumns(13)));
17055   EXPECT_EQ("// 一二三\n"
17056             "// 四五六七\n"
17057             "// 八  九\n"
17058             "// 十",
17059             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
17060 }
17061 
17062 TEST_F(FormatTest, SplitsUTF8BlockComments) {
17063   EXPECT_EQ("/* Гляжу,\n"
17064             " * поднимается\n"
17065             " * медленно в\n"
17066             " * гору\n"
17067             " * Лошадка,\n"
17068             " * везущая\n"
17069             " * хворосту\n"
17070             " * воз. */",
17071             format("/* Гляжу, поднимается медленно в гору\n"
17072                    " * Лошадка, везущая хворосту воз. */",
17073                    getLLVMStyleWithColumns(13)));
17074   EXPECT_EQ(
17075       "/* 一二三\n"
17076       " * 四五六七\n"
17077       " * 八  九\n"
17078       " * 十  */",
17079       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
17080   EXPECT_EQ("/* �������� ��������\n"
17081             " * ��������\n"
17082             " * ������-�� */",
17083             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
17084 }
17085 
17086 #endif // _MSC_VER
17087 
17088 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
17089   FormatStyle Style = getLLVMStyle();
17090 
17091   Style.ConstructorInitializerIndentWidth = 4;
17092   verifyFormat(
17093       "SomeClass::Constructor()\n"
17094       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
17095       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
17096       Style);
17097 
17098   Style.ConstructorInitializerIndentWidth = 2;
17099   verifyFormat(
17100       "SomeClass::Constructor()\n"
17101       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
17102       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
17103       Style);
17104 
17105   Style.ConstructorInitializerIndentWidth = 0;
17106   verifyFormat(
17107       "SomeClass::Constructor()\n"
17108       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
17109       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
17110       Style);
17111   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
17112   verifyFormat(
17113       "SomeLongTemplateVariableName<\n"
17114       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
17115       Style);
17116   verifyFormat("bool smaller = 1 < "
17117                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
17118                "                       "
17119                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
17120                Style);
17121 
17122   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
17123   verifyFormat("SomeClass::Constructor() :\n"
17124                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
17125                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
17126                Style);
17127 }
17128 
17129 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
17130   FormatStyle Style = getLLVMStyle();
17131   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
17132   Style.ConstructorInitializerIndentWidth = 4;
17133   verifyFormat("SomeClass::Constructor()\n"
17134                "    : a(a)\n"
17135                "    , b(b)\n"
17136                "    , c(c) {}",
17137                Style);
17138   verifyFormat("SomeClass::Constructor()\n"
17139                "    : a(a) {}",
17140                Style);
17141 
17142   Style.ColumnLimit = 0;
17143   verifyFormat("SomeClass::Constructor()\n"
17144                "    : a(a) {}",
17145                Style);
17146   verifyFormat("SomeClass::Constructor() noexcept\n"
17147                "    : a(a) {}",
17148                Style);
17149   verifyFormat("SomeClass::Constructor()\n"
17150                "    : a(a)\n"
17151                "    , b(b)\n"
17152                "    , c(c) {}",
17153                Style);
17154   verifyFormat("SomeClass::Constructor()\n"
17155                "    : a(a) {\n"
17156                "  foo();\n"
17157                "  bar();\n"
17158                "}",
17159                Style);
17160 
17161   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
17162   verifyFormat("SomeClass::Constructor()\n"
17163                "    : a(a)\n"
17164                "    , b(b)\n"
17165                "    , c(c) {\n}",
17166                Style);
17167   verifyFormat("SomeClass::Constructor()\n"
17168                "    : a(a) {\n}",
17169                Style);
17170 
17171   Style.ColumnLimit = 80;
17172   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
17173   Style.ConstructorInitializerIndentWidth = 2;
17174   verifyFormat("SomeClass::Constructor()\n"
17175                "  : a(a)\n"
17176                "  , b(b)\n"
17177                "  , c(c) {}",
17178                Style);
17179 
17180   Style.ConstructorInitializerIndentWidth = 0;
17181   verifyFormat("SomeClass::Constructor()\n"
17182                ": a(a)\n"
17183                ", b(b)\n"
17184                ", c(c) {}",
17185                Style);
17186 
17187   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
17188   Style.ConstructorInitializerIndentWidth = 4;
17189   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
17190   verifyFormat(
17191       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
17192       Style);
17193   verifyFormat(
17194       "SomeClass::Constructor()\n"
17195       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
17196       Style);
17197   Style.ConstructorInitializerIndentWidth = 4;
17198   Style.ColumnLimit = 60;
17199   verifyFormat("SomeClass::Constructor()\n"
17200                "    : aaaaaaaa(aaaaaaaa)\n"
17201                "    , aaaaaaaa(aaaaaaaa)\n"
17202                "    , aaaaaaaa(aaaaaaaa) {}",
17203                Style);
17204 }
17205 
17206 TEST_F(FormatTest, Destructors) {
17207   verifyFormat("void F(int &i) { i.~int(); }");
17208   verifyFormat("void F(int &i) { i->~int(); }");
17209 }
17210 
17211 TEST_F(FormatTest, FormatsWithWebKitStyle) {
17212   FormatStyle Style = getWebKitStyle();
17213 
17214   // Don't indent in outer namespaces.
17215   verifyFormat("namespace outer {\n"
17216                "int i;\n"
17217                "namespace inner {\n"
17218                "    int i;\n"
17219                "} // namespace inner\n"
17220                "} // namespace outer\n"
17221                "namespace other_outer {\n"
17222                "int i;\n"
17223                "}",
17224                Style);
17225 
17226   // Don't indent case labels.
17227   verifyFormat("switch (variable) {\n"
17228                "case 1:\n"
17229                "case 2:\n"
17230                "    doSomething();\n"
17231                "    break;\n"
17232                "default:\n"
17233                "    ++variable;\n"
17234                "}",
17235                Style);
17236 
17237   // Wrap before binary operators.
17238   EXPECT_EQ("void f()\n"
17239             "{\n"
17240             "    if (aaaaaaaaaaaaaaaa\n"
17241             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
17242             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
17243             "        return;\n"
17244             "}",
17245             format("void f() {\n"
17246                    "if (aaaaaaaaaaaaaaaa\n"
17247                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
17248                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
17249                    "return;\n"
17250                    "}",
17251                    Style));
17252 
17253   // Allow functions on a single line.
17254   verifyFormat("void f() { return; }", Style);
17255 
17256   // Allow empty blocks on a single line and insert a space in empty blocks.
17257   EXPECT_EQ("void f() { }", format("void f() {}", Style));
17258   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
17259   // However, don't merge non-empty short loops.
17260   EXPECT_EQ("while (true) {\n"
17261             "    continue;\n"
17262             "}",
17263             format("while (true) { continue; }", Style));
17264 
17265   // Constructor initializers are formatted one per line with the "," on the
17266   // new line.
17267   verifyFormat("Constructor()\n"
17268                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
17269                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
17270                "          aaaaaaaaaaaaaa)\n"
17271                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
17272                "{\n"
17273                "}",
17274                Style);
17275   verifyFormat("SomeClass::Constructor()\n"
17276                "    : a(a)\n"
17277                "{\n"
17278                "}",
17279                Style);
17280   EXPECT_EQ("SomeClass::Constructor()\n"
17281             "    : a(a)\n"
17282             "{\n"
17283             "}",
17284             format("SomeClass::Constructor():a(a){}", Style));
17285   verifyFormat("SomeClass::Constructor()\n"
17286                "    : a(a)\n"
17287                "    , b(b)\n"
17288                "    , c(c)\n"
17289                "{\n"
17290                "}",
17291                Style);
17292   verifyFormat("SomeClass::Constructor()\n"
17293                "    : a(a)\n"
17294                "{\n"
17295                "    foo();\n"
17296                "    bar();\n"
17297                "}",
17298                Style);
17299 
17300   // Access specifiers should be aligned left.
17301   verifyFormat("class C {\n"
17302                "public:\n"
17303                "    int i;\n"
17304                "};",
17305                Style);
17306 
17307   // Do not align comments.
17308   verifyFormat("int a; // Do not\n"
17309                "double b; // align comments.",
17310                Style);
17311 
17312   // Do not align operands.
17313   EXPECT_EQ("ASSERT(aaaa\n"
17314             "    || bbbb);",
17315             format("ASSERT ( aaaa\n||bbbb);", Style));
17316 
17317   // Accept input's line breaks.
17318   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
17319             "    || bbbbbbbbbbbbbbb) {\n"
17320             "    i++;\n"
17321             "}",
17322             format("if (aaaaaaaaaaaaaaa\n"
17323                    "|| bbbbbbbbbbbbbbb) { i++; }",
17324                    Style));
17325   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
17326             "    i++;\n"
17327             "}",
17328             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
17329 
17330   // Don't automatically break all macro definitions (llvm.org/PR17842).
17331   verifyFormat("#define aNumber 10", Style);
17332   // However, generally keep the line breaks that the user authored.
17333   EXPECT_EQ("#define aNumber \\\n"
17334             "    10",
17335             format("#define aNumber \\\n"
17336                    " 10",
17337                    Style));
17338 
17339   // Keep empty and one-element array literals on a single line.
17340   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
17341             "                                  copyItems:YES];",
17342             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
17343                    "copyItems:YES];",
17344                    Style));
17345   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
17346             "                                  copyItems:YES];",
17347             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
17348                    "             copyItems:YES];",
17349                    Style));
17350   // FIXME: This does not seem right, there should be more indentation before
17351   // the array literal's entries. Nested blocks have the same problem.
17352   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
17353             "    @\"a\",\n"
17354             "    @\"a\"\n"
17355             "]\n"
17356             "                                  copyItems:YES];",
17357             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
17358                    "     @\"a\",\n"
17359                    "     @\"a\"\n"
17360                    "     ]\n"
17361                    "       copyItems:YES];",
17362                    Style));
17363   EXPECT_EQ(
17364       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
17365       "                                  copyItems:YES];",
17366       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
17367              "   copyItems:YES];",
17368              Style));
17369 
17370   verifyFormat("[self.a b:c c:d];", Style);
17371   EXPECT_EQ("[self.a b:c\n"
17372             "        c:d];",
17373             format("[self.a b:c\n"
17374                    "c:d];",
17375                    Style));
17376 }
17377 
17378 TEST_F(FormatTest, FormatsLambdas) {
17379   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
17380   verifyFormat(
17381       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
17382   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
17383   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
17384   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
17385   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
17386   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
17387   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
17388   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
17389   verifyFormat("int x = f(*+[] {});");
17390   verifyFormat("void f() {\n"
17391                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
17392                "}\n");
17393   verifyFormat("void f() {\n"
17394                "  other(x.begin(), //\n"
17395                "        x.end(),   //\n"
17396                "        [&](int, int) { return 1; });\n"
17397                "}\n");
17398   verifyFormat("void f() {\n"
17399                "  other.other.other.other.other(\n"
17400                "      x.begin(), x.end(),\n"
17401                "      [something, rather](int, int, int, int, int, int, int) { "
17402                "return 1; });\n"
17403                "}\n");
17404   verifyFormat(
17405       "void f() {\n"
17406       "  other.other.other.other.other(\n"
17407       "      x.begin(), x.end(),\n"
17408       "      [something, rather](int, int, int, int, int, int, int) {\n"
17409       "        //\n"
17410       "      });\n"
17411       "}\n");
17412   verifyFormat("SomeFunction([]() { // A cool function...\n"
17413                "  return 43;\n"
17414                "});");
17415   EXPECT_EQ("SomeFunction([]() {\n"
17416             "#define A a\n"
17417             "  return 43;\n"
17418             "});",
17419             format("SomeFunction([](){\n"
17420                    "#define A a\n"
17421                    "return 43;\n"
17422                    "});"));
17423   verifyFormat("void f() {\n"
17424                "  SomeFunction([](decltype(x), A *a) {});\n"
17425                "  SomeFunction([](typeof(x), A *a) {});\n"
17426                "  SomeFunction([](_Atomic(x), A *a) {});\n"
17427                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
17428                "}");
17429   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
17430                "    [](const aaaaaaaaaa &a) { return a; });");
17431   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
17432                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
17433                "});");
17434   verifyFormat("Constructor()\n"
17435                "    : Field([] { // comment\n"
17436                "        int i;\n"
17437                "      }) {}");
17438   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
17439                "  return some_parameter.size();\n"
17440                "};");
17441   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
17442                "    [](const string &s) { return s; };");
17443   verifyFormat("int i = aaaaaa ? 1 //\n"
17444                "               : [] {\n"
17445                "                   return 2; //\n"
17446                "                 }();");
17447   verifyFormat("llvm::errs() << \"number of twos is \"\n"
17448                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
17449                "                  return x == 2; // force break\n"
17450                "                });");
17451   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
17452                "    [=](int iiiiiiiiiiii) {\n"
17453                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
17454                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
17455                "    });",
17456                getLLVMStyleWithColumns(60));
17457   verifyFormat("SomeFunction({[&] {\n"
17458                "                // comment\n"
17459                "              },\n"
17460                "              [&] {\n"
17461                "                // comment\n"
17462                "              }});");
17463   verifyFormat("SomeFunction({[&] {\n"
17464                "  // comment\n"
17465                "}});");
17466   verifyFormat(
17467       "virtual aaaaaaaaaaaaaaaa(\n"
17468       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
17469       "    aaaaa aaaaaaaaa);");
17470 
17471   // Lambdas with return types.
17472   verifyFormat("int c = []() -> int { return 2; }();\n");
17473   verifyFormat("int c = []() -> int * { return 2; }();\n");
17474   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
17475   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
17476   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
17477   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
17478   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
17479   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
17480   verifyFormat("[a, a]() -> a<1> {};");
17481   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
17482   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
17483   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
17484   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
17485   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
17486   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
17487   verifyFormat("[]() -> foo<!5> { return {}; };");
17488   verifyFormat("[]() -> foo<~5> { return {}; };");
17489   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
17490   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
17491   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
17492   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
17493   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
17494   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
17495   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
17496   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
17497   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
17498   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
17499   verifyFormat("namespace bar {\n"
17500                "// broken:\n"
17501                "auto foo{[]() -> foo<5 + 2> { return {}; }};\n"
17502                "} // namespace bar");
17503   verifyFormat("namespace bar {\n"
17504                "// broken:\n"
17505                "auto foo{[]() -> foo<5 - 2> { return {}; }};\n"
17506                "} // namespace bar");
17507   verifyFormat("namespace bar {\n"
17508                "// broken:\n"
17509                "auto foo{[]() -> foo<5 / 2> { return {}; }};\n"
17510                "} // namespace bar");
17511   verifyFormat("namespace bar {\n"
17512                "// broken:\n"
17513                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
17514                "} // namespace bar");
17515   verifyFormat("namespace bar {\n"
17516                "// broken:\n"
17517                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
17518                "} // namespace bar");
17519   verifyFormat("namespace bar {\n"
17520                "// broken:\n"
17521                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
17522                "} // namespace bar");
17523   verifyFormat("namespace bar {\n"
17524                "// broken:\n"
17525                "auto foo{[]() -> foo<!5> { return {}; }};\n"
17526                "} // namespace bar");
17527   verifyFormat("namespace bar {\n"
17528                "// broken:\n"
17529                "auto foo{[]() -> foo<~5> { return {}; }};\n"
17530                "} // namespace bar");
17531   verifyFormat("namespace bar {\n"
17532                "// broken:\n"
17533                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
17534                "} // namespace bar");
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 <= 2> { return {}; }};\n"
17562                "} // namespace bar");
17563   verifyFormat("namespace bar {\n"
17564                "// broken:\n"
17565                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
17566                "} // namespace bar");
17567   verifyFormat("namespace bar {\n"
17568                "// broken:\n"
17569                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
17570                "} // namespace bar");
17571   verifyFormat("[]() -> a<1> {};");
17572   verifyFormat("[]() -> a<1> { ; };");
17573   verifyFormat("[]() -> a<1> { ; }();");
17574   verifyFormat("[a, a]() -> a<true> {};");
17575   verifyFormat("[]() -> a<true> {};");
17576   verifyFormat("[]() -> a<true> { ; };");
17577   verifyFormat("[]() -> a<true> { ; }();");
17578   verifyFormat("[a, a]() -> a<false> {};");
17579   verifyFormat("[]() -> a<false> {};");
17580   verifyFormat("[]() -> a<false> { ; };");
17581   verifyFormat("[]() -> a<false> { ; }();");
17582   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
17583   verifyFormat("namespace bar {\n"
17584                "auto foo{[]() -> foo<false> { ; }};\n"
17585                "} // namespace bar");
17586   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
17587                "                   int j) -> int {\n"
17588                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
17589                "};");
17590   verifyFormat(
17591       "aaaaaaaaaaaaaaaaaaaaaa(\n"
17592       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
17593       "      return aaaaaaaaaaaaaaaaa;\n"
17594       "    });",
17595       getLLVMStyleWithColumns(70));
17596   verifyFormat("[]() //\n"
17597                "    -> int {\n"
17598                "  return 1; //\n"
17599                "};");
17600   verifyFormat("[]() -> Void<T...> {};");
17601   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
17602 
17603   // Lambdas with explicit template argument lists.
17604   verifyFormat(
17605       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
17606 
17607   // Multiple lambdas in the same parentheses change indentation rules. These
17608   // lambdas are forced to start on new lines.
17609   verifyFormat("SomeFunction(\n"
17610                "    []() {\n"
17611                "      //\n"
17612                "    },\n"
17613                "    []() {\n"
17614                "      //\n"
17615                "    });");
17616 
17617   // A lambda passed as arg0 is always pushed to the next line.
17618   verifyFormat("SomeFunction(\n"
17619                "    [this] {\n"
17620                "      //\n"
17621                "    },\n"
17622                "    1);\n");
17623 
17624   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
17625   // the arg0 case above.
17626   auto Style = getGoogleStyle();
17627   Style.BinPackArguments = false;
17628   verifyFormat("SomeFunction(\n"
17629                "    a,\n"
17630                "    [this] {\n"
17631                "      //\n"
17632                "    },\n"
17633                "    b);\n",
17634                Style);
17635   verifyFormat("SomeFunction(\n"
17636                "    a,\n"
17637                "    [this] {\n"
17638                "      //\n"
17639                "    },\n"
17640                "    b);\n");
17641 
17642   // A lambda with a very long line forces arg0 to be pushed out irrespective of
17643   // the BinPackArguments value (as long as the code is wide enough).
17644   verifyFormat(
17645       "something->SomeFunction(\n"
17646       "    a,\n"
17647       "    [this] {\n"
17648       "      "
17649       "D0000000000000000000000000000000000000000000000000000000000001();\n"
17650       "    },\n"
17651       "    b);\n");
17652 
17653   // A multi-line lambda is pulled up as long as the introducer fits on the
17654   // previous line and there are no further args.
17655   verifyFormat("function(1, [this, that] {\n"
17656                "  //\n"
17657                "});\n");
17658   verifyFormat("function([this, that] {\n"
17659                "  //\n"
17660                "});\n");
17661   // FIXME: this format is not ideal and we should consider forcing the first
17662   // arg onto its own line.
17663   verifyFormat("function(a, b, c, //\n"
17664                "         d, [this, that] {\n"
17665                "           //\n"
17666                "         });\n");
17667 
17668   // Multiple lambdas are treated correctly even when there is a short arg0.
17669   verifyFormat("SomeFunction(\n"
17670                "    1,\n"
17671                "    [this] {\n"
17672                "      //\n"
17673                "    },\n"
17674                "    [this] {\n"
17675                "      //\n"
17676                "    },\n"
17677                "    1);\n");
17678 
17679   // More complex introducers.
17680   verifyFormat("return [i, args...] {};");
17681 
17682   // Not lambdas.
17683   verifyFormat("constexpr char hello[]{\"hello\"};");
17684   verifyFormat("double &operator[](int i) { return 0; }\n"
17685                "int i;");
17686   verifyFormat("std::unique_ptr<int[]> foo() {}");
17687   verifyFormat("int i = a[a][a]->f();");
17688   verifyFormat("int i = (*b)[a]->f();");
17689 
17690   // Other corner cases.
17691   verifyFormat("void f() {\n"
17692                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
17693                "  );\n"
17694                "}");
17695 
17696   // Lambdas created through weird macros.
17697   verifyFormat("void f() {\n"
17698                "  MACRO((const AA &a) { return 1; });\n"
17699                "  MACRO((AA &a) { return 1; });\n"
17700                "}");
17701 
17702   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
17703                "      doo_dah();\n"
17704                "      doo_dah();\n"
17705                "    })) {\n"
17706                "}");
17707   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
17708                "                doo_dah();\n"
17709                "                doo_dah();\n"
17710                "              })) {\n"
17711                "}");
17712   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
17713                "                doo_dah();\n"
17714                "                doo_dah();\n"
17715                "              })) {\n"
17716                "}");
17717   verifyFormat("auto lambda = []() {\n"
17718                "  int a = 2\n"
17719                "#if A\n"
17720                "          + 2\n"
17721                "#endif\n"
17722                "      ;\n"
17723                "};");
17724 
17725   // Lambdas with complex multiline introducers.
17726   verifyFormat(
17727       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
17728       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
17729       "        -> ::std::unordered_set<\n"
17730       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
17731       "      //\n"
17732       "    });");
17733 
17734   FormatStyle DoNotMerge = getLLVMStyle();
17735   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17736   verifyFormat("auto c = []() {\n"
17737                "  return b;\n"
17738                "};",
17739                "auto c = []() { return b; };", DoNotMerge);
17740   verifyFormat("auto c = []() {\n"
17741                "};",
17742                " auto c = []() {};", DoNotMerge);
17743 
17744   FormatStyle MergeEmptyOnly = getLLVMStyle();
17745   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
17746   verifyFormat("auto c = []() {\n"
17747                "  return b;\n"
17748                "};",
17749                "auto c = []() {\n"
17750                "  return b;\n"
17751                " };",
17752                MergeEmptyOnly);
17753   verifyFormat("auto c = []() {};",
17754                "auto c = []() {\n"
17755                "};",
17756                MergeEmptyOnly);
17757 
17758   FormatStyle MergeInline = getLLVMStyle();
17759   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
17760   verifyFormat("auto c = []() {\n"
17761                "  return b;\n"
17762                "};",
17763                "auto c = []() { return b; };", MergeInline);
17764   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
17765                MergeInline);
17766   verifyFormat("function([]() { return b; }, a)",
17767                "function([]() { return b; }, a)", MergeInline);
17768   verifyFormat("function(a, []() { return b; })",
17769                "function(a, []() { return b; })", MergeInline);
17770 
17771   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
17772   // AllowShortLambdasOnASingleLine
17773   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
17774   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
17775   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
17776   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17777       FormatStyle::ShortLambdaStyle::SLS_None;
17778   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
17779                "    []()\n"
17780                "    {\n"
17781                "      return 17;\n"
17782                "    });",
17783                LLVMWithBeforeLambdaBody);
17784   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
17785                "    []()\n"
17786                "    {\n"
17787                "    });",
17788                LLVMWithBeforeLambdaBody);
17789   verifyFormat("auto fct_SLS_None = []()\n"
17790                "{\n"
17791                "  return 17;\n"
17792                "};",
17793                LLVMWithBeforeLambdaBody);
17794   verifyFormat("TwoNestedLambdas_SLS_None(\n"
17795                "    []()\n"
17796                "    {\n"
17797                "      return Call(\n"
17798                "          []()\n"
17799                "          {\n"
17800                "            return 17;\n"
17801                "          });\n"
17802                "    });",
17803                LLVMWithBeforeLambdaBody);
17804   verifyFormat("void Fct()\n"
17805                "{\n"
17806                "  return {[]()\n"
17807                "          {\n"
17808                "            return 17;\n"
17809                "          }};\n"
17810                "}",
17811                LLVMWithBeforeLambdaBody);
17812 
17813   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17814       FormatStyle::ShortLambdaStyle::SLS_Empty;
17815   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
17816                "    []()\n"
17817                "    {\n"
17818                "      return 17;\n"
17819                "    });",
17820                LLVMWithBeforeLambdaBody);
17821   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
17822                LLVMWithBeforeLambdaBody);
17823   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
17824                "ongFunctionName_SLS_Empty(\n"
17825                "    []() {});",
17826                LLVMWithBeforeLambdaBody);
17827   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
17828                "                                []()\n"
17829                "                                {\n"
17830                "                                  return 17;\n"
17831                "                                });",
17832                LLVMWithBeforeLambdaBody);
17833   verifyFormat("auto fct_SLS_Empty = []()\n"
17834                "{\n"
17835                "  return 17;\n"
17836                "};",
17837                LLVMWithBeforeLambdaBody);
17838   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
17839                "    []()\n"
17840                "    {\n"
17841                "      return Call([]() {});\n"
17842                "    });",
17843                LLVMWithBeforeLambdaBody);
17844   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
17845                "                           []()\n"
17846                "                           {\n"
17847                "                             return Call([]() {});\n"
17848                "                           });",
17849                LLVMWithBeforeLambdaBody);
17850   verifyFormat(
17851       "FctWithLongLineInLambda_SLS_Empty(\n"
17852       "    []()\n"
17853       "    {\n"
17854       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17855       "                               AndShouldNotBeConsiderAsInline,\n"
17856       "                               LambdaBodyMustBeBreak);\n"
17857       "    });",
17858       LLVMWithBeforeLambdaBody);
17859 
17860   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17861       FormatStyle::ShortLambdaStyle::SLS_Inline;
17862   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
17863                LLVMWithBeforeLambdaBody);
17864   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
17865                LLVMWithBeforeLambdaBody);
17866   verifyFormat("auto fct_SLS_Inline = []()\n"
17867                "{\n"
17868                "  return 17;\n"
17869                "};",
17870                LLVMWithBeforeLambdaBody);
17871   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
17872                "17; }); });",
17873                LLVMWithBeforeLambdaBody);
17874   verifyFormat(
17875       "FctWithLongLineInLambda_SLS_Inline(\n"
17876       "    []()\n"
17877       "    {\n"
17878       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17879       "                               AndShouldNotBeConsiderAsInline,\n"
17880       "                               LambdaBodyMustBeBreak);\n"
17881       "    });",
17882       LLVMWithBeforeLambdaBody);
17883   verifyFormat("FctWithMultipleParams_SLS_Inline("
17884                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
17885                "                                 []() { return 17; });",
17886                LLVMWithBeforeLambdaBody);
17887   verifyFormat(
17888       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
17889       LLVMWithBeforeLambdaBody);
17890 
17891   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17892       FormatStyle::ShortLambdaStyle::SLS_All;
17893   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
17894                LLVMWithBeforeLambdaBody);
17895   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
17896                LLVMWithBeforeLambdaBody);
17897   verifyFormat("auto fct_SLS_All = []() { return 17; };",
17898                LLVMWithBeforeLambdaBody);
17899   verifyFormat("FctWithOneParam_SLS_All(\n"
17900                "    []()\n"
17901                "    {\n"
17902                "      // A cool function...\n"
17903                "      return 43;\n"
17904                "    });",
17905                LLVMWithBeforeLambdaBody);
17906   verifyFormat("FctWithMultipleParams_SLS_All("
17907                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
17908                "                              []() { return 17; });",
17909                LLVMWithBeforeLambdaBody);
17910   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
17911                LLVMWithBeforeLambdaBody);
17912   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
17913                LLVMWithBeforeLambdaBody);
17914   verifyFormat(
17915       "FctWithLongLineInLambda_SLS_All(\n"
17916       "    []()\n"
17917       "    {\n"
17918       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17919       "                               AndShouldNotBeConsiderAsInline,\n"
17920       "                               LambdaBodyMustBeBreak);\n"
17921       "    });",
17922       LLVMWithBeforeLambdaBody);
17923   verifyFormat(
17924       "auto fct_SLS_All = []()\n"
17925       "{\n"
17926       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17927       "                           AndShouldNotBeConsiderAsInline,\n"
17928       "                           LambdaBodyMustBeBreak);\n"
17929       "};",
17930       LLVMWithBeforeLambdaBody);
17931   LLVMWithBeforeLambdaBody.BinPackParameters = false;
17932   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
17933                LLVMWithBeforeLambdaBody);
17934   verifyFormat(
17935       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
17936       "                                FirstParam,\n"
17937       "                                SecondParam,\n"
17938       "                                ThirdParam,\n"
17939       "                                FourthParam);",
17940       LLVMWithBeforeLambdaBody);
17941   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
17942                "    []() { return "
17943                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
17944                "    FirstParam,\n"
17945                "    SecondParam,\n"
17946                "    ThirdParam,\n"
17947                "    FourthParam);",
17948                LLVMWithBeforeLambdaBody);
17949   verifyFormat(
17950       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
17951       "                                SecondParam,\n"
17952       "                                ThirdParam,\n"
17953       "                                FourthParam,\n"
17954       "                                []() { return SomeValueNotSoLong; });",
17955       LLVMWithBeforeLambdaBody);
17956   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
17957                "    []()\n"
17958                "    {\n"
17959                "      return "
17960                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
17961                "eConsiderAsInline;\n"
17962                "    });",
17963                LLVMWithBeforeLambdaBody);
17964   verifyFormat(
17965       "FctWithLongLineInLambda_SLS_All(\n"
17966       "    []()\n"
17967       "    {\n"
17968       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17969       "                               AndShouldNotBeConsiderAsInline,\n"
17970       "                               LambdaBodyMustBeBreak);\n"
17971       "    });",
17972       LLVMWithBeforeLambdaBody);
17973   verifyFormat("FctWithTwoParams_SLS_All(\n"
17974                "    []()\n"
17975                "    {\n"
17976                "      // A cool function...\n"
17977                "      return 43;\n"
17978                "    },\n"
17979                "    87);",
17980                LLVMWithBeforeLambdaBody);
17981   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
17982                LLVMWithBeforeLambdaBody);
17983   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
17984                LLVMWithBeforeLambdaBody);
17985   verifyFormat(
17986       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
17987       LLVMWithBeforeLambdaBody);
17988   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
17989                "}); }, x);",
17990                LLVMWithBeforeLambdaBody);
17991   verifyFormat("TwoNestedLambdas_SLS_All(\n"
17992                "    []()\n"
17993                "    {\n"
17994                "      // A cool function...\n"
17995                "      return Call([]() { return 17; });\n"
17996                "    });",
17997                LLVMWithBeforeLambdaBody);
17998   verifyFormat("TwoNestedLambdas_SLS_All(\n"
17999                "    []()\n"
18000                "    {\n"
18001                "      return Call(\n"
18002                "          []()\n"
18003                "          {\n"
18004                "            // A cool function...\n"
18005                "            return 17;\n"
18006                "          });\n"
18007                "    });",
18008                LLVMWithBeforeLambdaBody);
18009 }
18010 
18011 TEST_F(FormatTest, LambdaWithLineComments) {
18012   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
18013   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
18014   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
18015   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
18016       FormatStyle::ShortLambdaStyle::SLS_All;
18017 
18018   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
18019   verifyFormat("auto k = []() // comment\n"
18020                "{ return; }",
18021                LLVMWithBeforeLambdaBody);
18022   verifyFormat("auto k = []() /* comment */ { return; }",
18023                LLVMWithBeforeLambdaBody);
18024   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
18025                LLVMWithBeforeLambdaBody);
18026   verifyFormat("auto k = []() // X\n"
18027                "{ return; }",
18028                LLVMWithBeforeLambdaBody);
18029   verifyFormat(
18030       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
18031       "{ return; }",
18032       LLVMWithBeforeLambdaBody);
18033 }
18034 
18035 TEST_F(FormatTest, EmptyLinesInLambdas) {
18036   verifyFormat("auto lambda = []() {\n"
18037                "  x(); //\n"
18038                "};",
18039                "auto lambda = []() {\n"
18040                "\n"
18041                "  x(); //\n"
18042                "\n"
18043                "};");
18044 }
18045 
18046 TEST_F(FormatTest, FormatsBlocks) {
18047   FormatStyle ShortBlocks = getLLVMStyle();
18048   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
18049   verifyFormat("int (^Block)(int, int);", ShortBlocks);
18050   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
18051   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
18052   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
18053   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
18054   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
18055 
18056   verifyFormat("foo(^{ bar(); });", ShortBlocks);
18057   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
18058   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
18059 
18060   verifyFormat("[operation setCompletionBlock:^{\n"
18061                "  [self onOperationDone];\n"
18062                "}];");
18063   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
18064                "  [self onOperationDone];\n"
18065                "}]};");
18066   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
18067                "  f();\n"
18068                "}];");
18069   verifyFormat("int a = [operation block:^int(int *i) {\n"
18070                "  return 1;\n"
18071                "}];");
18072   verifyFormat("[myObject doSomethingWith:arg1\n"
18073                "                      aaa:^int(int *a) {\n"
18074                "                        return 1;\n"
18075                "                      }\n"
18076                "                      bbb:f(a * bbbbbbbb)];");
18077 
18078   verifyFormat("[operation setCompletionBlock:^{\n"
18079                "  [self.delegate newDataAvailable];\n"
18080                "}];",
18081                getLLVMStyleWithColumns(60));
18082   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
18083                "  NSString *path = [self sessionFilePath];\n"
18084                "  if (path) {\n"
18085                "    // ...\n"
18086                "  }\n"
18087                "});");
18088   verifyFormat("[[SessionService sharedService]\n"
18089                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
18090                "      if (window) {\n"
18091                "        [self windowDidLoad:window];\n"
18092                "      } else {\n"
18093                "        [self errorLoadingWindow];\n"
18094                "      }\n"
18095                "    }];");
18096   verifyFormat("void (^largeBlock)(void) = ^{\n"
18097                "  // ...\n"
18098                "};\n",
18099                getLLVMStyleWithColumns(40));
18100   verifyFormat("[[SessionService sharedService]\n"
18101                "    loadWindowWithCompletionBlock: //\n"
18102                "        ^(SessionWindow *window) {\n"
18103                "          if (window) {\n"
18104                "            [self windowDidLoad:window];\n"
18105                "          } else {\n"
18106                "            [self errorLoadingWindow];\n"
18107                "          }\n"
18108                "        }];",
18109                getLLVMStyleWithColumns(60));
18110   verifyFormat("[myObject doSomethingWith:arg1\n"
18111                "    firstBlock:^(Foo *a) {\n"
18112                "      // ...\n"
18113                "      int i;\n"
18114                "    }\n"
18115                "    secondBlock:^(Bar *b) {\n"
18116                "      // ...\n"
18117                "      int i;\n"
18118                "    }\n"
18119                "    thirdBlock:^Foo(Bar *b) {\n"
18120                "      // ...\n"
18121                "      int i;\n"
18122                "    }];");
18123   verifyFormat("[myObject doSomethingWith:arg1\n"
18124                "               firstBlock:-1\n"
18125                "              secondBlock:^(Bar *b) {\n"
18126                "                // ...\n"
18127                "                int i;\n"
18128                "              }];");
18129 
18130   verifyFormat("f(^{\n"
18131                "  @autoreleasepool {\n"
18132                "    if (a) {\n"
18133                "      g();\n"
18134                "    }\n"
18135                "  }\n"
18136                "});");
18137   verifyFormat("Block b = ^int *(A *a, B *b) {}");
18138   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
18139                "};");
18140 
18141   FormatStyle FourIndent = getLLVMStyle();
18142   FourIndent.ObjCBlockIndentWidth = 4;
18143   verifyFormat("[operation setCompletionBlock:^{\n"
18144                "    [self onOperationDone];\n"
18145                "}];",
18146                FourIndent);
18147 }
18148 
18149 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
18150   FormatStyle ZeroColumn = getLLVMStyle();
18151   ZeroColumn.ColumnLimit = 0;
18152 
18153   verifyFormat("[[SessionService sharedService] "
18154                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
18155                "  if (window) {\n"
18156                "    [self windowDidLoad:window];\n"
18157                "  } else {\n"
18158                "    [self errorLoadingWindow];\n"
18159                "  }\n"
18160                "}];",
18161                ZeroColumn);
18162   EXPECT_EQ("[[SessionService sharedService]\n"
18163             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
18164             "      if (window) {\n"
18165             "        [self windowDidLoad:window];\n"
18166             "      } else {\n"
18167             "        [self errorLoadingWindow];\n"
18168             "      }\n"
18169             "    }];",
18170             format("[[SessionService sharedService]\n"
18171                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
18172                    "                if (window) {\n"
18173                    "    [self windowDidLoad:window];\n"
18174                    "  } else {\n"
18175                    "    [self errorLoadingWindow];\n"
18176                    "  }\n"
18177                    "}];",
18178                    ZeroColumn));
18179   verifyFormat("[myObject doSomethingWith:arg1\n"
18180                "    firstBlock:^(Foo *a) {\n"
18181                "      // ...\n"
18182                "      int i;\n"
18183                "    }\n"
18184                "    secondBlock:^(Bar *b) {\n"
18185                "      // ...\n"
18186                "      int i;\n"
18187                "    }\n"
18188                "    thirdBlock:^Foo(Bar *b) {\n"
18189                "      // ...\n"
18190                "      int i;\n"
18191                "    }];",
18192                ZeroColumn);
18193   verifyFormat("f(^{\n"
18194                "  @autoreleasepool {\n"
18195                "    if (a) {\n"
18196                "      g();\n"
18197                "    }\n"
18198                "  }\n"
18199                "});",
18200                ZeroColumn);
18201   verifyFormat("void (^largeBlock)(void) = ^{\n"
18202                "  // ...\n"
18203                "};",
18204                ZeroColumn);
18205 
18206   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
18207   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
18208             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
18209   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
18210   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
18211             "  int i;\n"
18212             "};",
18213             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
18214 }
18215 
18216 TEST_F(FormatTest, SupportsCRLF) {
18217   EXPECT_EQ("int a;\r\n"
18218             "int b;\r\n"
18219             "int c;\r\n",
18220             format("int a;\r\n"
18221                    "  int b;\r\n"
18222                    "    int c;\r\n",
18223                    getLLVMStyle()));
18224   EXPECT_EQ("int a;\r\n"
18225             "int b;\r\n"
18226             "int c;\r\n",
18227             format("int a;\r\n"
18228                    "  int b;\n"
18229                    "    int c;\r\n",
18230                    getLLVMStyle()));
18231   EXPECT_EQ("int a;\n"
18232             "int b;\n"
18233             "int c;\n",
18234             format("int a;\r\n"
18235                    "  int b;\n"
18236                    "    int c;\n",
18237                    getLLVMStyle()));
18238   EXPECT_EQ("\"aaaaaaa \"\r\n"
18239             "\"bbbbbbb\";\r\n",
18240             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
18241   EXPECT_EQ("#define A \\\r\n"
18242             "  b;      \\\r\n"
18243             "  c;      \\\r\n"
18244             "  d;\r\n",
18245             format("#define A \\\r\n"
18246                    "  b; \\\r\n"
18247                    "  c; d; \r\n",
18248                    getGoogleStyle()));
18249 
18250   EXPECT_EQ("/*\r\n"
18251             "multi line block comments\r\n"
18252             "should not introduce\r\n"
18253             "an extra carriage return\r\n"
18254             "*/\r\n",
18255             format("/*\r\n"
18256                    "multi line block comments\r\n"
18257                    "should not introduce\r\n"
18258                    "an extra carriage return\r\n"
18259                    "*/\r\n"));
18260   EXPECT_EQ("/*\r\n"
18261             "\r\n"
18262             "*/",
18263             format("/*\r\n"
18264                    "    \r\r\r\n"
18265                    "*/"));
18266 
18267   FormatStyle style = getLLVMStyle();
18268 
18269   style.DeriveLineEnding = true;
18270   style.UseCRLF = false;
18271   EXPECT_EQ("union FooBarBazQux {\n"
18272             "  int foo;\n"
18273             "  int bar;\n"
18274             "  int baz;\n"
18275             "};",
18276             format("union FooBarBazQux {\r\n"
18277                    "  int foo;\n"
18278                    "  int bar;\r\n"
18279                    "  int baz;\n"
18280                    "};",
18281                    style));
18282   style.UseCRLF = true;
18283   EXPECT_EQ("union FooBarBazQux {\r\n"
18284             "  int foo;\r\n"
18285             "  int bar;\r\n"
18286             "  int baz;\r\n"
18287             "};",
18288             format("union FooBarBazQux {\r\n"
18289                    "  int foo;\n"
18290                    "  int bar;\r\n"
18291                    "  int baz;\n"
18292                    "};",
18293                    style));
18294 
18295   style.DeriveLineEnding = false;
18296   style.UseCRLF = false;
18297   EXPECT_EQ("union FooBarBazQux {\n"
18298             "  int foo;\n"
18299             "  int bar;\n"
18300             "  int baz;\n"
18301             "  int qux;\n"
18302             "};",
18303             format("union FooBarBazQux {\r\n"
18304                    "  int foo;\n"
18305                    "  int bar;\r\n"
18306                    "  int baz;\n"
18307                    "  int qux;\r\n"
18308                    "};",
18309                    style));
18310   style.UseCRLF = true;
18311   EXPECT_EQ("union FooBarBazQux {\r\n"
18312             "  int foo;\r\n"
18313             "  int bar;\r\n"
18314             "  int baz;\r\n"
18315             "  int qux;\r\n"
18316             "};",
18317             format("union FooBarBazQux {\r\n"
18318                    "  int foo;\n"
18319                    "  int bar;\r\n"
18320                    "  int baz;\n"
18321                    "  int qux;\n"
18322                    "};",
18323                    style));
18324 
18325   style.DeriveLineEnding = true;
18326   style.UseCRLF = false;
18327   EXPECT_EQ("union FooBarBazQux {\r\n"
18328             "  int foo;\r\n"
18329             "  int bar;\r\n"
18330             "  int baz;\r\n"
18331             "  int qux;\r\n"
18332             "};",
18333             format("union FooBarBazQux {\r\n"
18334                    "  int foo;\n"
18335                    "  int bar;\r\n"
18336                    "  int baz;\n"
18337                    "  int qux;\r\n"
18338                    "};",
18339                    style));
18340   style.UseCRLF = true;
18341   EXPECT_EQ("union FooBarBazQux {\n"
18342             "  int foo;\n"
18343             "  int bar;\n"
18344             "  int baz;\n"
18345             "  int qux;\n"
18346             "};",
18347             format("union FooBarBazQux {\r\n"
18348                    "  int foo;\n"
18349                    "  int bar;\r\n"
18350                    "  int baz;\n"
18351                    "  int qux;\n"
18352                    "};",
18353                    style));
18354 }
18355 
18356 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
18357   verifyFormat("MY_CLASS(C) {\n"
18358                "  int i;\n"
18359                "  int j;\n"
18360                "};");
18361 }
18362 
18363 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
18364   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
18365   TwoIndent.ContinuationIndentWidth = 2;
18366 
18367   EXPECT_EQ("int i =\n"
18368             "  longFunction(\n"
18369             "    arg);",
18370             format("int i = longFunction(arg);", TwoIndent));
18371 
18372   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
18373   SixIndent.ContinuationIndentWidth = 6;
18374 
18375   EXPECT_EQ("int i =\n"
18376             "      longFunction(\n"
18377             "            arg);",
18378             format("int i = longFunction(arg);", SixIndent));
18379 }
18380 
18381 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
18382   FormatStyle Style = getLLVMStyle();
18383   verifyFormat("int Foo::getter(\n"
18384                "    //\n"
18385                ") const {\n"
18386                "  return foo;\n"
18387                "}",
18388                Style);
18389   verifyFormat("void Foo::setter(\n"
18390                "    //\n"
18391                ") {\n"
18392                "  foo = 1;\n"
18393                "}",
18394                Style);
18395 }
18396 
18397 TEST_F(FormatTest, SpacesInAngles) {
18398   FormatStyle Spaces = getLLVMStyle();
18399   Spaces.SpacesInAngles = true;
18400 
18401   verifyFormat("static_cast< int >(arg);", Spaces);
18402   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
18403   verifyFormat("f< int, float >();", Spaces);
18404   verifyFormat("template <> g() {}", Spaces);
18405   verifyFormat("template < std::vector< int > > f() {}", Spaces);
18406   verifyFormat("std::function< void(int, int) > fct;", Spaces);
18407   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
18408                Spaces);
18409 
18410   Spaces.Standard = FormatStyle::LS_Cpp03;
18411   Spaces.SpacesInAngles = true;
18412   verifyFormat("A< A< int > >();", Spaces);
18413 
18414   Spaces.SpacesInAngles = false;
18415   verifyFormat("A<A<int> >();", Spaces);
18416 
18417   Spaces.Standard = FormatStyle::LS_Cpp11;
18418   Spaces.SpacesInAngles = true;
18419   verifyFormat("A< A< int > >();", Spaces);
18420 
18421   Spaces.SpacesInAngles = false;
18422   verifyFormat("A<A<int>>();", Spaces);
18423 }
18424 
18425 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
18426   FormatStyle Style = getLLVMStyle();
18427   Style.SpaceAfterTemplateKeyword = false;
18428   verifyFormat("template<int> void foo();", Style);
18429 }
18430 
18431 TEST_F(FormatTest, TripleAngleBrackets) {
18432   verifyFormat("f<<<1, 1>>>();");
18433   verifyFormat("f<<<1, 1, 1, s>>>();");
18434   verifyFormat("f<<<a, b, c, d>>>();");
18435   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
18436   verifyFormat("f<param><<<1, 1>>>();");
18437   verifyFormat("f<1><<<1, 1>>>();");
18438   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
18439   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
18440                "aaaaaaaaaaa<<<\n    1, 1>>>();");
18441   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
18442                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
18443 }
18444 
18445 TEST_F(FormatTest, MergeLessLessAtEnd) {
18446   verifyFormat("<<");
18447   EXPECT_EQ("< < <", format("\\\n<<<"));
18448   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
18449                "aaallvm::outs() <<");
18450   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
18451                "aaaallvm::outs()\n    <<");
18452 }
18453 
18454 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
18455   std::string code = "#if A\n"
18456                      "#if B\n"
18457                      "a.\n"
18458                      "#endif\n"
18459                      "    a = 1;\n"
18460                      "#else\n"
18461                      "#endif\n"
18462                      "#if C\n"
18463                      "#else\n"
18464                      "#endif\n";
18465   EXPECT_EQ(code, format(code));
18466 }
18467 
18468 TEST_F(FormatTest, HandleConflictMarkers) {
18469   // Git/SVN conflict markers.
18470   EXPECT_EQ("int a;\n"
18471             "void f() {\n"
18472             "  callme(some(parameter1,\n"
18473             "<<<<<<< text by the vcs\n"
18474             "              parameter2),\n"
18475             "||||||| text by the vcs\n"
18476             "              parameter2),\n"
18477             "         parameter3,\n"
18478             "======= text by the vcs\n"
18479             "              parameter2, parameter3),\n"
18480             ">>>>>>> text by the vcs\n"
18481             "         otherparameter);\n",
18482             format("int a;\n"
18483                    "void f() {\n"
18484                    "  callme(some(parameter1,\n"
18485                    "<<<<<<< text by the vcs\n"
18486                    "  parameter2),\n"
18487                    "||||||| text by the vcs\n"
18488                    "  parameter2),\n"
18489                    "  parameter3,\n"
18490                    "======= text by the vcs\n"
18491                    "  parameter2,\n"
18492                    "  parameter3),\n"
18493                    ">>>>>>> text by the vcs\n"
18494                    "  otherparameter);\n"));
18495 
18496   // Perforce markers.
18497   EXPECT_EQ("void f() {\n"
18498             "  function(\n"
18499             ">>>> text by the vcs\n"
18500             "      parameter,\n"
18501             "==== text by the vcs\n"
18502             "      parameter,\n"
18503             "==== text by the vcs\n"
18504             "      parameter,\n"
18505             "<<<< text by the vcs\n"
18506             "      parameter);\n",
18507             format("void f() {\n"
18508                    "  function(\n"
18509                    ">>>> text by the vcs\n"
18510                    "  parameter,\n"
18511                    "==== text by the vcs\n"
18512                    "  parameter,\n"
18513                    "==== text by the vcs\n"
18514                    "  parameter,\n"
18515                    "<<<< text by the vcs\n"
18516                    "  parameter);\n"));
18517 
18518   EXPECT_EQ("<<<<<<<\n"
18519             "|||||||\n"
18520             "=======\n"
18521             ">>>>>>>",
18522             format("<<<<<<<\n"
18523                    "|||||||\n"
18524                    "=======\n"
18525                    ">>>>>>>"));
18526 
18527   EXPECT_EQ("<<<<<<<\n"
18528             "|||||||\n"
18529             "int i;\n"
18530             "=======\n"
18531             ">>>>>>>",
18532             format("<<<<<<<\n"
18533                    "|||||||\n"
18534                    "int i;\n"
18535                    "=======\n"
18536                    ">>>>>>>"));
18537 
18538   // FIXME: Handle parsing of macros around conflict markers correctly:
18539   EXPECT_EQ("#define Macro \\\n"
18540             "<<<<<<<\n"
18541             "Something \\\n"
18542             "|||||||\n"
18543             "Else \\\n"
18544             "=======\n"
18545             "Other \\\n"
18546             ">>>>>>>\n"
18547             "    End int i;\n",
18548             format("#define Macro \\\n"
18549                    "<<<<<<<\n"
18550                    "  Something \\\n"
18551                    "|||||||\n"
18552                    "  Else \\\n"
18553                    "=======\n"
18554                    "  Other \\\n"
18555                    ">>>>>>>\n"
18556                    "  End\n"
18557                    "int i;\n"));
18558 }
18559 
18560 TEST_F(FormatTest, DisableRegions) {
18561   EXPECT_EQ("int i;\n"
18562             "// clang-format off\n"
18563             "  int j;\n"
18564             "// clang-format on\n"
18565             "int k;",
18566             format(" int  i;\n"
18567                    "   // clang-format off\n"
18568                    "  int j;\n"
18569                    " // clang-format on\n"
18570                    "   int   k;"));
18571   EXPECT_EQ("int i;\n"
18572             "/* clang-format off */\n"
18573             "  int j;\n"
18574             "/* clang-format on */\n"
18575             "int k;",
18576             format(" int  i;\n"
18577                    "   /* clang-format off */\n"
18578                    "  int j;\n"
18579                    " /* clang-format on */\n"
18580                    "   int   k;"));
18581 
18582   // Don't reflow comments within disabled regions.
18583   EXPECT_EQ("// clang-format off\n"
18584             "// long long long long long long line\n"
18585             "/* clang-format on */\n"
18586             "/* long long long\n"
18587             " * long long long\n"
18588             " * line */\n"
18589             "int i;\n"
18590             "/* clang-format off */\n"
18591             "/* long long long long long long line */\n",
18592             format("// clang-format off\n"
18593                    "// long long long long long long line\n"
18594                    "/* clang-format on */\n"
18595                    "/* long long long long long long line */\n"
18596                    "int i;\n"
18597                    "/* clang-format off */\n"
18598                    "/* long long long long long long line */\n",
18599                    getLLVMStyleWithColumns(20)));
18600 }
18601 
18602 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
18603   format("? ) =");
18604   verifyNoCrash("#define a\\\n /**/}");
18605 }
18606 
18607 TEST_F(FormatTest, FormatsTableGenCode) {
18608   FormatStyle Style = getLLVMStyle();
18609   Style.Language = FormatStyle::LK_TableGen;
18610   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
18611 }
18612 
18613 TEST_F(FormatTest, ArrayOfTemplates) {
18614   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
18615             format("auto a = new unique_ptr<int > [ 10];"));
18616 
18617   FormatStyle Spaces = getLLVMStyle();
18618   Spaces.SpacesInSquareBrackets = true;
18619   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
18620             format("auto a = new unique_ptr<int > [10];", Spaces));
18621 }
18622 
18623 TEST_F(FormatTest, ArrayAsTemplateType) {
18624   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
18625             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
18626 
18627   FormatStyle Spaces = getLLVMStyle();
18628   Spaces.SpacesInSquareBrackets = true;
18629   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
18630             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
18631 }
18632 
18633 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
18634 
18635 TEST(FormatStyle, GetStyleWithEmptyFileName) {
18636   llvm::vfs::InMemoryFileSystem FS;
18637   auto Style1 = getStyle("file", "", "Google", "", &FS);
18638   ASSERT_TRUE((bool)Style1);
18639   ASSERT_EQ(*Style1, getGoogleStyle());
18640 }
18641 
18642 TEST(FormatStyle, GetStyleOfFile) {
18643   llvm::vfs::InMemoryFileSystem FS;
18644   // Test 1: format file in the same directory.
18645   ASSERT_TRUE(
18646       FS.addFile("/a/.clang-format", 0,
18647                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
18648   ASSERT_TRUE(
18649       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
18650   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
18651   ASSERT_TRUE((bool)Style1);
18652   ASSERT_EQ(*Style1, getLLVMStyle());
18653 
18654   // Test 2.1: fallback to default.
18655   ASSERT_TRUE(
18656       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
18657   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
18658   ASSERT_TRUE((bool)Style2);
18659   ASSERT_EQ(*Style2, getMozillaStyle());
18660 
18661   // Test 2.2: no format on 'none' fallback style.
18662   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
18663   ASSERT_TRUE((bool)Style2);
18664   ASSERT_EQ(*Style2, getNoStyle());
18665 
18666   // Test 2.3: format if config is found with no based style while fallback is
18667   // 'none'.
18668   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
18669                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
18670   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
18671   ASSERT_TRUE((bool)Style2);
18672   ASSERT_EQ(*Style2, getLLVMStyle());
18673 
18674   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
18675   Style2 = getStyle("{}", "a.h", "none", "", &FS);
18676   ASSERT_TRUE((bool)Style2);
18677   ASSERT_EQ(*Style2, getLLVMStyle());
18678 
18679   // Test 3: format file in parent directory.
18680   ASSERT_TRUE(
18681       FS.addFile("/c/.clang-format", 0,
18682                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
18683   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
18684                          llvm::MemoryBuffer::getMemBuffer("int i;")));
18685   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
18686   ASSERT_TRUE((bool)Style3);
18687   ASSERT_EQ(*Style3, getGoogleStyle());
18688 
18689   // Test 4: error on invalid fallback style
18690   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
18691   ASSERT_FALSE((bool)Style4);
18692   llvm::consumeError(Style4.takeError());
18693 
18694   // Test 5: error on invalid yaml on command line
18695   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
18696   ASSERT_FALSE((bool)Style5);
18697   llvm::consumeError(Style5.takeError());
18698 
18699   // Test 6: error on invalid style
18700   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
18701   ASSERT_FALSE((bool)Style6);
18702   llvm::consumeError(Style6.takeError());
18703 
18704   // Test 7: found config file, error on parsing it
18705   ASSERT_TRUE(
18706       FS.addFile("/d/.clang-format", 0,
18707                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
18708                                                   "InvalidKey: InvalidValue")));
18709   ASSERT_TRUE(
18710       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
18711   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
18712   ASSERT_FALSE((bool)Style7a);
18713   llvm::consumeError(Style7a.takeError());
18714 
18715   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
18716   ASSERT_TRUE((bool)Style7b);
18717 
18718   // Test 8: inferred per-language defaults apply.
18719   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
18720   ASSERT_TRUE((bool)StyleTd);
18721   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
18722 
18723   // Test 9.1: overwriting a file style, when parent no file exists with no
18724   // fallback style
18725   ASSERT_TRUE(FS.addFile(
18726       "/e/sub/.clang-format", 0,
18727       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
18728                                        "ColumnLimit: 20")));
18729   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
18730                          llvm::MemoryBuffer::getMemBuffer("int i;")));
18731   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
18732   ASSERT_TRUE(static_cast<bool>(Style9));
18733   ASSERT_EQ(*Style9, [] {
18734     auto Style = getNoStyle();
18735     Style.ColumnLimit = 20;
18736     return Style;
18737   }());
18738 
18739   // Test 9.2: with LLVM fallback style
18740   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
18741   ASSERT_TRUE(static_cast<bool>(Style9));
18742   ASSERT_EQ(*Style9, [] {
18743     auto Style = getLLVMStyle();
18744     Style.ColumnLimit = 20;
18745     return Style;
18746   }());
18747 
18748   // Test 9.3: with a parent file
18749   ASSERT_TRUE(
18750       FS.addFile("/e/.clang-format", 0,
18751                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
18752                                                   "UseTab: Always")));
18753   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
18754   ASSERT_TRUE(static_cast<bool>(Style9));
18755   ASSERT_EQ(*Style9, [] {
18756     auto Style = getGoogleStyle();
18757     Style.ColumnLimit = 20;
18758     Style.UseTab = FormatStyle::UT_Always;
18759     return Style;
18760   }());
18761 
18762   // Test 9.4: propagate more than one level
18763   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
18764                          llvm::MemoryBuffer::getMemBuffer("int i;")));
18765   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
18766                          llvm::MemoryBuffer::getMemBuffer(
18767                              "BasedOnStyle: InheritParentConfig\n"
18768                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
18769   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
18770 
18771   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
18772     auto Style = getGoogleStyle();
18773     Style.ColumnLimit = 20;
18774     Style.UseTab = FormatStyle::UT_Always;
18775     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
18776     return Style;
18777   }();
18778 
18779   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
18780   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
18781   ASSERT_TRUE(static_cast<bool>(Style9));
18782   ASSERT_EQ(*Style9, SubSubStyle);
18783 
18784   // Test 9.5: use InheritParentConfig as style name
18785   Style9 =
18786       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
18787   ASSERT_TRUE(static_cast<bool>(Style9));
18788   ASSERT_EQ(*Style9, SubSubStyle);
18789 
18790   // Test 9.6: use command line style with inheritance
18791   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
18792                     "none", "", &FS);
18793   ASSERT_TRUE(static_cast<bool>(Style9));
18794   ASSERT_EQ(*Style9, SubSubStyle);
18795 
18796   // Test 9.7: use command line style with inheritance and own config
18797   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
18798                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
18799                     "/e/sub/code.cpp", "none", "", &FS);
18800   ASSERT_TRUE(static_cast<bool>(Style9));
18801   ASSERT_EQ(*Style9, SubSubStyle);
18802 
18803   // Test 9.8: use inheritance from a file without BasedOnStyle
18804   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
18805                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
18806   ASSERT_TRUE(
18807       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
18808                  llvm::MemoryBuffer::getMemBuffer(
18809                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
18810   // Make sure we do not use the fallback style
18811   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
18812   ASSERT_TRUE(static_cast<bool>(Style9));
18813   ASSERT_EQ(*Style9, [] {
18814     auto Style = getLLVMStyle();
18815     Style.ColumnLimit = 123;
18816     return Style;
18817   }());
18818 
18819   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
18820   ASSERT_TRUE(static_cast<bool>(Style9));
18821   ASSERT_EQ(*Style9, [] {
18822     auto Style = getLLVMStyle();
18823     Style.ColumnLimit = 123;
18824     Style.IndentWidth = 7;
18825     return Style;
18826   }());
18827 }
18828 
18829 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
18830   // Column limit is 20.
18831   std::string Code = "Type *a =\n"
18832                      "    new Type();\n"
18833                      "g(iiiii, 0, jjjjj,\n"
18834                      "  0, kkkkk, 0, mm);\n"
18835                      "int  bad     = format   ;";
18836   std::string Expected = "auto a = new Type();\n"
18837                          "g(iiiii, nullptr,\n"
18838                          "  jjjjj, nullptr,\n"
18839                          "  kkkkk, nullptr,\n"
18840                          "  mm);\n"
18841                          "int  bad     = format   ;";
18842   FileID ID = Context.createInMemoryFile("format.cpp", Code);
18843   tooling::Replacements Replaces = toReplacements(
18844       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
18845                             "auto "),
18846        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
18847                             "nullptr"),
18848        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
18849                             "nullptr"),
18850        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
18851                             "nullptr")});
18852 
18853   format::FormatStyle Style = format::getLLVMStyle();
18854   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
18855   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
18856   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
18857       << llvm::toString(FormattedReplaces.takeError()) << "\n";
18858   auto Result = applyAllReplacements(Code, *FormattedReplaces);
18859   EXPECT_TRUE(static_cast<bool>(Result));
18860   EXPECT_EQ(Expected, *Result);
18861 }
18862 
18863 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
18864   std::string Code = "#include \"a.h\"\n"
18865                      "#include \"c.h\"\n"
18866                      "\n"
18867                      "int main() {\n"
18868                      "  return 0;\n"
18869                      "}";
18870   std::string Expected = "#include \"a.h\"\n"
18871                          "#include \"b.h\"\n"
18872                          "#include \"c.h\"\n"
18873                          "\n"
18874                          "int main() {\n"
18875                          "  return 0;\n"
18876                          "}";
18877   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
18878   tooling::Replacements Replaces = toReplacements(
18879       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
18880                             "#include \"b.h\"\n")});
18881 
18882   format::FormatStyle Style = format::getLLVMStyle();
18883   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
18884   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
18885   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
18886       << llvm::toString(FormattedReplaces.takeError()) << "\n";
18887   auto Result = applyAllReplacements(Code, *FormattedReplaces);
18888   EXPECT_TRUE(static_cast<bool>(Result));
18889   EXPECT_EQ(Expected, *Result);
18890 }
18891 
18892 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
18893   EXPECT_EQ("using std::cin;\n"
18894             "using std::cout;",
18895             format("using std::cout;\n"
18896                    "using std::cin;",
18897                    getGoogleStyle()));
18898 }
18899 
18900 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
18901   format::FormatStyle Style = format::getLLVMStyle();
18902   Style.Standard = FormatStyle::LS_Cpp03;
18903   // cpp03 recognize this string as identifier u8 and literal character 'a'
18904   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
18905 }
18906 
18907 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
18908   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
18909   // all modes, including C++11, C++14 and C++17
18910   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
18911 }
18912 
18913 TEST_F(FormatTest, DoNotFormatLikelyXml) {
18914   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
18915   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
18916 }
18917 
18918 TEST_F(FormatTest, StructuredBindings) {
18919   // Structured bindings is a C++17 feature.
18920   // all modes, including C++11, C++14 and C++17
18921   verifyFormat("auto [a, b] = f();");
18922   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
18923   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
18924   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
18925   EXPECT_EQ("auto const volatile [a, b] = f();",
18926             format("auto  const   volatile[a, b] = f();"));
18927   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
18928   EXPECT_EQ("auto &[a, b, c] = f();",
18929             format("auto   &[  a  ,  b,c   ] = f();"));
18930   EXPECT_EQ("auto &&[a, b, c] = f();",
18931             format("auto   &&[  a  ,  b,c   ] = f();"));
18932   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
18933   EXPECT_EQ("auto const volatile &&[a, b] = f();",
18934             format("auto  const  volatile  &&[a, b] = f();"));
18935   EXPECT_EQ("auto const &&[a, b] = f();",
18936             format("auto  const   &&  [a, b] = f();"));
18937   EXPECT_EQ("const auto &[a, b] = f();",
18938             format("const  auto  &  [a, b] = f();"));
18939   EXPECT_EQ("const auto volatile &&[a, b] = f();",
18940             format("const  auto   volatile  &&[a, b] = f();"));
18941   EXPECT_EQ("volatile const auto &&[a, b] = f();",
18942             format("volatile  const  auto   &&[a, b] = f();"));
18943   EXPECT_EQ("const auto &&[a, b] = f();",
18944             format("const  auto  &&  [a, b] = f();"));
18945 
18946   // Make sure we don't mistake structured bindings for lambdas.
18947   FormatStyle PointerMiddle = getLLVMStyle();
18948   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
18949   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
18950   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
18951   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
18952   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
18953   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
18954   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
18955   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
18956   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
18957   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
18958   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
18959   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
18960   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
18961 
18962   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
18963             format("for (const auto   &&   [a, b] : some_range) {\n}"));
18964   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
18965             format("for (const auto   &   [a, b] : some_range) {\n}"));
18966   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
18967             format("for (const auto[a, b] : some_range) {\n}"));
18968   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
18969   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
18970   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
18971   EXPECT_EQ("auto const &[x, y](expr);",
18972             format("auto  const  &  [x,y]  (expr);"));
18973   EXPECT_EQ("auto const &&[x, y](expr);",
18974             format("auto  const  &&  [x,y]  (expr);"));
18975   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
18976   EXPECT_EQ("auto const &[x, y]{expr};",
18977             format("auto  const  &  [x,y]  {expr};"));
18978   EXPECT_EQ("auto const &&[x, y]{expr};",
18979             format("auto  const  &&  [x,y]  {expr};"));
18980 
18981   format::FormatStyle Spaces = format::getLLVMStyle();
18982   Spaces.SpacesInSquareBrackets = true;
18983   verifyFormat("auto [ a, b ] = f();", Spaces);
18984   verifyFormat("auto &&[ a, b ] = f();", Spaces);
18985   verifyFormat("auto &[ a, b ] = f();", Spaces);
18986   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
18987   verifyFormat("auto const &[ a, b ] = f();", Spaces);
18988 }
18989 
18990 TEST_F(FormatTest, FileAndCode) {
18991   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
18992   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
18993   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
18994   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
18995   EXPECT_EQ(FormatStyle::LK_ObjC,
18996             guessLanguage("foo.h", "@interface Foo\n@end\n"));
18997   EXPECT_EQ(
18998       FormatStyle::LK_ObjC,
18999       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
19000   EXPECT_EQ(FormatStyle::LK_ObjC,
19001             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
19002   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
19003   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
19004   EXPECT_EQ(FormatStyle::LK_ObjC,
19005             guessLanguage("foo", "@interface Foo\n@end\n"));
19006   EXPECT_EQ(FormatStyle::LK_ObjC,
19007             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
19008   EXPECT_EQ(
19009       FormatStyle::LK_ObjC,
19010       guessLanguage("foo.h",
19011                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
19012   EXPECT_EQ(
19013       FormatStyle::LK_Cpp,
19014       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
19015 }
19016 
19017 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
19018   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
19019   EXPECT_EQ(FormatStyle::LK_ObjC,
19020             guessLanguage("foo.h", "array[[calculator getIndex]];"));
19021   EXPECT_EQ(FormatStyle::LK_Cpp,
19022             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
19023   EXPECT_EQ(
19024       FormatStyle::LK_Cpp,
19025       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
19026   EXPECT_EQ(FormatStyle::LK_ObjC,
19027             guessLanguage("foo.h", "[[noreturn foo] bar];"));
19028   EXPECT_EQ(FormatStyle::LK_Cpp,
19029             guessLanguage("foo.h", "[[clang::fallthrough]];"));
19030   EXPECT_EQ(FormatStyle::LK_ObjC,
19031             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
19032   EXPECT_EQ(FormatStyle::LK_Cpp,
19033             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
19034   EXPECT_EQ(FormatStyle::LK_Cpp,
19035             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
19036   EXPECT_EQ(FormatStyle::LK_ObjC,
19037             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
19038   EXPECT_EQ(FormatStyle::LK_Cpp,
19039             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
19040   EXPECT_EQ(
19041       FormatStyle::LK_Cpp,
19042       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
19043   EXPECT_EQ(
19044       FormatStyle::LK_Cpp,
19045       guessLanguage("foo.h",
19046                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
19047   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
19048 }
19049 
19050 TEST_F(FormatTest, GuessLanguageWithCaret) {
19051   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
19052   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
19053   EXPECT_EQ(FormatStyle::LK_ObjC,
19054             guessLanguage("foo.h", "int(^)(char, float);"));
19055   EXPECT_EQ(FormatStyle::LK_ObjC,
19056             guessLanguage("foo.h", "int(^foo)(char, float);"));
19057   EXPECT_EQ(FormatStyle::LK_ObjC,
19058             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
19059   EXPECT_EQ(FormatStyle::LK_ObjC,
19060             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
19061   EXPECT_EQ(
19062       FormatStyle::LK_ObjC,
19063       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
19064 }
19065 
19066 TEST_F(FormatTest, GuessLanguageWithPragmas) {
19067   EXPECT_EQ(FormatStyle::LK_Cpp,
19068             guessLanguage("foo.h", "__pragma(warning(disable:))"));
19069   EXPECT_EQ(FormatStyle::LK_Cpp,
19070             guessLanguage("foo.h", "#pragma(warning(disable:))"));
19071   EXPECT_EQ(FormatStyle::LK_Cpp,
19072             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
19073 }
19074 
19075 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
19076   // ASM symbolic names are identifiers that must be surrounded by [] without
19077   // space in between:
19078   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
19079 
19080   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
19081   verifyFormat(R"(//
19082 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
19083 )");
19084 
19085   // A list of several ASM symbolic names.
19086   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
19087 
19088   // ASM symbolic names in inline ASM with inputs and outputs.
19089   verifyFormat(R"(//
19090 asm("cmoveq %1, %2, %[result]"
19091     : [result] "=r"(result)
19092     : "r"(test), "r"(new), "[result]"(old));
19093 )");
19094 
19095   // ASM symbolic names in inline ASM with no outputs.
19096   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
19097 }
19098 
19099 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
19100   EXPECT_EQ(FormatStyle::LK_Cpp,
19101             guessLanguage("foo.h", "void f() {\n"
19102                                    "  asm (\"mov %[e], %[d]\"\n"
19103                                    "     : [d] \"=rm\" (d)\n"
19104                                    "       [e] \"rm\" (*e));\n"
19105                                    "}"));
19106   EXPECT_EQ(FormatStyle::LK_Cpp,
19107             guessLanguage("foo.h", "void f() {\n"
19108                                    "  _asm (\"mov %[e], %[d]\"\n"
19109                                    "     : [d] \"=rm\" (d)\n"
19110                                    "       [e] \"rm\" (*e));\n"
19111                                    "}"));
19112   EXPECT_EQ(FormatStyle::LK_Cpp,
19113             guessLanguage("foo.h", "void f() {\n"
19114                                    "  __asm (\"mov %[e], %[d]\"\n"
19115                                    "     : [d] \"=rm\" (d)\n"
19116                                    "       [e] \"rm\" (*e));\n"
19117                                    "}"));
19118   EXPECT_EQ(FormatStyle::LK_Cpp,
19119             guessLanguage("foo.h", "void f() {\n"
19120                                    "  __asm__ (\"mov %[e], %[d]\"\n"
19121                                    "     : [d] \"=rm\" (d)\n"
19122                                    "       [e] \"rm\" (*e));\n"
19123                                    "}"));
19124   EXPECT_EQ(FormatStyle::LK_Cpp,
19125             guessLanguage("foo.h", "void f() {\n"
19126                                    "  asm (\"mov %[e], %[d]\"\n"
19127                                    "     : [d] \"=rm\" (d),\n"
19128                                    "       [e] \"rm\" (*e));\n"
19129                                    "}"));
19130   EXPECT_EQ(FormatStyle::LK_Cpp,
19131             guessLanguage("foo.h", "void f() {\n"
19132                                    "  asm volatile (\"mov %[e], %[d]\"\n"
19133                                    "     : [d] \"=rm\" (d)\n"
19134                                    "       [e] \"rm\" (*e));\n"
19135                                    "}"));
19136 }
19137 
19138 TEST_F(FormatTest, GuessLanguageWithChildLines) {
19139   EXPECT_EQ(FormatStyle::LK_Cpp,
19140             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
19141   EXPECT_EQ(FormatStyle::LK_ObjC,
19142             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
19143   EXPECT_EQ(
19144       FormatStyle::LK_Cpp,
19145       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
19146   EXPECT_EQ(
19147       FormatStyle::LK_ObjC,
19148       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
19149 }
19150 
19151 TEST_F(FormatTest, TypenameMacros) {
19152   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
19153 
19154   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
19155   FormatStyle Google = getGoogleStyleWithColumns(0);
19156   Google.TypenameMacros = TypenameMacros;
19157   verifyFormat("struct foo {\n"
19158                "  int bar;\n"
19159                "  TAILQ_ENTRY(a) bleh;\n"
19160                "};",
19161                Google);
19162 
19163   FormatStyle Macros = getLLVMStyle();
19164   Macros.TypenameMacros = TypenameMacros;
19165 
19166   verifyFormat("STACK_OF(int) a;", Macros);
19167   verifyFormat("STACK_OF(int) *a;", Macros);
19168   verifyFormat("STACK_OF(int const *) *a;", Macros);
19169   verifyFormat("STACK_OF(int *const) *a;", Macros);
19170   verifyFormat("STACK_OF(int, string) a;", Macros);
19171   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
19172   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
19173   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
19174   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
19175   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
19176   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
19177 
19178   Macros.PointerAlignment = FormatStyle::PAS_Left;
19179   verifyFormat("STACK_OF(int)* a;", Macros);
19180   verifyFormat("STACK_OF(int*)* a;", Macros);
19181   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
19182   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
19183   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
19184 }
19185 
19186 TEST_F(FormatTest, AtomicQualifier) {
19187   // Check that we treate _Atomic as a type and not a function call
19188   FormatStyle Google = getGoogleStyleWithColumns(0);
19189   verifyFormat("struct foo {\n"
19190                "  int a1;\n"
19191                "  _Atomic(a) a2;\n"
19192                "  _Atomic(_Atomic(int) *const) a3;\n"
19193                "};",
19194                Google);
19195   verifyFormat("_Atomic(uint64_t) a;");
19196   verifyFormat("_Atomic(uint64_t) *a;");
19197   verifyFormat("_Atomic(uint64_t const *) *a;");
19198   verifyFormat("_Atomic(uint64_t *const) *a;");
19199   verifyFormat("_Atomic(const uint64_t *) *a;");
19200   verifyFormat("_Atomic(uint64_t) a;");
19201   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
19202   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
19203   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
19204   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
19205 
19206   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
19207   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
19208   FormatStyle Style = getLLVMStyle();
19209   Style.PointerAlignment = FormatStyle::PAS_Left;
19210   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
19211   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
19212   verifyFormat("_Atomic(int)* a;", Style);
19213   verifyFormat("_Atomic(int*)* a;", Style);
19214   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
19215 
19216   Style.SpacesInCStyleCastParentheses = true;
19217   Style.SpacesInParentheses = false;
19218   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
19219   Style.SpacesInCStyleCastParentheses = false;
19220   Style.SpacesInParentheses = true;
19221   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
19222   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
19223 }
19224 
19225 TEST_F(FormatTest, AmbersandInLamda) {
19226   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
19227   FormatStyle AlignStyle = getLLVMStyle();
19228   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
19229   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
19230   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
19231   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
19232 }
19233 
19234 TEST_F(FormatTest, SpacesInConditionalStatement) {
19235   FormatStyle Spaces = getLLVMStyle();
19236   Spaces.SpacesInConditionalStatement = true;
19237   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
19238   verifyFormat("if ( !a )\n  return;", Spaces);
19239   verifyFormat("if ( a )\n  return;", Spaces);
19240   verifyFormat("if constexpr ( a )\n  return;", Spaces);
19241   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
19242   verifyFormat("while ( a )\n  return;", Spaces);
19243   verifyFormat("while ( (a && b) )\n  return;", Spaces);
19244   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
19245   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
19246   // Check that space on the left of "::" is inserted as expected at beginning
19247   // of condition.
19248   verifyFormat("while ( ::func() )\n  return;", Spaces);
19249 }
19250 
19251 TEST_F(FormatTest, AlternativeOperators) {
19252   // Test case for ensuring alternate operators are not
19253   // combined with their right most neighbour.
19254   verifyFormat("int a and b;");
19255   verifyFormat("int a and_eq b;");
19256   verifyFormat("int a bitand b;");
19257   verifyFormat("int a bitor b;");
19258   verifyFormat("int a compl b;");
19259   verifyFormat("int a not b;");
19260   verifyFormat("int a not_eq b;");
19261   verifyFormat("int a or b;");
19262   verifyFormat("int a xor b;");
19263   verifyFormat("int a xor_eq b;");
19264   verifyFormat("return this not_eq bitand other;");
19265   verifyFormat("bool operator not_eq(const X bitand other)");
19266 
19267   verifyFormat("int a and 5;");
19268   verifyFormat("int a and_eq 5;");
19269   verifyFormat("int a bitand 5;");
19270   verifyFormat("int a bitor 5;");
19271   verifyFormat("int a compl 5;");
19272   verifyFormat("int a not 5;");
19273   verifyFormat("int a not_eq 5;");
19274   verifyFormat("int a or 5;");
19275   verifyFormat("int a xor 5;");
19276   verifyFormat("int a xor_eq 5;");
19277 
19278   verifyFormat("int a compl(5);");
19279   verifyFormat("int a not(5);");
19280 
19281   /* FIXME handle alternate tokens
19282    * https://en.cppreference.com/w/cpp/language/operator_alternative
19283   // alternative tokens
19284   verifyFormat("compl foo();");     //  ~foo();
19285   verifyFormat("foo() <%%>;");      // foo();
19286   verifyFormat("void foo() <%%>;"); // void foo(){}
19287   verifyFormat("int a <:1:>;");     // int a[1];[
19288   verifyFormat("%:define ABC abc"); // #define ABC abc
19289   verifyFormat("%:%:");             // ##
19290   */
19291 }
19292 
19293 TEST_F(FormatTest, STLWhileNotDefineChed) {
19294   verifyFormat("#if defined(while)\n"
19295                "#define while EMIT WARNING C4005\n"
19296                "#endif // while");
19297 }
19298 
19299 TEST_F(FormatTest, OperatorSpacing) {
19300   FormatStyle Style = getLLVMStyle();
19301   Style.PointerAlignment = FormatStyle::PAS_Right;
19302   verifyFormat("Foo::operator*();", Style);
19303   verifyFormat("Foo::operator void *();", Style);
19304   verifyFormat("Foo::operator void **();", Style);
19305   verifyFormat("Foo::operator void *&();", Style);
19306   verifyFormat("Foo::operator void *&&();", Style);
19307   verifyFormat("Foo::operator void const *();", Style);
19308   verifyFormat("Foo::operator void const **();", Style);
19309   verifyFormat("Foo::operator void const *&();", Style);
19310   verifyFormat("Foo::operator void const *&&();", Style);
19311   verifyFormat("Foo::operator()(void *);", Style);
19312   verifyFormat("Foo::operator*(void *);", Style);
19313   verifyFormat("Foo::operator*();", Style);
19314   verifyFormat("Foo::operator**();", Style);
19315   verifyFormat("Foo::operator&();", Style);
19316   verifyFormat("Foo::operator<int> *();", Style);
19317   verifyFormat("Foo::operator<Foo> *();", Style);
19318   verifyFormat("Foo::operator<int> **();", Style);
19319   verifyFormat("Foo::operator<Foo> **();", Style);
19320   verifyFormat("Foo::operator<int> &();", Style);
19321   verifyFormat("Foo::operator<Foo> &();", Style);
19322   verifyFormat("Foo::operator<int> &&();", Style);
19323   verifyFormat("Foo::operator<Foo> &&();", Style);
19324   verifyFormat("Foo::operator<int> *&();", Style);
19325   verifyFormat("Foo::operator<Foo> *&();", Style);
19326   verifyFormat("Foo::operator<int> *&&();", Style);
19327   verifyFormat("Foo::operator<Foo> *&&();", Style);
19328   verifyFormat("operator*(int (*)(), class Foo);", Style);
19329 
19330   verifyFormat("Foo::operator&();", Style);
19331   verifyFormat("Foo::operator void &();", Style);
19332   verifyFormat("Foo::operator void const &();", Style);
19333   verifyFormat("Foo::operator()(void &);", Style);
19334   verifyFormat("Foo::operator&(void &);", Style);
19335   verifyFormat("Foo::operator&();", Style);
19336   verifyFormat("operator&(int (&)(), class Foo);", Style);
19337 
19338   verifyFormat("Foo::operator&&();", Style);
19339   verifyFormat("Foo::operator**();", Style);
19340   verifyFormat("Foo::operator void &&();", Style);
19341   verifyFormat("Foo::operator void const &&();", Style);
19342   verifyFormat("Foo::operator()(void &&);", Style);
19343   verifyFormat("Foo::operator&&(void &&);", Style);
19344   verifyFormat("Foo::operator&&();", Style);
19345   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
19346   verifyFormat("operator const nsTArrayRight<E> &()", Style);
19347   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
19348                Style);
19349   verifyFormat("operator void **()", Style);
19350   verifyFormat("operator const FooRight<Object> &()", Style);
19351   verifyFormat("operator const FooRight<Object> *()", Style);
19352   verifyFormat("operator const FooRight<Object> **()", Style);
19353   verifyFormat("operator const FooRight<Object> *&()", Style);
19354   verifyFormat("operator const FooRight<Object> *&&()", Style);
19355 
19356   Style.PointerAlignment = FormatStyle::PAS_Left;
19357   verifyFormat("Foo::operator*();", Style);
19358   verifyFormat("Foo::operator**();", Style);
19359   verifyFormat("Foo::operator void*();", Style);
19360   verifyFormat("Foo::operator void**();", Style);
19361   verifyFormat("Foo::operator void*&();", Style);
19362   verifyFormat("Foo::operator void*&&();", Style);
19363   verifyFormat("Foo::operator void const*();", Style);
19364   verifyFormat("Foo::operator void const**();", Style);
19365   verifyFormat("Foo::operator void const*&();", Style);
19366   verifyFormat("Foo::operator void const*&&();", Style);
19367   verifyFormat("Foo::operator/*comment*/ void*();", Style);
19368   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
19369   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
19370   verifyFormat("Foo::operator()(void*);", Style);
19371   verifyFormat("Foo::operator*(void*);", Style);
19372   verifyFormat("Foo::operator*();", Style);
19373   verifyFormat("Foo::operator<int>*();", Style);
19374   verifyFormat("Foo::operator<Foo>*();", Style);
19375   verifyFormat("Foo::operator<int>**();", Style);
19376   verifyFormat("Foo::operator<Foo>**();", Style);
19377   verifyFormat("Foo::operator<Foo>*&();", Style);
19378   verifyFormat("Foo::operator<int>&();", Style);
19379   verifyFormat("Foo::operator<Foo>&();", Style);
19380   verifyFormat("Foo::operator<int>&&();", Style);
19381   verifyFormat("Foo::operator<Foo>&&();", Style);
19382   verifyFormat("Foo::operator<int>*&();", Style);
19383   verifyFormat("Foo::operator<Foo>*&();", Style);
19384   verifyFormat("operator*(int (*)(), class Foo);", Style);
19385 
19386   verifyFormat("Foo::operator&();", Style);
19387   verifyFormat("Foo::operator void&();", Style);
19388   verifyFormat("Foo::operator void const&();", Style);
19389   verifyFormat("Foo::operator/*comment*/ void&();", Style);
19390   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
19391   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
19392   verifyFormat("Foo::operator()(void&);", Style);
19393   verifyFormat("Foo::operator&(void&);", Style);
19394   verifyFormat("Foo::operator&();", Style);
19395   verifyFormat("operator&(int (&)(), class Foo);", Style);
19396 
19397   verifyFormat("Foo::operator&&();", Style);
19398   verifyFormat("Foo::operator void&&();", Style);
19399   verifyFormat("Foo::operator void const&&();", Style);
19400   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
19401   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
19402   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
19403   verifyFormat("Foo::operator()(void&&);", Style);
19404   verifyFormat("Foo::operator&&(void&&);", Style);
19405   verifyFormat("Foo::operator&&();", Style);
19406   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
19407   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
19408   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
19409                Style);
19410   verifyFormat("operator void**()", Style);
19411   verifyFormat("operator const FooLeft<Object>&()", Style);
19412   verifyFormat("operator const FooLeft<Object>*()", Style);
19413   verifyFormat("operator const FooLeft<Object>**()", Style);
19414   verifyFormat("operator const FooLeft<Object>*&()", Style);
19415   verifyFormat("operator const FooLeft<Object>*&&()", Style);
19416 
19417   // PR45107
19418   verifyFormat("operator Vector<String>&();", Style);
19419   verifyFormat("operator const Vector<String>&();", Style);
19420   verifyFormat("operator foo::Bar*();", Style);
19421   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
19422   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
19423                Style);
19424 
19425   Style.PointerAlignment = FormatStyle::PAS_Middle;
19426   verifyFormat("Foo::operator*();", Style);
19427   verifyFormat("Foo::operator 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()(void &);", Style);
19437   verifyFormat("Foo::operator&(void &);", Style);
19438   verifyFormat("Foo::operator&();", Style);
19439   verifyFormat("operator&(int (&)(), class Foo);", Style);
19440 
19441   verifyFormat("Foo::operator&&();", Style);
19442   verifyFormat("Foo::operator void &&();", Style);
19443   verifyFormat("Foo::operator void const &&();", Style);
19444   verifyFormat("Foo::operator()(void &&);", Style);
19445   verifyFormat("Foo::operator&&(void &&);", Style);
19446   verifyFormat("Foo::operator&&();", Style);
19447   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
19448 }
19449 
19450 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
19451   FormatStyle Style = getLLVMStyle();
19452   // PR46157
19453   verifyFormat("foo(operator+, -42);", Style);
19454   verifyFormat("foo(operator++, -42);", Style);
19455   verifyFormat("foo(operator--, -42);", Style);
19456   verifyFormat("foo(-42, operator--);", Style);
19457   verifyFormat("foo(-42, operator, );", Style);
19458   verifyFormat("foo(operator, , -42);", Style);
19459 }
19460 
19461 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
19462   FormatStyle Style = getLLVMStyle();
19463   Style.WhitespaceSensitiveMacros.push_back("FOO");
19464 
19465   // Don't use the helpers here, since 'mess up' will change the whitespace
19466   // and these are all whitespace sensitive by definition
19467   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
19468             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
19469   EXPECT_EQ(
19470       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
19471       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
19472   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
19473             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
19474   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
19475             "       Still=Intentional);",
19476             format("FOO(String-ized&Messy+But,: :\n"
19477                    "       Still=Intentional);",
19478                    Style));
19479   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
19480   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
19481             "       Still=Intentional);",
19482             format("FOO(String-ized=&Messy+But,: :\n"
19483                    "       Still=Intentional);",
19484                    Style));
19485 
19486   Style.ColumnLimit = 21;
19487   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
19488             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
19489 }
19490 
19491 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
19492   // These tests are not in NamespaceFixer because that doesn't
19493   // test its interaction with line wrapping
19494   FormatStyle Style = getLLVMStyle();
19495   Style.ColumnLimit = 80;
19496   verifyFormat("namespace {\n"
19497                "int i;\n"
19498                "int j;\n"
19499                "} // namespace",
19500                Style);
19501 
19502   verifyFormat("namespace AAA {\n"
19503                "int i;\n"
19504                "int j;\n"
19505                "} // namespace AAA",
19506                Style);
19507 
19508   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
19509             "int i;\n"
19510             "int j;\n"
19511             "} // namespace Averyveryveryverylongnamespace",
19512             format("namespace Averyveryveryverylongnamespace {\n"
19513                    "int i;\n"
19514                    "int j;\n"
19515                    "}",
19516                    Style));
19517 
19518   EXPECT_EQ(
19519       "namespace "
19520       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
19521       "    went::mad::now {\n"
19522       "int i;\n"
19523       "int j;\n"
19524       "} // namespace\n"
19525       "  // "
19526       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
19527       "went::mad::now",
19528       format("namespace "
19529              "would::it::save::you::a::lot::of::time::if_::i::"
19530              "just::gave::up::and_::went::mad::now {\n"
19531              "int i;\n"
19532              "int j;\n"
19533              "}",
19534              Style));
19535 
19536   // This used to duplicate the comment again and again on subsequent runs
19537   EXPECT_EQ(
19538       "namespace "
19539       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
19540       "    went::mad::now {\n"
19541       "int i;\n"
19542       "int j;\n"
19543       "} // namespace\n"
19544       "  // "
19545       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
19546       "went::mad::now",
19547       format("namespace "
19548              "would::it::save::you::a::lot::of::time::if_::i::"
19549              "just::gave::up::and_::went::mad::now {\n"
19550              "int i;\n"
19551              "int j;\n"
19552              "} // namespace\n"
19553              "  // "
19554              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
19555              "and_::went::mad::now",
19556              Style));
19557 }
19558 
19559 TEST_F(FormatTest, LikelyUnlikely) {
19560   FormatStyle Style = getLLVMStyle();
19561 
19562   verifyFormat("if (argc > 5) [[unlikely]] {\n"
19563                "  return 29;\n"
19564                "}",
19565                Style);
19566 
19567   verifyFormat("if (argc > 5) [[likely]] {\n"
19568                "  return 29;\n"
19569                "}",
19570                Style);
19571 
19572   verifyFormat("if (argc > 5) [[unlikely]] {\n"
19573                "  return 29;\n"
19574                "} else [[likely]] {\n"
19575                "  return 42;\n"
19576                "}\n",
19577                Style);
19578 
19579   verifyFormat("if (argc > 5) [[unlikely]] {\n"
19580                "  return 29;\n"
19581                "} else if (argc > 10) [[likely]] {\n"
19582                "  return 99;\n"
19583                "} else {\n"
19584                "  return 42;\n"
19585                "}\n",
19586                Style);
19587 
19588   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
19589                "  return 29;\n"
19590                "}",
19591                Style);
19592 }
19593 
19594 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
19595   verifyFormat("Constructor()\n"
19596                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19597                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
19598                "aaaaaaaaaaaaaaaaaat))");
19599   verifyFormat("Constructor()\n"
19600                "    : aaaaaaaaaaaaa(aaaaaa), "
19601                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
19602 
19603   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
19604   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
19605   verifyFormat("Constructor()\n"
19606                "    : aaaaaa(aaaaaa),\n"
19607                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19608                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
19609                StyleWithWhitespacePenalty);
19610   verifyFormat("Constructor()\n"
19611                "    : aaaaaaaaaaaaa(aaaaaa), "
19612                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
19613                StyleWithWhitespacePenalty);
19614 }
19615 
19616 TEST_F(FormatTest, LLVMDefaultStyle) {
19617   FormatStyle Style = getLLVMStyle();
19618   verifyFormat("extern \"C\" {\n"
19619                "int foo();\n"
19620                "}",
19621                Style);
19622 }
19623 TEST_F(FormatTest, GNUDefaultStyle) {
19624   FormatStyle Style = getGNUStyle();
19625   verifyFormat("extern \"C\"\n"
19626                "{\n"
19627                "  int foo ();\n"
19628                "}",
19629                Style);
19630 }
19631 TEST_F(FormatTest, MozillaDefaultStyle) {
19632   FormatStyle Style = getMozillaStyle();
19633   verifyFormat("extern \"C\"\n"
19634                "{\n"
19635                "  int foo();\n"
19636                "}",
19637                Style);
19638 }
19639 TEST_F(FormatTest, GoogleDefaultStyle) {
19640   FormatStyle Style = getGoogleStyle();
19641   verifyFormat("extern \"C\" {\n"
19642                "int foo();\n"
19643                "}",
19644                Style);
19645 }
19646 TEST_F(FormatTest, ChromiumDefaultStyle) {
19647   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
19648   verifyFormat("extern \"C\" {\n"
19649                "int foo();\n"
19650                "}",
19651                Style);
19652 }
19653 TEST_F(FormatTest, MicrosoftDefaultStyle) {
19654   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
19655   verifyFormat("extern \"C\"\n"
19656                "{\n"
19657                "    int foo();\n"
19658                "}",
19659                Style);
19660 }
19661 TEST_F(FormatTest, WebKitDefaultStyle) {
19662   FormatStyle Style = getWebKitStyle();
19663   verifyFormat("extern \"C\" {\n"
19664                "int foo();\n"
19665                "}",
19666                Style);
19667 }
19668 
19669 TEST_F(FormatTest, ConceptsAndRequires) {
19670   FormatStyle Style = getLLVMStyle();
19671   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
19672 
19673   verifyFormat("template <typename T>\n"
19674                "concept Hashable = requires(T a) {\n"
19675                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
19676                "};",
19677                Style);
19678   verifyFormat("template <typename T>\n"
19679                "concept EqualityComparable = requires(T a, T b) {\n"
19680                "  { a == b } -> bool;\n"
19681                "};",
19682                Style);
19683   verifyFormat("template <typename T>\n"
19684                "concept EqualityComparable = requires(T a, T b) {\n"
19685                "  { a == b } -> bool;\n"
19686                "  { a != b } -> bool;\n"
19687                "};",
19688                Style);
19689   verifyFormat("template <typename T>\n"
19690                "concept EqualityComparable = requires(T a, T b) {\n"
19691                "  { a == b } -> bool;\n"
19692                "  { a != b } -> bool;\n"
19693                "};",
19694                Style);
19695 
19696   verifyFormat("template <typename It>\n"
19697                "requires Iterator<It>\n"
19698                "void sort(It begin, It end) {\n"
19699                "  //....\n"
19700                "}",
19701                Style);
19702 
19703   verifyFormat("template <typename T>\n"
19704                "concept Large = sizeof(T) > 10;",
19705                Style);
19706 
19707   verifyFormat("template <typename T, typename U>\n"
19708                "concept FooableWith = requires(T t, U u) {\n"
19709                "  typename T::foo_type;\n"
19710                "  { t.foo(u) } -> typename T::foo_type;\n"
19711                "  t++;\n"
19712                "};\n"
19713                "void doFoo(FooableWith<int> auto t) {\n"
19714                "  t.foo(3);\n"
19715                "}",
19716                Style);
19717   verifyFormat("template <typename T>\n"
19718                "concept Context = sizeof(T) == 1;",
19719                Style);
19720   verifyFormat("template <typename T>\n"
19721                "concept Context = is_specialization_of_v<context, T>;",
19722                Style);
19723   verifyFormat("template <typename T>\n"
19724                "concept Node = std::is_object_v<T>;",
19725                Style);
19726   verifyFormat("template <typename T>\n"
19727                "concept Tree = true;",
19728                Style);
19729 
19730   verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
19731                "  //...\n"
19732                "}",
19733                Style);
19734 
19735   verifyFormat(
19736       "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
19737       "  //...\n"
19738       "}",
19739       Style);
19740 
19741   verifyFormat(
19742       "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
19743       "  //...\n"
19744       "}",
19745       Style);
19746 
19747   verifyFormat("template <typename T>\n"
19748                "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
19749                "Concept2<I> {\n"
19750                "  //...\n"
19751                "}",
19752                Style);
19753 
19754   verifyFormat("template <typename T>\n"
19755                "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
19756                "Concept2<I> {\n"
19757                "  //...\n"
19758                "}",
19759                Style);
19760 
19761   verifyFormat(
19762       "template <typename T>\n"
19763       "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
19764       "  //...\n"
19765       "}",
19766       Style);
19767 
19768   verifyFormat(
19769       "template <typename T>\n"
19770       "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
19771       "  //...\n"
19772       "}",
19773       Style);
19774 
19775   verifyFormat("template <typename It>\n"
19776                "requires Foo<It>() && Bar<It> {\n"
19777                "  //....\n"
19778                "}",
19779                Style);
19780 
19781   verifyFormat("template <typename It>\n"
19782                "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
19783                "  //....\n"
19784                "}",
19785                Style);
19786 
19787   verifyFormat("template <typename It>\n"
19788                "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
19789                "  //....\n"
19790                "}",
19791                Style);
19792 
19793   verifyFormat(
19794       "template <typename It>\n"
19795       "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
19796       "  //....\n"
19797       "}",
19798       Style);
19799 
19800   Style.IndentRequires = true;
19801   verifyFormat("template <typename It>\n"
19802                "  requires Iterator<It>\n"
19803                "void sort(It begin, It end) {\n"
19804                "  //....\n"
19805                "}",
19806                Style);
19807   verifyFormat("template <std::size index_>\n"
19808                "  requires(index_ < sizeof...(Children_))\n"
19809                "Tree auto &child() {\n"
19810                "  // ...\n"
19811                "}",
19812                Style);
19813 
19814   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
19815   verifyFormat("template <typename T>\n"
19816                "concept Hashable = requires (T a) {\n"
19817                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
19818                "};",
19819                Style);
19820 
19821   verifyFormat("template <class T = void>\n"
19822                "  requires EqualityComparable<T> || Same<T, void>\n"
19823                "struct equal_to;",
19824                Style);
19825 
19826   verifyFormat("template <class T>\n"
19827                "  requires requires {\n"
19828                "    T{};\n"
19829                "    T (int);\n"
19830                "  }\n",
19831                Style);
19832 
19833   Style.ColumnLimit = 78;
19834   verifyFormat("template <typename T>\n"
19835                "concept Context = Traits<typename T::traits_type> and\n"
19836                "    Interface<typename T::interface_type> and\n"
19837                "    Request<typename T::request_type> and\n"
19838                "    Response<typename T::response_type> and\n"
19839                "    ContextExtension<typename T::extension_type> and\n"
19840                "    ::std::is_copy_constructable<T> and "
19841                "::std::is_move_constructable<T> and\n"
19842                "    requires (T c) {\n"
19843                "  { c.response; } -> Response;\n"
19844                "} and requires (T c) {\n"
19845                "  { c.request; } -> Request;\n"
19846                "}\n",
19847                Style);
19848 
19849   verifyFormat("template <typename T>\n"
19850                "concept Context = Traits<typename T::traits_type> or\n"
19851                "    Interface<typename T::interface_type> or\n"
19852                "    Request<typename T::request_type> or\n"
19853                "    Response<typename T::response_type> or\n"
19854                "    ContextExtension<typename T::extension_type> or\n"
19855                "    ::std::is_copy_constructable<T> or "
19856                "::std::is_move_constructable<T> or\n"
19857                "    requires (T c) {\n"
19858                "  { c.response; } -> Response;\n"
19859                "} or requires (T c) {\n"
19860                "  { c.request; } -> Request;\n"
19861                "}\n",
19862                Style);
19863 
19864   verifyFormat("template <typename T>\n"
19865                "concept Context = Traits<typename T::traits_type> &&\n"
19866                "    Interface<typename T::interface_type> &&\n"
19867                "    Request<typename T::request_type> &&\n"
19868                "    Response<typename T::response_type> &&\n"
19869                "    ContextExtension<typename T::extension_type> &&\n"
19870                "    ::std::is_copy_constructable<T> && "
19871                "::std::is_move_constructable<T> &&\n"
19872                "    requires (T c) {\n"
19873                "  { c.response; } -> Response;\n"
19874                "} && requires (T c) {\n"
19875                "  { c.request; } -> Request;\n"
19876                "}\n",
19877                Style);
19878 
19879   verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
19880                "Constraint2<T>;");
19881 
19882   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
19883   Style.BraceWrapping.AfterFunction = true;
19884   Style.BraceWrapping.AfterClass = true;
19885   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
19886   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
19887   verifyFormat("void Foo () requires (std::copyable<T>)\n"
19888                "{\n"
19889                "  return\n"
19890                "}\n",
19891                Style);
19892 
19893   verifyFormat("void Foo () requires std::copyable<T>\n"
19894                "{\n"
19895                "  return\n"
19896                "}\n",
19897                Style);
19898 
19899   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
19900                "  requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
19901                "struct constant;",
19902                Style);
19903 
19904   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
19905                "  requires std::invocable<F, std::invoke_result_t<Args>...>\n"
19906                "struct constant;",
19907                Style);
19908 
19909   verifyFormat("template <class T>\n"
19910                "class plane_with_very_very_very_long_name\n"
19911                "{\n"
19912                "  constexpr plane_with_very_very_very_long_name () requires "
19913                "std::copyable<T>\n"
19914                "      : plane_with_very_very_very_long_name (1)\n"
19915                "  {\n"
19916                "  }\n"
19917                "}\n",
19918                Style);
19919 
19920   verifyFormat("template <class T>\n"
19921                "class plane_with_long_name\n"
19922                "{\n"
19923                "  constexpr plane_with_long_name () requires std::copyable<T>\n"
19924                "      : plane_with_long_name (1)\n"
19925                "  {\n"
19926                "  }\n"
19927                "}\n",
19928                Style);
19929 
19930   Style.BreakBeforeConceptDeclarations = false;
19931   verifyFormat("template <typename T> concept Tree = true;", Style);
19932 
19933   Style.IndentRequires = false;
19934   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
19935                "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
19936                "struct constant;",
19937                Style);
19938 }
19939 
19940 TEST_F(FormatTest, StatementAttributeLikeMacros) {
19941   FormatStyle Style = getLLVMStyle();
19942   StringRef Source = "void Foo::slot() {\n"
19943                      "  unsigned char MyChar = 'x';\n"
19944                      "  emit signal(MyChar);\n"
19945                      "  Q_EMIT signal(MyChar);\n"
19946                      "}";
19947 
19948   EXPECT_EQ(Source, format(Source, Style));
19949 
19950   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
19951   EXPECT_EQ("void Foo::slot() {\n"
19952             "  unsigned char MyChar = 'x';\n"
19953             "  emit          signal(MyChar);\n"
19954             "  Q_EMIT signal(MyChar);\n"
19955             "}",
19956             format(Source, Style));
19957 
19958   Style.StatementAttributeLikeMacros.push_back("emit");
19959   EXPECT_EQ(Source, format(Source, Style));
19960 
19961   Style.StatementAttributeLikeMacros = {};
19962   EXPECT_EQ("void Foo::slot() {\n"
19963             "  unsigned char MyChar = 'x';\n"
19964             "  emit          signal(MyChar);\n"
19965             "  Q_EMIT        signal(MyChar);\n"
19966             "}",
19967             format(Source, Style));
19968 }
19969 
19970 TEST_F(FormatTest, IndentAccessModifiers) {
19971   FormatStyle Style = getLLVMStyle();
19972   Style.IndentAccessModifiers = true;
19973   // Members are *two* levels below the record;
19974   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
19975   verifyFormat("class C {\n"
19976                "    int i;\n"
19977                "};\n",
19978                Style);
19979   verifyFormat("union C {\n"
19980                "    int i;\n"
19981                "    unsigned u;\n"
19982                "};\n",
19983                Style);
19984   // Access modifiers should be indented one level below the record.
19985   verifyFormat("class C {\n"
19986                "  public:\n"
19987                "    int i;\n"
19988                "};\n",
19989                Style);
19990   verifyFormat("struct S {\n"
19991                "  private:\n"
19992                "    class C {\n"
19993                "        int j;\n"
19994                "\n"
19995                "      public:\n"
19996                "        C();\n"
19997                "    };\n"
19998                "\n"
19999                "  public:\n"
20000                "    int i;\n"
20001                "};\n",
20002                Style);
20003   // Enumerations are not records and should be unaffected.
20004   Style.AllowShortEnumsOnASingleLine = false;
20005   verifyFormat("enum class E\n"
20006                "{\n"
20007                "  A,\n"
20008                "  B\n"
20009                "};\n",
20010                Style);
20011   // Test with a different indentation width;
20012   // also proves that the result is Style.AccessModifierOffset agnostic.
20013   Style.IndentWidth = 3;
20014   verifyFormat("class C {\n"
20015                "   public:\n"
20016                "      int i;\n"
20017                "};\n",
20018                Style);
20019 }
20020 
20021 TEST_F(FormatTest, LimitlessStringsAndComments) {
20022   auto Style = getLLVMStyleWithColumns(0);
20023   constexpr StringRef Code =
20024       "/**\n"
20025       " * This is a multiline comment with quite some long lines, at least for "
20026       "the LLVM Style.\n"
20027       " * We will redo this with strings and line comments. Just to  check if "
20028       "everything is working.\n"
20029       " */\n"
20030       "bool foo() {\n"
20031       "  /* Single line multi line comment. */\n"
20032       "  const std::string String = \"This is a multiline string with quite "
20033       "some long lines, at least for the LLVM Style.\"\n"
20034       "                             \"We already did it with multi line "
20035       "comments, and we will do it with line comments. Just to check if "
20036       "everything is working.\";\n"
20037       "  // This is a line comment (block) with quite some long lines, at "
20038       "least for the LLVM Style.\n"
20039       "  // We already did this with multi line comments and strings. Just to "
20040       "check if everything is working.\n"
20041       "  const std::string SmallString = \"Hello World\";\n"
20042       "  // Small line comment\n"
20043       "  return String.size() > SmallString.size();\n"
20044       "}";
20045   EXPECT_EQ(Code, format(Code, Style));
20046 }
20047 } // namespace
20048 } // namespace format
20049 } // namespace clang
20050