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   EXPECT_EQ(
6464       "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
6465       "    /*\n"
6466       "     */\n"
6467       "    function() {\n"
6468       "      try {\n"
6469       "        return JJJJJJJJJJJJJJ(\n"
6470       "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
6471       "      }\n"
6472       "    } :\n"
6473       "    function() {};",
6474       format(
6475           "MMMMMMMMMMMMMMMMMMMMMMMMMMM = A ?\n"
6476           "     /*\n"
6477           "      */\n"
6478           "     function() {\n"
6479           "      try {\n"
6480           "        return JJJJJJJJJJJJJJ(\n"
6481           "            pppppppppppppppppppppppppppppppppppppppppppppppppp);\n"
6482           "      }\n"
6483           "    } :\n"
6484           "    function() {};",
6485           getGoogleStyle(FormatStyle::LK_JavaScript)));
6486 }
6487 
6488 TEST_F(FormatTest, BreaksConditionalExpressionsAfterOperator) {
6489   FormatStyle Style = getLLVMStyle();
6490   Style.BreakBeforeTernaryOperators = false;
6491   Style.ColumnLimit = 70;
6492   verifyFormat(
6493       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6494       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6495       "                               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6496       Style);
6497   verifyFormat(
6498       "aaaa(aaaaaaaaaa, aaaaaaaa,\n"
6499       "     aaaaaaaaaaaaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6500       "                                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6501       Style);
6502   verifyFormat(
6503       "aaaa(aaaaaaaaaaaaaaaaaaaa, aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6504       "                                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6505       Style);
6506   verifyFormat("aaaa(aaaaaaaa, aaaaaaaaaa,\n"
6507                "     aaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6508                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6509                Style);
6510   verifyFormat(
6511       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa ? aaaa(aaaaaa) :\n"
6512       "                                                      aaaaaaaaaaaaa);",
6513       Style);
6514   verifyFormat(
6515       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6516       "                   aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6517       "                                      aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6518       "                   aaaaaaaaaaaaa);",
6519       Style);
6520   verifyFormat(
6521       "aaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6522       "                   aaaaaaaaaaaaaaaa ?: aaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6523       "                   aaaaaaaaaaaaa);",
6524       Style);
6525   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6526                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6527                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6528                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6529                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6530                Style);
6531   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6532                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6533                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6534                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) :\n"
6535                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6536                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6537                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6538                Style);
6539   verifyFormat("aaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
6540                "       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?:\n"
6541                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
6542                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa),\n"
6543                "       aaaaaaaaaaaaaaaaaaaaaaaaaaa);",
6544                Style);
6545   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6546                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6547                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6548                Style);
6549   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaa =\n"
6550                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6551                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa :\n"
6552                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
6553                Style);
6554   verifyFormat(
6555       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa == aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6556       "    aaaaaaaaaaaaaaa :\n"
6557       "    aaaaaaaaaaaaaaa;",
6558       Style);
6559   verifyFormat("f(aaaaaaaaaaaaaaaa == // force break\n"
6560                "          aaaaaaaaa ?\n"
6561                "      b :\n"
6562                "      c);",
6563                Style);
6564   verifyFormat("unsigned Indent =\n"
6565                "    format(TheLine.First,\n"
6566                "           IndentForLevel[TheLine.Level] >= 0 ?\n"
6567                "               IndentForLevel[TheLine.Level] :\n"
6568                "               TheLine * 2,\n"
6569                "           TheLine.InPPDirective, PreviousEndOfLineColumn);",
6570                Style);
6571   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6572                "                  aaaaaaaaaaaaaaa :\n"
6573                "                  bbbbbbbbbbbbbbb ? //\n"
6574                "                      ccccccccccccccc :\n"
6575                "                      ddddddddddddddd;",
6576                Style);
6577   verifyFormat("bool aaaaaa = aaaaaaaaaaaaa ? //\n"
6578                "                  aaaaaaaaaaaaaaa :\n"
6579                "                  (bbbbbbbbbbbbbbb ? //\n"
6580                "                       ccccccccccccccc :\n"
6581                "                       ddddddddddddddd);",
6582                Style);
6583   verifyFormat("int i = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6584                "            /*bbbbbbbbbbbbbbb=*/bbbbbbbbbbbbbbbbbbbbbbbbb :\n"
6585                "            ccccccccccccccccccccccccccc;",
6586                Style);
6587   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ?\n"
6588                "           aaaaa :\n"
6589                "           bbbbbbbbbbbbbbb + cccccccccccccccc;",
6590                Style);
6591 
6592   // Chained conditionals
6593   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6594                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6595                "                          3333333333333333;",
6596                Style);
6597   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6598                "       bbbbbbbbbb       ? 2222222222222222 :\n"
6599                "                          3333333333333333;",
6600                Style);
6601   verifyFormat("return aaaaaaaaaa       ? 1111111111111111 :\n"
6602                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6603                "                          3333333333333333;",
6604                Style);
6605   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6606                "       bbbbbbbbbbbbbbbb ? 222222 :\n"
6607                "                          333333;",
6608                Style);
6609   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6610                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6611                "       cccccccccccccccc ? 3333333333333333 :\n"
6612                "                          4444444444444444;",
6613                Style);
6614   verifyFormat("return aaaaaaaaaaaaaaaa ? (aaa ? bbb : ccc) :\n"
6615                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6616                "                          3333333333333333;",
6617                Style);
6618   verifyFormat("return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6619                "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6620                "                          (aaa ? bbb : ccc);",
6621                Style);
6622   verifyFormat(
6623       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6624       "                                               cccccccccccccccccc) :\n"
6625       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6626       "                          3333333333333333;",
6627       Style);
6628   verifyFormat(
6629       "return aaaaaaaaa        ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6630       "                                               cccccccccccccccccc) :\n"
6631       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6632       "                          3333333333333333;",
6633       Style);
6634   verifyFormat(
6635       "return aaaaaaaaa        ? a = (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6636       "                                               dddddddddddddddddd) :\n"
6637       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6638       "                          3333333333333333;",
6639       Style);
6640   verifyFormat(
6641       "return aaaaaaaaa        ? a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6642       "                                               dddddddddddddddddd) :\n"
6643       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6644       "                          3333333333333333;",
6645       Style);
6646   verifyFormat(
6647       "return aaaaaaaaa        ? 1111111111111111 :\n"
6648       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6649       "                          a + (aaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6650       "                                               dddddddddddddddddd)\n",
6651       Style);
6652   verifyFormat(
6653       "return aaaaaaaaaaaaaaaa ? 1111111111111111 :\n"
6654       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6655       "                          (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6656       "                                               cccccccccccccccccc);",
6657       Style);
6658   verifyFormat(
6659       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6660       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
6661       "                                               eeeeeeeeeeeeeeeeee) :\n"
6662       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6663       "                          3333333333333333;",
6664       Style);
6665   verifyFormat(
6666       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6667       "                           ccccccccccccc     ? dddddddddddddddddd :\n"
6668       "                                               eeeeeeeeeeeeeeeeee) :\n"
6669       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6670       "                          3333333333333333;",
6671       Style);
6672   verifyFormat(
6673       "return aaaaaaaaaaaaaaaa ? (aaaaaaaaaaaaa     ? bbbbbbbbbbbbbbbbbb :\n"
6674       "                           ccccccccccccccccc ? dddddddddddddddddd :\n"
6675       "                                               eeeeeeeeeeeeeeeeee) :\n"
6676       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6677       "                          3333333333333333;",
6678       Style);
6679   verifyFormat(
6680       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6681       "                                               cccccccccccccccccc :\n"
6682       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6683       "                          3333333333333333;",
6684       Style);
6685   verifyFormat(
6686       "return aaaaaaaaaaaaaaaa ? aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6687       "                          cccccccccccccccccc ? dddddddddddddddddd :\n"
6688       "                                               eeeeeeeeeeeeeeeeee :\n"
6689       "       bbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6690       "                          3333333333333333;",
6691       Style);
6692   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
6693                "           (aaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6694                "            cccccccccccccccccc ? dddddddddddddddddd :\n"
6695                "                                 eeeeeeeeeeeeeeeeee) :\n"
6696                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6697                "                               3333333333333333;",
6698                Style);
6699   verifyFormat("return aaaaaaaaaaaaaaaaaaaaa ?\n"
6700                "           aaaaaaaaaaaaaaaaaaaa ? bbbbbbbbbbbbbbbbbb :\n"
6701                "           cccccccccccccccccccc ? dddddddddddddddddd :\n"
6702                "                                  eeeeeeeeeeeeeeeeee :\n"
6703                "       bbbbbbbbbbbbbbbbbbbbb ? 2222222222222222 :\n"
6704                "                               3333333333333333;",
6705                Style);
6706 }
6707 
6708 TEST_F(FormatTest, DeclarationsOfMultipleVariables) {
6709   verifyFormat("bool aaaaaaaaaaaaaaaaa = aaaaaa->aaaaaaaaaaaaaaaaa(),\n"
6710                "     aaaaaaaaaaa = aaaaaa->aaaaaaaaaaa();");
6711   verifyFormat("bool a = true, b = false;");
6712 
6713   verifyFormat("bool aaaaaaaaaaaaaaaaaaaaaaaaa =\n"
6714                "         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaa),\n"
6715                "     bbbbbbbbbbbbbbbbbbbbbbbbb =\n"
6716                "         bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(bbbbbbbbbbbbbbbb);");
6717   verifyFormat(
6718       "bool aaaaaaaaaaaaaaaaaaaaa =\n"
6719       "         bbbbbbbbbbbbbbbbbbbbbbbbbbbb && cccccccccccccccccccccccccccc,\n"
6720       "     d = e && f;");
6721   verifyFormat("aaaaaaaaa a = aaaaaaaaaaaaaaaaaaaa, b = bbbbbbbbbbbbbbbbbbbb,\n"
6722                "          c = cccccccccccccccccccc, d = dddddddddddddddddddd;");
6723   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
6724                "          *c = ccccccccccccccccccc, *d = ddddddddddddddddddd;");
6725   verifyFormat("aaaaaaaaa ***a = aaaaaaaaaaaaaaaaaaa, ***b = bbbbbbbbbbbbbbb,\n"
6726                "          ***c = ccccccccccccccccccc, ***d = ddddddddddddddd;");
6727 
6728   FormatStyle Style = getGoogleStyle();
6729   Style.PointerAlignment = FormatStyle::PAS_Left;
6730   Style.DerivePointerAlignment = false;
6731   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
6732                "    *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaa,\n"
6733                "    *b = bbbbbbbbbbbbbbbbbbb;",
6734                Style);
6735   verifyFormat("aaaaaaaaa *a = aaaaaaaaaaaaaaaaaaa, *b = bbbbbbbbbbbbbbbbbbb,\n"
6736                "          *b = bbbbbbbbbbbbbbbbbbb, *d = ddddddddddddddddddd;",
6737                Style);
6738   verifyFormat("vector<int*> a, b;", Style);
6739   verifyFormat("for (int *p, *q; p != q; p = p->next) {\n}", Style);
6740 }
6741 
6742 TEST_F(FormatTest, ConditionalExpressionsInBrackets) {
6743   verifyFormat("arr[foo ? bar : baz];");
6744   verifyFormat("f()[foo ? bar : baz];");
6745   verifyFormat("(a + b)[foo ? bar : baz];");
6746   verifyFormat("arr[foo ? (4 > 5 ? 4 : 5) : 5 < 5 ? 5 : 7];");
6747 }
6748 
6749 TEST_F(FormatTest, AlignsStringLiterals) {
6750   verifyFormat("loooooooooooooooooooooooooongFunction(\"short literal \"\n"
6751                "                                      \"short literal\");");
6752   verifyFormat(
6753       "looooooooooooooooooooooooongFunction(\n"
6754       "    \"short literal\"\n"
6755       "    \"looooooooooooooooooooooooooooooooooooooooooooooooong literal\");");
6756   verifyFormat("someFunction(\"Always break between multi-line\"\n"
6757                "             \" string literals\",\n"
6758                "             and, other, parameters);");
6759   EXPECT_EQ("fun + \"1243\" /* comment */\n"
6760             "      \"5678\";",
6761             format("fun + \"1243\" /* comment */\n"
6762                    "    \"5678\";",
6763                    getLLVMStyleWithColumns(28)));
6764   EXPECT_EQ(
6765       "aaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
6766       "         \"aaaaaaaaaaaaaaaaaaaaa\"\n"
6767       "         \"aaaaaaaaaaaaaaaa\";",
6768       format("aaaaaa ="
6769              "\"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaa "
6770              "aaaaaaaaaaaaaaaaaaaaa\" "
6771              "\"aaaaaaaaaaaaaaaa\";"));
6772   verifyFormat("a = a + \"a\"\n"
6773                "        \"a\"\n"
6774                "        \"a\";");
6775   verifyFormat("f(\"a\", \"b\"\n"
6776                "       \"c\");");
6777 
6778   verifyFormat(
6779       "#define LL_FORMAT \"ll\"\n"
6780       "printf(\"aaaaa: %d, bbbbbb: %\" LL_FORMAT \"d, cccccccc: %\" LL_FORMAT\n"
6781       "       \"d, ddddddddd: %\" LL_FORMAT \"d\");");
6782 
6783   verifyFormat("#define A(X)          \\\n"
6784                "  \"aaaaa\" #X \"bbbbbb\" \\\n"
6785                "  \"ccccc\"",
6786                getLLVMStyleWithColumns(23));
6787   verifyFormat("#define A \"def\"\n"
6788                "f(\"abc\" A \"ghi\"\n"
6789                "  \"jkl\");");
6790 
6791   verifyFormat("f(L\"a\"\n"
6792                "  L\"b\");");
6793   verifyFormat("#define A(X)            \\\n"
6794                "  L\"aaaaa\" #X L\"bbbbbb\" \\\n"
6795                "  L\"ccccc\"",
6796                getLLVMStyleWithColumns(25));
6797 
6798   verifyFormat("f(@\"a\"\n"
6799                "  @\"b\");");
6800   verifyFormat("NSString s = @\"a\"\n"
6801                "             @\"b\"\n"
6802                "             @\"c\";");
6803   verifyFormat("NSString s = @\"a\"\n"
6804                "              \"b\"\n"
6805                "              \"c\";");
6806 }
6807 
6808 TEST_F(FormatTest, ReturnTypeBreakingStyle) {
6809   FormatStyle Style = getLLVMStyle();
6810   // No declarations or definitions should be moved to own line.
6811   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_None;
6812   verifyFormat("class A {\n"
6813                "  int f() { return 1; }\n"
6814                "  int g();\n"
6815                "};\n"
6816                "int f() { return 1; }\n"
6817                "int g();\n",
6818                Style);
6819 
6820   // All declarations and definitions should have the return type moved to its
6821   // own line.
6822   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
6823   Style.TypenameMacros = {"LIST"};
6824   verifyFormat("SomeType\n"
6825                "funcdecl(LIST(uint64_t));",
6826                Style);
6827   verifyFormat("class E {\n"
6828                "  int\n"
6829                "  f() {\n"
6830                "    return 1;\n"
6831                "  }\n"
6832                "  int\n"
6833                "  g();\n"
6834                "};\n"
6835                "int\n"
6836                "f() {\n"
6837                "  return 1;\n"
6838                "}\n"
6839                "int\n"
6840                "g();\n",
6841                Style);
6842 
6843   // Top-level definitions, and no kinds of declarations should have the
6844   // return type moved to its own line.
6845   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevelDefinitions;
6846   verifyFormat("class B {\n"
6847                "  int f() { return 1; }\n"
6848                "  int g();\n"
6849                "};\n"
6850                "int\n"
6851                "f() {\n"
6852                "  return 1;\n"
6853                "}\n"
6854                "int g();\n",
6855                Style);
6856 
6857   // Top-level definitions and declarations should have the return type moved
6858   // to its own line.
6859   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_TopLevel;
6860   verifyFormat("class C {\n"
6861                "  int f() { return 1; }\n"
6862                "  int g();\n"
6863                "};\n"
6864                "int\n"
6865                "f() {\n"
6866                "  return 1;\n"
6867                "}\n"
6868                "int\n"
6869                "g();\n",
6870                Style);
6871 
6872   // All definitions should have the return type moved to its own line, but no
6873   // kinds of declarations.
6874   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_AllDefinitions;
6875   verifyFormat("class D {\n"
6876                "  int\n"
6877                "  f() {\n"
6878                "    return 1;\n"
6879                "  }\n"
6880                "  int g();\n"
6881                "};\n"
6882                "int\n"
6883                "f() {\n"
6884                "  return 1;\n"
6885                "}\n"
6886                "int g();\n",
6887                Style);
6888   verifyFormat("const char *\n"
6889                "f(void) {\n" // Break here.
6890                "  return \"\";\n"
6891                "}\n"
6892                "const char *bar(void);\n", // No break here.
6893                Style);
6894   verifyFormat("template <class T>\n"
6895                "T *\n"
6896                "f(T &c) {\n" // Break here.
6897                "  return NULL;\n"
6898                "}\n"
6899                "template <class T> T *f(T &c);\n", // No break here.
6900                Style);
6901   verifyFormat("class C {\n"
6902                "  int\n"
6903                "  operator+() {\n"
6904                "    return 1;\n"
6905                "  }\n"
6906                "  int\n"
6907                "  operator()() {\n"
6908                "    return 1;\n"
6909                "  }\n"
6910                "};\n",
6911                Style);
6912   verifyFormat("void\n"
6913                "A::operator()() {}\n"
6914                "void\n"
6915                "A::operator>>() {}\n"
6916                "void\n"
6917                "A::operator+() {}\n"
6918                "void\n"
6919                "A::operator*() {}\n"
6920                "void\n"
6921                "A::operator->() {}\n"
6922                "void\n"
6923                "A::operator void *() {}\n"
6924                "void\n"
6925                "A::operator void &() {}\n"
6926                "void\n"
6927                "A::operator void &&() {}\n"
6928                "void\n"
6929                "A::operator char *() {}\n"
6930                "void\n"
6931                "A::operator[]() {}\n"
6932                "void\n"
6933                "A::operator!() {}\n"
6934                "void\n"
6935                "A::operator**() {}\n"
6936                "void\n"
6937                "A::operator<Foo> *() {}\n"
6938                "void\n"
6939                "A::operator<Foo> **() {}\n"
6940                "void\n"
6941                "A::operator<Foo> &() {}\n"
6942                "void\n"
6943                "A::operator void **() {}\n",
6944                Style);
6945   verifyFormat("constexpr auto\n"
6946                "operator()() const -> reference {}\n"
6947                "constexpr auto\n"
6948                "operator>>() const -> reference {}\n"
6949                "constexpr auto\n"
6950                "operator+() const -> reference {}\n"
6951                "constexpr auto\n"
6952                "operator*() const -> reference {}\n"
6953                "constexpr auto\n"
6954                "operator->() const -> reference {}\n"
6955                "constexpr auto\n"
6956                "operator++() const -> reference {}\n"
6957                "constexpr auto\n"
6958                "operator void *() const -> reference {}\n"
6959                "constexpr auto\n"
6960                "operator void **() const -> reference {}\n"
6961                "constexpr auto\n"
6962                "operator void *() const -> reference {}\n"
6963                "constexpr auto\n"
6964                "operator void &() const -> reference {}\n"
6965                "constexpr auto\n"
6966                "operator void &&() const -> reference {}\n"
6967                "constexpr auto\n"
6968                "operator char *() const -> reference {}\n"
6969                "constexpr auto\n"
6970                "operator!() const -> reference {}\n"
6971                "constexpr auto\n"
6972                "operator[]() const -> reference {}\n",
6973                Style);
6974   verifyFormat("void *operator new(std::size_t s);", // No break here.
6975                Style);
6976   verifyFormat("void *\n"
6977                "operator new(std::size_t s) {}",
6978                Style);
6979   verifyFormat("void *\n"
6980                "operator delete[](void *ptr) {}",
6981                Style);
6982   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
6983   verifyFormat("const char *\n"
6984                "f(void)\n" // Break here.
6985                "{\n"
6986                "  return \"\";\n"
6987                "}\n"
6988                "const char *bar(void);\n", // No break here.
6989                Style);
6990   verifyFormat("template <class T>\n"
6991                "T *\n"     // Problem here: no line break
6992                "f(T &c)\n" // Break here.
6993                "{\n"
6994                "  return NULL;\n"
6995                "}\n"
6996                "template <class T> T *f(T &c);\n", // No break here.
6997                Style);
6998   verifyFormat("int\n"
6999                "foo(A<bool> a)\n"
7000                "{\n"
7001                "  return a;\n"
7002                "}\n",
7003                Style);
7004   verifyFormat("int\n"
7005                "foo(A<8> a)\n"
7006                "{\n"
7007                "  return a;\n"
7008                "}\n",
7009                Style);
7010   verifyFormat("int\n"
7011                "foo(A<B<bool>, 8> a)\n"
7012                "{\n"
7013                "  return a;\n"
7014                "}\n",
7015                Style);
7016   verifyFormat("int\n"
7017                "foo(A<B<8>, bool> a)\n"
7018                "{\n"
7019                "  return a;\n"
7020                "}\n",
7021                Style);
7022   verifyFormat("int\n"
7023                "foo(A<B<bool>, bool> a)\n"
7024                "{\n"
7025                "  return a;\n"
7026                "}\n",
7027                Style);
7028   verifyFormat("int\n"
7029                "foo(A<B<8>, 8> a)\n"
7030                "{\n"
7031                "  return a;\n"
7032                "}\n",
7033                Style);
7034 
7035   Style = getGNUStyle();
7036 
7037   // Test for comments at the end of function declarations.
7038   verifyFormat("void\n"
7039                "foo (int a, /*abc*/ int b) // def\n"
7040                "{\n"
7041                "}\n",
7042                Style);
7043 
7044   verifyFormat("void\n"
7045                "foo (int a, /* abc */ int b) /* def */\n"
7046                "{\n"
7047                "}\n",
7048                Style);
7049 
7050   // Definitions that should not break after return type
7051   verifyFormat("void foo (int a, int b); // def\n", Style);
7052   verifyFormat("void foo (int a, int b); /* def */\n", Style);
7053   verifyFormat("void foo (int a, int b);\n", Style);
7054 }
7055 
7056 TEST_F(FormatTest, AlwaysBreakBeforeMultilineStrings) {
7057   FormatStyle NoBreak = getLLVMStyle();
7058   NoBreak.AlwaysBreakBeforeMultilineStrings = false;
7059   FormatStyle Break = getLLVMStyle();
7060   Break.AlwaysBreakBeforeMultilineStrings = true;
7061   verifyFormat("aaaa = \"bbbb\"\n"
7062                "       \"cccc\";",
7063                NoBreak);
7064   verifyFormat("aaaa =\n"
7065                "    \"bbbb\"\n"
7066                "    \"cccc\";",
7067                Break);
7068   verifyFormat("aaaa(\"bbbb\"\n"
7069                "     \"cccc\");",
7070                NoBreak);
7071   verifyFormat("aaaa(\n"
7072                "    \"bbbb\"\n"
7073                "    \"cccc\");",
7074                Break);
7075   verifyFormat("aaaa(qqq, \"bbbb\"\n"
7076                "          \"cccc\");",
7077                NoBreak);
7078   verifyFormat("aaaa(qqq,\n"
7079                "     \"bbbb\"\n"
7080                "     \"cccc\");",
7081                Break);
7082   verifyFormat("aaaa(qqq,\n"
7083                "     L\"bbbb\"\n"
7084                "     L\"cccc\");",
7085                Break);
7086   verifyFormat("aaaaa(aaaaaa, aaaaaaa(\"aaaa\"\n"
7087                "                      \"bbbb\"));",
7088                Break);
7089   verifyFormat("string s = someFunction(\n"
7090                "    \"abc\"\n"
7091                "    \"abc\");",
7092                Break);
7093 
7094   // As we break before unary operators, breaking right after them is bad.
7095   verifyFormat("string foo = abc ? \"x\"\n"
7096                "                   \"blah blah blah blah blah blah\"\n"
7097                "                 : \"y\";",
7098                Break);
7099 
7100   // Don't break if there is no column gain.
7101   verifyFormat("f(\"aaaa\"\n"
7102                "  \"bbbb\");",
7103                Break);
7104 
7105   // Treat literals with escaped newlines like multi-line string literals.
7106   EXPECT_EQ("x = \"a\\\n"
7107             "b\\\n"
7108             "c\";",
7109             format("x = \"a\\\n"
7110                    "b\\\n"
7111                    "c\";",
7112                    NoBreak));
7113   EXPECT_EQ("xxxx =\n"
7114             "    \"a\\\n"
7115             "b\\\n"
7116             "c\";",
7117             format("xxxx = \"a\\\n"
7118                    "b\\\n"
7119                    "c\";",
7120                    Break));
7121 
7122   EXPECT_EQ("NSString *const kString =\n"
7123             "    @\"aaaa\"\n"
7124             "    @\"bbbb\";",
7125             format("NSString *const kString = @\"aaaa\"\n"
7126                    "@\"bbbb\";",
7127                    Break));
7128 
7129   Break.ColumnLimit = 0;
7130   verifyFormat("const char *hello = \"hello llvm\";", Break);
7131 }
7132 
7133 TEST_F(FormatTest, AlignsPipes) {
7134   verifyFormat(
7135       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7136       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7137       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7138   verifyFormat(
7139       "aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaa\n"
7140       "                     << aaaaaaaaaaaaaaaaaaaa;");
7141   verifyFormat(
7142       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7143       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7144   verifyFormat(
7145       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()\n"
7146       "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7147   verifyFormat(
7148       "llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n"
7149       "                \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\"\n"
7150       "             << \"ccccccccccccccccccccccccccccccccccccccccccccccccc\";");
7151   verifyFormat(
7152       "aaaaaaaa << (aaaaaaaaaaaaaaaaaaa << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7153       "                                 << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7154       "         << aaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7155   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7156                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7157                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7158                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7159   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaaaaaa: \"\n"
7160                "             << aaaaaaaaaaaaaaaaa(aaaaaaaa, aaaaaaaaaaa);");
7161   verifyFormat(
7162       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7163       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7164   verifyFormat(
7165       "auto Diag = diag() << aaaaaaaaaaaaaaaa(aaaaaaaaaaaa, aaaaaaaaaaaaa,\n"
7166       "                                       aaaaaaaaaaaaaaaaaaaaaaaaaa);");
7167 
7168   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \"\n"
7169                "             << aaaaaaaa.aaaaaaaaaaaa(aaa)->aaaaaaaaaaaaaa();");
7170   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7171                "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7172                "                    aaaaaaaaaaaaaaaaaaaaa)\n"
7173                "             << aaaaaaaaaaaaaaaaaaaaaaaaaa;");
7174   verifyFormat("LOG_IF(aaa == //\n"
7175                "       bbb)\n"
7176                "    << a << b;");
7177 
7178   // But sometimes, breaking before the first "<<" is desirable.
7179   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7180                "    << aaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaa);");
7181   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaaaaaaaaaaa, bbbbbbbbb)\n"
7182                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7183                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7184   verifyFormat("SemaRef.Diag(Loc, diag::note_for_range_begin_end)\n"
7185                "    << BEF << IsTemplate << Description << E->getType();");
7186   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7187                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7188                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7189   verifyFormat("Diag(aaaaaaaaaaaaaaaaaaaa, aaaaaaaa)\n"
7190                "    << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7191                "           aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7192                "    << aaa;");
7193 
7194   verifyFormat(
7195       "llvm::errs() << aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7196       "                    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7197 
7198   // Incomplete string literal.
7199   EXPECT_EQ("llvm::errs() << \"\n"
7200             "             << a;",
7201             format("llvm::errs() << \"\n<<a;"));
7202 
7203   verifyFormat("void f() {\n"
7204                "  CHECK_EQ(aaaa, (*bbbbbbbbb)->cccccc)\n"
7205                "      << \"qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\";\n"
7206                "}");
7207 
7208   // Handle 'endl'.
7209   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << endl\n"
7210                "             << bbbbbbbbbbbbbbbbbbbbbb << endl;");
7211   verifyFormat("llvm::errs() << endl << bbbbbbbbbbbbbbbbbbbbbb << endl;");
7212 
7213   // Handle '\n'.
7214   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \"\\n\"\n"
7215                "             << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
7216   verifyFormat("llvm::errs() << aaaaaaaaaaaaaaaaaaaaaa << \'\\n\'\n"
7217                "             << bbbbbbbbbbbbbbbbbbbbbb << \'\\n\';");
7218   verifyFormat("llvm::errs() << aaaa << \"aaaaaaaaaaaaaaaaaa\\n\"\n"
7219                "             << bbbb << \"bbbbbbbbbbbbbbbbbb\\n\";");
7220   verifyFormat("llvm::errs() << \"\\n\" << bbbbbbbbbbbbbbbbbbbbbb << \"\\n\";");
7221 }
7222 
7223 TEST_F(FormatTest, KeepStringLabelValuePairsOnALine) {
7224   verifyFormat("return out << \"somepacket = {\\n\"\n"
7225                "           << \" aaaaaa = \" << pkt.aaaaaa << \"\\n\"\n"
7226                "           << \" bbbb = \" << pkt.bbbb << \"\\n\"\n"
7227                "           << \" cccccc = \" << pkt.cccccc << \"\\n\"\n"
7228                "           << \" ddd = [\" << pkt.ddd << \"]\\n\"\n"
7229                "           << \"}\";");
7230 
7231   verifyFormat("llvm::outs() << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
7232                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa\n"
7233                "             << \"aaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaa;");
7234   verifyFormat(
7235       "llvm::outs() << \"aaaaaaaaaaaaaaaaa = \" << aaaaaaaaaaaaaaaaa\n"
7236       "             << \"bbbbbbbbbbbbbbbbb = \" << bbbbbbbbbbbbbbbbb\n"
7237       "             << \"ccccccccccccccccc = \" << ccccccccccccccccc\n"
7238       "             << \"ddddddddddddddddd = \" << ddddddddddddddddd\n"
7239       "             << \"eeeeeeeeeeeeeeeee = \" << eeeeeeeeeeeeeeeee;");
7240   verifyFormat("llvm::outs() << aaaaaaaaaaaaaaaaaaaaaaaa << \"=\"\n"
7241                "             << bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
7242   verifyFormat(
7243       "void f() {\n"
7244       "  llvm::outs() << \"aaaaaaaaaaaaaaaaaaaa: \"\n"
7245       "               << aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaa);\n"
7246       "}");
7247 
7248   // Breaking before the first "<<" is generally not desirable.
7249   verifyFormat(
7250       "llvm::errs()\n"
7251       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7252       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7253       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7254       "    << \"aaaaaaaaaaaaaaaaaaa: \" << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7255       getLLVMStyleWithColumns(70));
7256   verifyFormat("llvm::errs() << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7257                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7258                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7259                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7260                "             << \"aaaaaaaaaaaaaaaaaaa: \"\n"
7261                "             << aaaaaaaaaaaaaaaaaaaaaaaaaaaa;",
7262                getLLVMStyleWithColumns(70));
7263 
7264   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
7265                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa +\n"
7266                "           \"aaaaaaaaaaaaaaaa: \" + aaaaaaaaaaaaaaaa;");
7267   verifyFormat("string v = StrCat(\"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
7268                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa,\n"
7269                "                  \"aaaaaaaaaaaaaaaa: \", aaaaaaaaaaaaaaaa);");
7270   verifyFormat("string v = \"aaaaaaaaaaaaaaaa: \" +\n"
7271                "           (aaaa + aaaa);",
7272                getLLVMStyleWithColumns(40));
7273   verifyFormat("string v = StrCat(\"aaaaaaaaaaaa: \" +\n"
7274                "                  (aaaaaaa + aaaaa));",
7275                getLLVMStyleWithColumns(40));
7276   verifyFormat(
7277       "string v = StrCat(\"aaaaaaaaaaaaaaaaaaaaaaaaaaa: \",\n"
7278       "                  SomeFunction(aaaaaaaaaaaa, aaaaaaaa.aaaaaaa),\n"
7279       "                  bbbbbbbbbbbbbbbbbbbbbbb);");
7280 }
7281 
7282 TEST_F(FormatTest, UnderstandsEquals) {
7283   verifyFormat(
7284       "aaaaaaaaaaaaaaaaa =\n"
7285       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
7286   verifyFormat(
7287       "if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7288       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
7289   verifyFormat(
7290       "if (a) {\n"
7291       "  f();\n"
7292       "} else if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7293       "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n"
7294       "}");
7295 
7296   verifyFormat("if (int aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
7297                "        100000000 + 10000000) {\n}");
7298 }
7299 
7300 TEST_F(FormatTest, WrapsAtFunctionCallsIfNecessary) {
7301   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
7302                "    .looooooooooooooooooooooooooooooooooooooongFunction();");
7303 
7304   verifyFormat("LoooooooooooooooooooooooooooooooooooooongObject\n"
7305                "    ->looooooooooooooooooooooooooooooooooooooongFunction();");
7306 
7307   verifyFormat(
7308       "LooooooooooooooooooooooooooooooooongObject->shortFunction(Parameter1,\n"
7309       "                                                          Parameter2);");
7310 
7311   verifyFormat(
7312       "ShortObject->shortFunction(\n"
7313       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter1,\n"
7314       "    LooooooooooooooooooooooooooooooooooooooooooooooongParameter2);");
7315 
7316   verifyFormat("loooooooooooooongFunction(\n"
7317                "    LoooooooooooooongObject->looooooooooooooooongFunction());");
7318 
7319   verifyFormat(
7320       "function(LoooooooooooooooooooooooooooooooooooongObject\n"
7321       "             ->loooooooooooooooooooooooooooooooooooooooongFunction());");
7322 
7323   verifyFormat("EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
7324                "    .WillRepeatedly(Return(SomeValue));");
7325   verifyFormat("void f() {\n"
7326                "  EXPECT_CALL(SomeObject, SomeFunction(Parameter))\n"
7327                "      .Times(2)\n"
7328                "      .WillRepeatedly(Return(SomeValue));\n"
7329                "}");
7330   verifyFormat("SomeMap[std::pair(aaaaaaaaaaaa, bbbbbbbbbbbbbbb)].insert(\n"
7331                "    ccccccccccccccccccccccc);");
7332   verifyFormat("aaaaa(aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7333                "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7334                "          .aaaaa(aaaaa),\n"
7335                "      aaaaaaaaaaaaaaaaaaaaa);");
7336   verifyFormat("void f() {\n"
7337                "  aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7338                "      aaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa)->aaaaaaaaa());\n"
7339                "}");
7340   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7341                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7342                "    .aaaaaaaaaaaaaaa(aa(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7343                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7344                "                        aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7345   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7346                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7347                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7348                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()) {\n"
7349                "}");
7350 
7351   // Here, it is not necessary to wrap at "." or "->".
7352   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaa) ||\n"
7353                "    aaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) {\n}");
7354   verifyFormat(
7355       "aaaaaaaaaaa->aaaaaaaaa(\n"
7356       "    aaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7357       "    aaaaaaaaaaaaaaaaaa->aaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaa));\n");
7358 
7359   verifyFormat(
7360       "aaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7361       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa().aaaaaaaaaaaaaaaaa());");
7362   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() *\n"
7363                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
7364   verifyFormat("a->aaaaaa()->aaaaaaaaaaa(aaaaaaaa()->aaaaaa()->aaaaa() ||\n"
7365                "                         aaaaaaaaa()->aaaaaa()->aaaaa());");
7366 
7367   verifyFormat("aaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7368                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7369                "    .a();");
7370 
7371   FormatStyle NoBinPacking = getLLVMStyle();
7372   NoBinPacking.BinPackParameters = false;
7373   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7374                "    .aaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaa)\n"
7375                "    .aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa,\n"
7376                "                         aaaaaaaaaaaaaaaaaaa,\n"
7377                "                         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
7378                NoBinPacking);
7379 
7380   // If there is a subsequent call, change to hanging indentation.
7381   verifyFormat(
7382       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7383       "                         aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa))\n"
7384       "    .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7385   verifyFormat(
7386       "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7387       "    aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa));");
7388   verifyFormat("aaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7389                "                 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7390                "                 .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7391   verifyFormat("aaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7392                "               aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
7393                "               .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
7394 }
7395 
7396 TEST_F(FormatTest, WrapsTemplateDeclarations) {
7397   verifyFormat("template <typename T>\n"
7398                "virtual void loooooooooooongFunction(int Param1, int Param2);");
7399   verifyFormat("template <typename T>\n"
7400                "// T should be one of {A, B}.\n"
7401                "virtual void loooooooooooongFunction(int Param1, int Param2);");
7402   verifyFormat(
7403       "template <typename T>\n"
7404       "using comment_to_xml_conversion = comment_to_xml_conversion<T, int>;");
7405   verifyFormat("template <typename T>\n"
7406                "void f(int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram1,\n"
7407                "       int Paaaaaaaaaaaaaaaaaaaaaaaaaaaaaaram2);");
7408   verifyFormat(
7409       "template <typename T>\n"
7410       "void looooooooooooooooooooongFunction(int Paaaaaaaaaaaaaaaaaaaaram1,\n"
7411       "                                      int Paaaaaaaaaaaaaaaaaaaaram2);");
7412   verifyFormat(
7413       "template <typename T>\n"
7414       "aaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa,\n"
7415       "                    aaaaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaaaaa,\n"
7416       "                    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7417   verifyFormat("template <typename T>\n"
7418                "void aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7419                "    int aaaaaaaaaaaaaaaaaaaaaa);");
7420   verifyFormat(
7421       "template <typename T1, typename T2 = char, typename T3 = char,\n"
7422       "          typename T4 = char>\n"
7423       "void f();");
7424   verifyFormat("template <typename aaaaaaaaaaa, typename bbbbbbbbbbbbb,\n"
7425                "          template <typename> class cccccccccccccccccccccc,\n"
7426                "          typename ddddddddddddd>\n"
7427                "class C {};");
7428   verifyFormat(
7429       "aaaaaaaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>(\n"
7430       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
7431 
7432   verifyFormat("void f() {\n"
7433                "  a<aaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaa>(\n"
7434                "      a(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaa));\n"
7435                "}");
7436 
7437   verifyFormat("template <typename T> class C {};");
7438   verifyFormat("template <typename T> void f();");
7439   verifyFormat("template <typename T> void f() {}");
7440   verifyFormat(
7441       "aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
7442       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7443       "              aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> *aaaa =\n"
7444       "    new aaaaaaaaaaaaa<aaaaaaaaaa, aaaaaaaaaaa,\n"
7445       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7446       "                      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>(\n"
7447       "        bbbbbbbbbbbbbbbbbbbbbbbb);",
7448       getLLVMStyleWithColumns(72));
7449   EXPECT_EQ("static_cast<A< //\n"
7450             "    B> *>(\n"
7451             "\n"
7452             ");",
7453             format("static_cast<A<//\n"
7454                    "    B>*>(\n"
7455                    "\n"
7456                    "    );"));
7457   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7458                "    const typename aaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaa);");
7459 
7460   FormatStyle AlwaysBreak = getLLVMStyle();
7461   AlwaysBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7462   verifyFormat("template <typename T>\nclass C {};", AlwaysBreak);
7463   verifyFormat("template <typename T>\nvoid f();", AlwaysBreak);
7464   verifyFormat("template <typename T>\nvoid f() {}", AlwaysBreak);
7465   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7466                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
7467                "    ccccccccccccccccccccccccccccccccccccccccccccccc);");
7468   verifyFormat("template <template <typename> class Fooooooo,\n"
7469                "          template <typename> class Baaaaaaar>\n"
7470                "struct C {};",
7471                AlwaysBreak);
7472   verifyFormat("template <typename T> // T can be A, B or C.\n"
7473                "struct C {};",
7474                AlwaysBreak);
7475   verifyFormat("template <enum E> class A {\n"
7476                "public:\n"
7477                "  E *f();\n"
7478                "};");
7479 
7480   FormatStyle NeverBreak = getLLVMStyle();
7481   NeverBreak.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_No;
7482   verifyFormat("template <typename T> class C {};", NeverBreak);
7483   verifyFormat("template <typename T> void f();", NeverBreak);
7484   verifyFormat("template <typename T> void f() {}", NeverBreak);
7485   verifyFormat("template <typename T>\nvoid foo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
7486                "bbbbbbbbbbbbbbbbbbbb) {}",
7487                NeverBreak);
7488   verifyFormat("void aaaaaaaaaaaaaaaaaaa<aaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7489                "                         bbbbbbbbbbbbbbbbbbbbbbbbbbbb>(\n"
7490                "    ccccccccccccccccccccccccccccccccccccccccccccccc);",
7491                NeverBreak);
7492   verifyFormat("template <template <typename> class Fooooooo,\n"
7493                "          template <typename> class Baaaaaaar>\n"
7494                "struct C {};",
7495                NeverBreak);
7496   verifyFormat("template <typename T> // T can be A, B or C.\n"
7497                "struct C {};",
7498                NeverBreak);
7499   verifyFormat("template <enum E> class A {\n"
7500                "public:\n"
7501                "  E *f();\n"
7502                "};",
7503                NeverBreak);
7504   NeverBreak.PenaltyBreakTemplateDeclaration = 100;
7505   verifyFormat("template <typename T> void\nfoo(aaaaaaaaaaaaaaaaaaaaaaaaaa "
7506                "bbbbbbbbbbbbbbbbbbbb) {}",
7507                NeverBreak);
7508 }
7509 
7510 TEST_F(FormatTest, WrapsTemplateDeclarationsWithComments) {
7511   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
7512   Style.ColumnLimit = 60;
7513   EXPECT_EQ("// Baseline - no comments.\n"
7514             "template <\n"
7515             "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
7516             "void f() {}",
7517             format("// Baseline - no comments.\n"
7518                    "template <\n"
7519                    "    typename aaaaaaaaaaaaaaaaaaaaaa<bbbbbbbbbbbb>::value>\n"
7520                    "void f() {}",
7521                    Style));
7522 
7523   EXPECT_EQ("template <\n"
7524             "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
7525             "void f() {}",
7526             format("template <\n"
7527                    "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7528                    "void f() {}",
7529                    Style));
7530 
7531   EXPECT_EQ(
7532       "template <\n"
7533       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> /* line */\n"
7534       "void f() {}",
7535       format("template <typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  /* line */\n"
7536              "void f() {}",
7537              Style));
7538 
7539   EXPECT_EQ(
7540       "template <\n"
7541       "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value>  // trailing\n"
7542       "                                               // multiline\n"
7543       "void f() {}",
7544       format("template <\n"
7545              "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing\n"
7546              "                                              // multiline\n"
7547              "void f() {}",
7548              Style));
7549 
7550   EXPECT_EQ(
7551       "template <typename aaaaaaaaaa<\n"
7552       "    bbbbbbbbbbbb>::value>  // trailing loooong\n"
7553       "void f() {}",
7554       format(
7555           "template <\n"
7556           "    typename aaaaaaaaaa<bbbbbbbbbbbb>::value> // trailing loooong\n"
7557           "void f() {}",
7558           Style));
7559 }
7560 
7561 TEST_F(FormatTest, WrapsTemplateParameters) {
7562   FormatStyle Style = getLLVMStyle();
7563   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7564   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
7565   verifyFormat(
7566       "template <typename... a> struct q {};\n"
7567       "extern q<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
7568       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
7569       "    y;",
7570       Style);
7571   Style.AlignAfterOpenBracket = FormatStyle::BAS_DontAlign;
7572   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
7573   verifyFormat(
7574       "template <typename... a> struct r {};\n"
7575       "extern r<aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa,\n"
7576       "    aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa>\n"
7577       "    y;",
7578       Style);
7579   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7580   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
7581   verifyFormat("template <typename... a> struct s {};\n"
7582                "extern s<\n"
7583                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7584                "aaaaaaaaaaaaaaaaaaaaaa,\n"
7585                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7586                "aaaaaaaaaaaaaaaaaaaaaa>\n"
7587                "    y;",
7588                Style);
7589   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
7590   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
7591   verifyFormat("template <typename... a> struct t {};\n"
7592                "extern t<\n"
7593                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7594                "aaaaaaaaaaaaaaaaaaaaaa,\n"
7595                "    aaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaa, "
7596                "aaaaaaaaaaaaaaaaaaaaaa>\n"
7597                "    y;",
7598                Style);
7599 }
7600 
7601 TEST_F(FormatTest, WrapsAtNestedNameSpecifiers) {
7602   verifyFormat(
7603       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7604       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7605   verifyFormat(
7606       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7607       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7608       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa());");
7609 
7610   // FIXME: Should we have the extra indent after the second break?
7611   verifyFormat(
7612       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7613       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7614       "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7615 
7616   verifyFormat(
7617       "aaaaaaaaaaaaaaa(bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb::\n"
7618       "                    cccccccccccccccccccccccccccccccccccccccccccccc());");
7619 
7620   // Breaking at nested name specifiers is generally not desirable.
7621   verifyFormat(
7622       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7623       "    aaaaaaaaaaaaaaaaaaaaaaa);");
7624 
7625   verifyFormat("aaaaaaaaaaaaaaaaaa(aaaaaaaa,\n"
7626                "                   aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7627                "                       aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
7628                "                   aaaaaaaaaaaaaaaaaaaaa);",
7629                getLLVMStyleWithColumns(74));
7630 
7631   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa::\n"
7632                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7633                "        .aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa();");
7634 }
7635 
7636 TEST_F(FormatTest, UnderstandsTemplateParameters) {
7637   verifyFormat("A<int> a;");
7638   verifyFormat("A<A<A<int>>> a;");
7639   verifyFormat("A<A<A<int, 2>, 3>, 4> a;");
7640   verifyFormat("bool x = a < 1 || 2 > a;");
7641   verifyFormat("bool x = 5 < f<int>();");
7642   verifyFormat("bool x = f<int>() > 5;");
7643   verifyFormat("bool x = 5 < a<int>::x;");
7644   verifyFormat("bool x = a < 4 ? a > 2 : false;");
7645   verifyFormat("bool x = f() ? a < 2 : a > 2;");
7646 
7647   verifyGoogleFormat("A<A<int>> a;");
7648   verifyGoogleFormat("A<A<A<int>>> a;");
7649   verifyGoogleFormat("A<A<A<A<int>>>> a;");
7650   verifyGoogleFormat("A<A<int> > a;");
7651   verifyGoogleFormat("A<A<A<int> > > a;");
7652   verifyGoogleFormat("A<A<A<A<int> > > > a;");
7653   verifyGoogleFormat("A<::A<int>> a;");
7654   verifyGoogleFormat("A<::A> a;");
7655   verifyGoogleFormat("A< ::A> a;");
7656   verifyGoogleFormat("A< ::A<int> > a;");
7657   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A> >> a;", getGoogleStyle()));
7658   EXPECT_EQ("A<A<A<A>>> a;", format("A<A<A<A>> > a;", getGoogleStyle()));
7659   EXPECT_EQ("A<::A<int>> a;", format("A< ::A<int>> a;", getGoogleStyle()));
7660   EXPECT_EQ("A<::A<int>> a;", format("A<::A<int> > a;", getGoogleStyle()));
7661   EXPECT_EQ("auto x = [] { A<A<A<A>>> a; };",
7662             format("auto x=[]{A<A<A<A> >> a;};", getGoogleStyle()));
7663 
7664   verifyFormat("A<A<int>> a;", getChromiumStyle(FormatStyle::LK_Cpp));
7665 
7666   // template closer followed by a token that starts with > or =
7667   verifyFormat("bool b = a<1> > 1;");
7668   verifyFormat("bool b = a<1> >= 1;");
7669   verifyFormat("int i = a<1> >> 1;");
7670   FormatStyle Style = getLLVMStyle();
7671   Style.SpaceBeforeAssignmentOperators = false;
7672   verifyFormat("bool b= a<1> == 1;", Style);
7673   verifyFormat("a<int> = 1;", Style);
7674   verifyFormat("a<int> >>= 1;", Style);
7675 
7676   verifyFormat("test >> a >> b;");
7677   verifyFormat("test << a >> b;");
7678 
7679   verifyFormat("f<int>();");
7680   verifyFormat("template <typename T> void f() {}");
7681   verifyFormat("struct A<std::enable_if<sizeof(T2) < sizeof(int32)>::type>;");
7682   verifyFormat("struct A<std::enable_if<sizeof(T2) ? sizeof(int32) : "
7683                "sizeof(char)>::type>;");
7684   verifyFormat("template <class T> struct S<std::is_arithmetic<T>{}> {};");
7685   verifyFormat("f(a.operator()<A>());");
7686   verifyFormat("f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
7687                "      .template operator()<A>());",
7688                getLLVMStyleWithColumns(35));
7689 
7690   // Not template parameters.
7691   verifyFormat("return a < b && c > d;");
7692   verifyFormat("void f() {\n"
7693                "  while (a < b && c > d) {\n"
7694                "  }\n"
7695                "}");
7696   verifyFormat("template <typename... Types>\n"
7697                "typename enable_if<0 < sizeof...(Types)>::type Foo() {}");
7698 
7699   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
7700                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaa >> aaaaa);",
7701                getLLVMStyleWithColumns(60));
7702   verifyFormat("static_assert(is_convertible<A &&, B>::value, \"AAA\");");
7703   verifyFormat("Constructor(A... a) : a_(X<A>{std::forward<A>(a)}...) {}");
7704   verifyFormat("< < < < < < < < < < < < < < < < < < < < < < < < < < < < < <");
7705   verifyFormat("some_templated_type<decltype([](int i) { return i; })>");
7706 }
7707 
7708 TEST_F(FormatTest, UnderstandsShiftOperators) {
7709   verifyFormat("if (i < x >> 1)");
7710   verifyFormat("while (i < x >> 1)");
7711   verifyFormat("for (unsigned i = 0; i < i; ++i, v = v >> 1)");
7712   verifyFormat("for (unsigned i = 0; i < x >> 1; ++i, v = v >> 1)");
7713   verifyFormat(
7714       "for (std::vector<int>::iterator i = 0; i < x >> 1; ++i, v = v >> 1)");
7715   verifyFormat("Foo.call<Bar<Function>>()");
7716   verifyFormat("if (Foo.call<Bar<Function>>() == 0)");
7717   verifyFormat("for (std::vector<std::pair<int>>::iterator i = 0; i < x >> 1; "
7718                "++i, v = v >> 1)");
7719   verifyFormat("if (w<u<v<x>>, 1>::t)");
7720 }
7721 
7722 TEST_F(FormatTest, BitshiftOperatorWidth) {
7723   EXPECT_EQ("int a = 1 << 2; /* foo\n"
7724             "                   bar */",
7725             format("int    a=1<<2;  /* foo\n"
7726                    "                   bar */"));
7727 
7728   EXPECT_EQ("int b = 256 >> 1; /* foo\n"
7729             "                     bar */",
7730             format("int  b  =256>>1 ;  /* foo\n"
7731                    "                      bar */"));
7732 }
7733 
7734 TEST_F(FormatTest, UnderstandsBinaryOperators) {
7735   verifyFormat("COMPARE(a, ==, b);");
7736   verifyFormat("auto s = sizeof...(Ts) - 1;");
7737 }
7738 
7739 TEST_F(FormatTest, UnderstandsPointersToMembers) {
7740   verifyFormat("int A::*x;");
7741   verifyFormat("int (S::*func)(void *);");
7742   verifyFormat("void f() { int (S::*func)(void *); }");
7743   verifyFormat("typedef bool *(Class::*Member)() const;");
7744   verifyFormat("void f() {\n"
7745                "  (a->*f)();\n"
7746                "  a->*x;\n"
7747                "  (a.*f)();\n"
7748                "  ((*a).*f)();\n"
7749                "  a.*x;\n"
7750                "}");
7751   verifyFormat("void f() {\n"
7752                "  (a->*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
7753                "      aaaa, bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb);\n"
7754                "}");
7755   verifyFormat(
7756       "(aaaaaaaaaa->*bbbbbbb)(\n"
7757       "    aaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa));");
7758   FormatStyle Style = getLLVMStyle();
7759   Style.PointerAlignment = FormatStyle::PAS_Left;
7760   verifyFormat("typedef bool* (Class::*Member)() const;", Style);
7761 }
7762 
7763 TEST_F(FormatTest, UnderstandsUnaryOperators) {
7764   verifyFormat("int a = -2;");
7765   verifyFormat("f(-1, -2, -3);");
7766   verifyFormat("a[-1] = 5;");
7767   verifyFormat("int a = 5 + -2;");
7768   verifyFormat("if (i == -1) {\n}");
7769   verifyFormat("if (i != -1) {\n}");
7770   verifyFormat("if (i > -1) {\n}");
7771   verifyFormat("if (i < -1) {\n}");
7772   verifyFormat("++(a->f());");
7773   verifyFormat("--(a->f());");
7774   verifyFormat("(a->f())++;");
7775   verifyFormat("a[42]++;");
7776   verifyFormat("if (!(a->f())) {\n}");
7777   verifyFormat("if (!+i) {\n}");
7778   verifyFormat("~&a;");
7779 
7780   verifyFormat("a-- > b;");
7781   verifyFormat("b ? -a : c;");
7782   verifyFormat("n * sizeof char16;");
7783   verifyFormat("n * alignof char16;", getGoogleStyle());
7784   verifyFormat("sizeof(char);");
7785   verifyFormat("alignof(char);", getGoogleStyle());
7786 
7787   verifyFormat("return -1;");
7788   verifyFormat("throw -1;");
7789   verifyFormat("switch (a) {\n"
7790                "case -1:\n"
7791                "  break;\n"
7792                "}");
7793   verifyFormat("#define X -1");
7794   verifyFormat("#define X -kConstant");
7795 
7796   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {-5, +3};");
7797   verifyFormat("const NSPoint kBrowserFrameViewPatternOffset = {+5, -3};");
7798 
7799   verifyFormat("int a = /* confusing comment */ -1;");
7800   // FIXME: The space after 'i' is wrong, but hopefully, this is a rare case.
7801   verifyFormat("int a = i /* confusing comment */++;");
7802 
7803   verifyFormat("co_yield -1;");
7804   verifyFormat("co_return -1;");
7805 
7806   // Check that * is not treated as a binary operator when we set
7807   // PointerAlignment as PAS_Left after a keyword and not a declaration.
7808   FormatStyle PASLeftStyle = getLLVMStyle();
7809   PASLeftStyle.PointerAlignment = FormatStyle::PAS_Left;
7810   verifyFormat("co_return *a;", PASLeftStyle);
7811   verifyFormat("co_await *a;", PASLeftStyle);
7812   verifyFormat("co_yield *a", PASLeftStyle);
7813   verifyFormat("return *a;", PASLeftStyle);
7814 }
7815 
7816 TEST_F(FormatTest, DoesNotIndentRelativeToUnaryOperators) {
7817   verifyFormat("if (!aaaaaaaaaa( // break\n"
7818                "        aaaaa)) {\n"
7819                "}");
7820   verifyFormat("aaaaaaaaaa(!aaaaaaaaaa( // break\n"
7821                "    aaaaa));");
7822   verifyFormat("*aaa = aaaaaaa( // break\n"
7823                "    bbbbbb);");
7824 }
7825 
7826 TEST_F(FormatTest, UnderstandsOverloadedOperators) {
7827   verifyFormat("bool operator<();");
7828   verifyFormat("bool operator>();");
7829   verifyFormat("bool operator=();");
7830   verifyFormat("bool operator==();");
7831   verifyFormat("bool operator!=();");
7832   verifyFormat("int operator+();");
7833   verifyFormat("int operator++();");
7834   verifyFormat("int operator++(int) volatile noexcept;");
7835   verifyFormat("bool operator,();");
7836   verifyFormat("bool operator();");
7837   verifyFormat("bool operator()();");
7838   verifyFormat("bool operator[]();");
7839   verifyFormat("operator bool();");
7840   verifyFormat("operator int();");
7841   verifyFormat("operator void *();");
7842   verifyFormat("operator SomeType<int>();");
7843   verifyFormat("operator SomeType<int, int>();");
7844   verifyFormat("operator SomeType<SomeType<int>>();");
7845   verifyFormat("void *operator new(std::size_t size);");
7846   verifyFormat("void *operator new[](std::size_t size);");
7847   verifyFormat("void operator delete(void *ptr);");
7848   verifyFormat("void operator delete[](void *ptr);");
7849   verifyFormat("template <typename AAAAAAA, typename BBBBBBB>\n"
7850                "AAAAAAA operator/(const AAAAAAA &a, BBBBBBB &b);");
7851   verifyFormat("aaaaaaaaaaaaaaaaaaaaaa operator,(\n"
7852                "    aaaaaaaaaaaaaaaaaaaaa &aaaaaaaaaaaaaaaaaaaaaaaaaa) const;");
7853 
7854   verifyFormat(
7855       "ostream &operator<<(ostream &OutputStream,\n"
7856       "                    SomeReallyLongType WithSomeReallyLongValue);");
7857   verifyFormat("bool operator<(const aaaaaaaaaaaaaaaaaaaaa &left,\n"
7858                "               const aaaaaaaaaaaaaaaaaaaaa &right) {\n"
7859                "  return left.group < right.group;\n"
7860                "}");
7861   verifyFormat("SomeType &operator=(const SomeType &S);");
7862   verifyFormat("f.template operator()<int>();");
7863 
7864   verifyGoogleFormat("operator void*();");
7865   verifyGoogleFormat("operator SomeType<SomeType<int>>();");
7866   verifyGoogleFormat("operator ::A();");
7867 
7868   verifyFormat("using A::operator+;");
7869   verifyFormat("inline A operator^(const A &lhs, const A &rhs) {}\n"
7870                "int i;");
7871 }
7872 
7873 TEST_F(FormatTest, UnderstandsFunctionRefQualification) {
7874   verifyFormat("Deleted &operator=(const Deleted &) & = default;");
7875   verifyFormat("Deleted &operator=(const Deleted &) && = delete;");
7876   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;");
7877   verifyFormat("SomeType MemberFunction(const Deleted &) && = delete;");
7878   verifyFormat("Deleted &operator=(const Deleted &) &;");
7879   verifyFormat("Deleted &operator=(const Deleted &) &&;");
7880   verifyFormat("SomeType MemberFunction(const Deleted &) &;");
7881   verifyFormat("SomeType MemberFunction(const Deleted &) &&;");
7882   verifyFormat("SomeType MemberFunction(const Deleted &) && {}");
7883   verifyFormat("SomeType MemberFunction(const Deleted &) && final {}");
7884   verifyFormat("SomeType MemberFunction(const Deleted &) && override {}");
7885   verifyFormat("void Fn(T const &) const &;");
7886   verifyFormat("void Fn(T const volatile &&) const volatile &&;");
7887   verifyFormat("template <typename T>\n"
7888                "void F(T) && = delete;",
7889                getGoogleStyle());
7890 
7891   FormatStyle AlignLeft = getLLVMStyle();
7892   AlignLeft.PointerAlignment = FormatStyle::PAS_Left;
7893   verifyFormat("void A::b() && {}", AlignLeft);
7894   verifyFormat("Deleted& operator=(const Deleted&) & = default;", AlignLeft);
7895   verifyFormat("SomeType MemberFunction(const Deleted&) & = delete;",
7896                AlignLeft);
7897   verifyFormat("Deleted& operator=(const Deleted&) &;", AlignLeft);
7898   verifyFormat("SomeType MemberFunction(const Deleted&) &;", AlignLeft);
7899   verifyFormat("auto Function(T t) & -> void {}", AlignLeft);
7900   verifyFormat("auto Function(T... t) & -> void {}", AlignLeft);
7901   verifyFormat("auto Function(T) & -> void {}", AlignLeft);
7902   verifyFormat("auto Function(T) & -> void;", AlignLeft);
7903   verifyFormat("void Fn(T const&) const&;", AlignLeft);
7904   verifyFormat("void Fn(T const volatile&&) const volatile&&;", AlignLeft);
7905 
7906   FormatStyle Spaces = getLLVMStyle();
7907   Spaces.SpacesInCStyleCastParentheses = true;
7908   verifyFormat("Deleted &operator=(const Deleted &) & = default;", Spaces);
7909   verifyFormat("SomeType MemberFunction(const Deleted &) & = delete;", Spaces);
7910   verifyFormat("Deleted &operator=(const Deleted &) &;", Spaces);
7911   verifyFormat("SomeType MemberFunction(const Deleted &) &;", Spaces);
7912 
7913   Spaces.SpacesInCStyleCastParentheses = false;
7914   Spaces.SpacesInParentheses = true;
7915   verifyFormat("Deleted &operator=( const Deleted & ) & = default;", Spaces);
7916   verifyFormat("SomeType MemberFunction( const Deleted & ) & = delete;",
7917                Spaces);
7918   verifyFormat("Deleted &operator=( const Deleted & ) &;", Spaces);
7919   verifyFormat("SomeType MemberFunction( const Deleted & ) &;", Spaces);
7920 
7921   FormatStyle BreakTemplate = getLLVMStyle();
7922   BreakTemplate.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
7923 
7924   verifyFormat("struct f {\n"
7925                "  template <class T>\n"
7926                "  int &foo(const std::string &str) &noexcept {}\n"
7927                "};",
7928                BreakTemplate);
7929 
7930   verifyFormat("struct f {\n"
7931                "  template <class T>\n"
7932                "  int &foo(const std::string &str) &&noexcept {}\n"
7933                "};",
7934                BreakTemplate);
7935 
7936   verifyFormat("struct f {\n"
7937                "  template <class T>\n"
7938                "  int &foo(const std::string &str) const &noexcept {}\n"
7939                "};",
7940                BreakTemplate);
7941 
7942   verifyFormat("struct f {\n"
7943                "  template <class T>\n"
7944                "  int &foo(const std::string &str) const &noexcept {}\n"
7945                "};",
7946                BreakTemplate);
7947 
7948   verifyFormat("struct f {\n"
7949                "  template <class T>\n"
7950                "  auto foo(const std::string &str) &&noexcept -> int & {}\n"
7951                "};",
7952                BreakTemplate);
7953 
7954   FormatStyle AlignLeftBreakTemplate = getLLVMStyle();
7955   AlignLeftBreakTemplate.AlwaysBreakTemplateDeclarations =
7956       FormatStyle::BTDS_Yes;
7957   AlignLeftBreakTemplate.PointerAlignment = FormatStyle::PAS_Left;
7958 
7959   verifyFormat("struct f {\n"
7960                "  template <class T>\n"
7961                "  int& foo(const std::string& str) & noexcept {}\n"
7962                "};",
7963                AlignLeftBreakTemplate);
7964 
7965   verifyFormat("struct f {\n"
7966                "  template <class T>\n"
7967                "  int& foo(const std::string& str) && noexcept {}\n"
7968                "};",
7969                AlignLeftBreakTemplate);
7970 
7971   verifyFormat("struct f {\n"
7972                "  template <class T>\n"
7973                "  int& foo(const std::string& str) const& noexcept {}\n"
7974                "};",
7975                AlignLeftBreakTemplate);
7976 
7977   verifyFormat("struct f {\n"
7978                "  template <class T>\n"
7979                "  int& foo(const std::string& str) const&& noexcept {}\n"
7980                "};",
7981                AlignLeftBreakTemplate);
7982 
7983   verifyFormat("struct f {\n"
7984                "  template <class T>\n"
7985                "  auto foo(const std::string& str) && noexcept -> int& {}\n"
7986                "};",
7987                AlignLeftBreakTemplate);
7988 
7989   // The `&` in `Type&` should not be confused with a trailing `&` of
7990   // DEPRECATED(reason) member function.
7991   verifyFormat("struct f {\n"
7992                "  template <class T>\n"
7993                "  DEPRECATED(reason)\n"
7994                "  Type &foo(arguments) {}\n"
7995                "};",
7996                BreakTemplate);
7997 
7998   verifyFormat("struct f {\n"
7999                "  template <class T>\n"
8000                "  DEPRECATED(reason)\n"
8001                "  Type& foo(arguments) {}\n"
8002                "};",
8003                AlignLeftBreakTemplate);
8004 
8005   verifyFormat("void (*foopt)(int) = &func;");
8006 }
8007 
8008 TEST_F(FormatTest, UnderstandsNewAndDelete) {
8009   verifyFormat("void f() {\n"
8010                "  A *a = new A;\n"
8011                "  A *a = new (placement) A;\n"
8012                "  delete a;\n"
8013                "  delete (A *)a;\n"
8014                "}");
8015   verifyFormat("new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
8016                "    typename aaaaaaaaaaaaaaaaaaaaaaaa();");
8017   verifyFormat("auto aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8018                "    new (aaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaa))\n"
8019                "        typename aaaaaaaaaaaaaaaaaaaaaaaa();");
8020   verifyFormat("delete[] h->p;");
8021 }
8022 
8023 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
8024   verifyFormat("int *f(int *a) {}");
8025   verifyFormat("int main(int argc, char **argv) {}");
8026   verifyFormat("Test::Test(int b) : a(b * b) {}");
8027   verifyIndependentOfContext("f(a, *a);");
8028   verifyFormat("void g() { f(*a); }");
8029   verifyIndependentOfContext("int a = b * 10;");
8030   verifyIndependentOfContext("int a = 10 * b;");
8031   verifyIndependentOfContext("int a = b * c;");
8032   verifyIndependentOfContext("int a += b * c;");
8033   verifyIndependentOfContext("int a -= b * c;");
8034   verifyIndependentOfContext("int a *= b * c;");
8035   verifyIndependentOfContext("int a /= b * c;");
8036   verifyIndependentOfContext("int a = *b;");
8037   verifyIndependentOfContext("int a = *b * c;");
8038   verifyIndependentOfContext("int a = b * *c;");
8039   verifyIndependentOfContext("int a = b * (10);");
8040   verifyIndependentOfContext("S << b * (10);");
8041   verifyIndependentOfContext("return 10 * b;");
8042   verifyIndependentOfContext("return *b * *c;");
8043   verifyIndependentOfContext("return a & ~b;");
8044   verifyIndependentOfContext("f(b ? *c : *d);");
8045   verifyIndependentOfContext("int a = b ? *c : *d;");
8046   verifyIndependentOfContext("*b = a;");
8047   verifyIndependentOfContext("a * ~b;");
8048   verifyIndependentOfContext("a * !b;");
8049   verifyIndependentOfContext("a * +b;");
8050   verifyIndependentOfContext("a * -b;");
8051   verifyIndependentOfContext("a * ++b;");
8052   verifyIndependentOfContext("a * --b;");
8053   verifyIndependentOfContext("a[4] * b;");
8054   verifyIndependentOfContext("a[a * a] = 1;");
8055   verifyIndependentOfContext("f() * b;");
8056   verifyIndependentOfContext("a * [self dostuff];");
8057   verifyIndependentOfContext("int x = a * (a + b);");
8058   verifyIndependentOfContext("(a *)(a + b);");
8059   verifyIndependentOfContext("*(int *)(p & ~3UL) = 0;");
8060   verifyIndependentOfContext("int *pa = (int *)&a;");
8061   verifyIndependentOfContext("return sizeof(int **);");
8062   verifyIndependentOfContext("return sizeof(int ******);");
8063   verifyIndependentOfContext("return (int **&)a;");
8064   verifyIndependentOfContext("f((*PointerToArray)[10]);");
8065   verifyFormat("void f(Type (*parameter)[10]) {}");
8066   verifyFormat("void f(Type (&parameter)[10]) {}");
8067   verifyGoogleFormat("return sizeof(int**);");
8068   verifyIndependentOfContext("Type **A = static_cast<Type **>(P);");
8069   verifyGoogleFormat("Type** A = static_cast<Type**>(P);");
8070   verifyFormat("auto a = [](int **&, int ***) {};");
8071   verifyFormat("auto PointerBinding = [](const char *S) {};");
8072   verifyFormat("typedef typeof(int(int, int)) *MyFunc;");
8073   verifyFormat("[](const decltype(*a) &value) {}");
8074   verifyFormat("[](const typeof(*a) &value) {}");
8075   verifyFormat("[](const _Atomic(a *) &value) {}");
8076   verifyFormat("[](const __underlying_type(a) &value) {}");
8077   verifyFormat("decltype(a * b) F();");
8078   verifyFormat("typeof(a * b) F();");
8079   verifyFormat("#define MACRO() [](A *a) { return 1; }");
8080   verifyFormat("Constructor() : member([](A *a, B *b) {}) {}");
8081   verifyIndependentOfContext("typedef void (*f)(int *a);");
8082   verifyIndependentOfContext("int i{a * b};");
8083   verifyIndependentOfContext("aaa && aaa->f();");
8084   verifyIndependentOfContext("int x = ~*p;");
8085   verifyFormat("Constructor() : a(a), area(width * height) {}");
8086   verifyFormat("Constructor() : a(a), area(a, width * height) {}");
8087   verifyGoogleFormat("MACRO Constructor(const int& i) : a(a), b(b) {}");
8088   verifyFormat("void f() { f(a, c * d); }");
8089   verifyFormat("void f() { f(new a(), c * d); }");
8090   verifyFormat("void f(const MyOverride &override);");
8091   verifyFormat("void f(const MyFinal &final);");
8092   verifyIndependentOfContext("bool a = f() && override.f();");
8093   verifyIndependentOfContext("bool a = f() && final.f();");
8094 
8095   verifyIndependentOfContext("InvalidRegions[*R] = 0;");
8096 
8097   verifyIndependentOfContext("A<int *> a;");
8098   verifyIndependentOfContext("A<int **> a;");
8099   verifyIndependentOfContext("A<int *, int *> a;");
8100   verifyIndependentOfContext("A<int *[]> a;");
8101   verifyIndependentOfContext(
8102       "const char *const p = reinterpret_cast<const char *const>(q);");
8103   verifyIndependentOfContext("A<int **, int **> a;");
8104   verifyIndependentOfContext("void f(int *a = d * e, int *b = c * d);");
8105   verifyFormat("for (char **a = b; *a; ++a) {\n}");
8106   verifyFormat("for (; a && b;) {\n}");
8107   verifyFormat("bool foo = true && [] { return false; }();");
8108 
8109   verifyFormat(
8110       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8111       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaa, *aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8112 
8113   verifyGoogleFormat("int const* a = &b;");
8114   verifyGoogleFormat("**outparam = 1;");
8115   verifyGoogleFormat("*outparam = a * b;");
8116   verifyGoogleFormat("int main(int argc, char** argv) {}");
8117   verifyGoogleFormat("A<int*> a;");
8118   verifyGoogleFormat("A<int**> a;");
8119   verifyGoogleFormat("A<int*, int*> a;");
8120   verifyGoogleFormat("A<int**, int**> a;");
8121   verifyGoogleFormat("f(b ? *c : *d);");
8122   verifyGoogleFormat("int a = b ? *c : *d;");
8123   verifyGoogleFormat("Type* t = **x;");
8124   verifyGoogleFormat("Type* t = *++*x;");
8125   verifyGoogleFormat("*++*x;");
8126   verifyGoogleFormat("Type* t = const_cast<T*>(&*x);");
8127   verifyGoogleFormat("Type* t = x++ * y;");
8128   verifyGoogleFormat(
8129       "const char* const p = reinterpret_cast<const char* const>(q);");
8130   verifyGoogleFormat("void f(int i = 0, SomeType** temps = NULL);");
8131   verifyGoogleFormat("void f(Bar* a = nullptr, Bar* b);");
8132   verifyGoogleFormat("template <typename T>\n"
8133                      "void f(int i = 0, SomeType** temps = NULL);");
8134 
8135   FormatStyle Left = getLLVMStyle();
8136   Left.PointerAlignment = FormatStyle::PAS_Left;
8137   verifyFormat("x = *a(x) = *a(y);", Left);
8138   verifyFormat("for (;; *a = b) {\n}", Left);
8139   verifyFormat("return *this += 1;", Left);
8140   verifyFormat("throw *x;", Left);
8141   verifyFormat("delete *x;", Left);
8142   verifyFormat("typedef typeof(int(int, int))* MyFuncPtr;", Left);
8143   verifyFormat("[](const decltype(*a)* ptr) {}", Left);
8144   verifyFormat("[](const typeof(*a)* ptr) {}", Left);
8145   verifyFormat("[](const _Atomic(a*)* ptr) {}", Left);
8146   verifyFormat("[](const __underlying_type(a)* ptr) {}", Left);
8147   verifyFormat("typedef typeof /*comment*/ (int(int, int))* MyFuncPtr;", Left);
8148   verifyFormat("auto x(A&&, B&&, C&&) -> D;", Left);
8149   verifyFormat("auto x = [](A&&, B&&, C&&) -> D {};", Left);
8150   verifyFormat("template <class T> X(T&&, T&&, T&&) -> X<T>;", Left);
8151 
8152   verifyIndependentOfContext("a = *(x + y);");
8153   verifyIndependentOfContext("a = &(x + y);");
8154   verifyIndependentOfContext("*(x + y).call();");
8155   verifyIndependentOfContext("&(x + y)->call();");
8156   verifyFormat("void f() { &(*I).first; }");
8157 
8158   verifyIndependentOfContext("f(b * /* confusing comment */ ++c);");
8159   verifyFormat(
8160       "int *MyValues = {\n"
8161       "    *A, // Operator detection might be confused by the '{'\n"
8162       "    *BB // Operator detection might be confused by previous comment\n"
8163       "};");
8164 
8165   verifyIndependentOfContext("if (int *a = &b)");
8166   verifyIndependentOfContext("if (int &a = *b)");
8167   verifyIndependentOfContext("if (a & b[i])");
8168   verifyIndependentOfContext("if constexpr (a & b[i])");
8169   verifyIndependentOfContext("if CONSTEXPR (a & b[i])");
8170   verifyIndependentOfContext("if (a * (b * c))");
8171   verifyIndependentOfContext("if constexpr (a * (b * c))");
8172   verifyIndependentOfContext("if CONSTEXPR (a * (b * c))");
8173   verifyIndependentOfContext("if (a::b::c::d & b[i])");
8174   verifyIndependentOfContext("if (*b[i])");
8175   verifyIndependentOfContext("if (int *a = (&b))");
8176   verifyIndependentOfContext("while (int *a = &b)");
8177   verifyIndependentOfContext("while (a * (b * c))");
8178   verifyIndependentOfContext("size = sizeof *a;");
8179   verifyIndependentOfContext("if (a && (b = c))");
8180   verifyFormat("void f() {\n"
8181                "  for (const int &v : Values) {\n"
8182                "  }\n"
8183                "}");
8184   verifyFormat("for (int i = a * a; i < 10; ++i) {\n}");
8185   verifyFormat("for (int i = 0; i < a * a; ++i) {\n}");
8186   verifyGoogleFormat("for (int i = 0; i * 2 < z; i *= 2) {\n}");
8187 
8188   verifyFormat("#define A (!a * b)");
8189   verifyFormat("#define MACRO     \\\n"
8190                "  int *i = a * b; \\\n"
8191                "  void f(a *b);",
8192                getLLVMStyleWithColumns(19));
8193 
8194   verifyIndependentOfContext("A = new SomeType *[Length];");
8195   verifyIndependentOfContext("A = new SomeType *[Length]();");
8196   verifyIndependentOfContext("T **t = new T *;");
8197   verifyIndependentOfContext("T **t = new T *();");
8198   verifyGoogleFormat("A = new SomeType*[Length]();");
8199   verifyGoogleFormat("A = new SomeType*[Length];");
8200   verifyGoogleFormat("T** t = new T*;");
8201   verifyGoogleFormat("T** t = new T*();");
8202 
8203   verifyFormat("STATIC_ASSERT((a & b) == 0);");
8204   verifyFormat("STATIC_ASSERT(0 == (a & b));");
8205   verifyFormat("template <bool a, bool b> "
8206                "typename t::if<x && y>::type f() {}");
8207   verifyFormat("template <int *y> f() {}");
8208   verifyFormat("vector<int *> v;");
8209   verifyFormat("vector<int *const> v;");
8210   verifyFormat("vector<int *const **const *> v;");
8211   verifyFormat("vector<int *volatile> v;");
8212   verifyFormat("vector<a *_Nonnull> v;");
8213   verifyFormat("vector<a *_Nullable> v;");
8214   verifyFormat("vector<a *_Null_unspecified> v;");
8215   verifyFormat("vector<a *__ptr32> v;");
8216   verifyFormat("vector<a *__ptr64> v;");
8217   verifyFormat("vector<a *__capability> v;");
8218   FormatStyle TypeMacros = getLLVMStyle();
8219   TypeMacros.TypenameMacros = {"LIST"};
8220   verifyFormat("vector<LIST(uint64_t)> v;", TypeMacros);
8221   verifyFormat("vector<LIST(uint64_t) *> v;", TypeMacros);
8222   verifyFormat("vector<LIST(uint64_t) **> v;", TypeMacros);
8223   verifyFormat("vector<LIST(uint64_t) *attr> v;", TypeMacros);
8224   verifyFormat("vector<A(uint64_t) * attr> v;", TypeMacros); // multiplication
8225 
8226   FormatStyle CustomQualifier = getLLVMStyle();
8227   // Add indentifers that should not be parsed as a qualifier by default.
8228   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
8229   CustomQualifier.AttributeMacros.push_back("_My_qualifier");
8230   CustomQualifier.AttributeMacros.push_back("my_other_qualifier");
8231   verifyFormat("vector<a * __my_qualifier> parse_as_multiply;");
8232   verifyFormat("vector<a *__my_qualifier> v;", CustomQualifier);
8233   verifyFormat("vector<a * _My_qualifier> parse_as_multiply;");
8234   verifyFormat("vector<a *_My_qualifier> v;", CustomQualifier);
8235   verifyFormat("vector<a * my_other_qualifier> parse_as_multiply;");
8236   verifyFormat("vector<a *my_other_qualifier> v;", CustomQualifier);
8237   verifyFormat("vector<a * _NotAQualifier> v;");
8238   verifyFormat("vector<a * __not_a_qualifier> v;");
8239   verifyFormat("vector<a * b> v;");
8240   verifyFormat("foo<b && false>();");
8241   verifyFormat("foo<b & 1>();");
8242   verifyFormat("decltype(*::std::declval<const T &>()) void F();");
8243   verifyFormat("typeof(*::std::declval<const T &>()) void F();");
8244   verifyFormat("_Atomic(*::std::declval<const T &>()) void F();");
8245   verifyFormat("__underlying_type(*::std::declval<const T &>()) void F();");
8246   verifyFormat(
8247       "template <class T, class = typename std::enable_if<\n"
8248       "                       std::is_integral<T>::value &&\n"
8249       "                       (sizeof(T) > 1 || sizeof(T) < 8)>::type>\n"
8250       "void F();",
8251       getLLVMStyleWithColumns(70));
8252   verifyFormat("template <class T,\n"
8253                "          class = typename std::enable_if<\n"
8254                "              std::is_integral<T>::value &&\n"
8255                "              (sizeof(T) > 1 || sizeof(T) < 8)>::type,\n"
8256                "          class U>\n"
8257                "void F();",
8258                getLLVMStyleWithColumns(70));
8259   verifyFormat(
8260       "template <class T,\n"
8261       "          class = typename ::std::enable_if<\n"
8262       "              ::std::is_array<T>{} && ::std::is_array<T>{}>::type>\n"
8263       "void F();",
8264       getGoogleStyleWithColumns(68));
8265 
8266   verifyIndependentOfContext("MACRO(int *i);");
8267   verifyIndependentOfContext("MACRO(auto *a);");
8268   verifyIndependentOfContext("MACRO(const A *a);");
8269   verifyIndependentOfContext("MACRO(_Atomic(A) *a);");
8270   verifyIndependentOfContext("MACRO(decltype(A) *a);");
8271   verifyIndependentOfContext("MACRO(typeof(A) *a);");
8272   verifyIndependentOfContext("MACRO(__underlying_type(A) *a);");
8273   verifyIndependentOfContext("MACRO(A *const a);");
8274   verifyIndependentOfContext("MACRO(A *restrict a);");
8275   verifyIndependentOfContext("MACRO(A *__restrict__ a);");
8276   verifyIndependentOfContext("MACRO(A *__restrict a);");
8277   verifyIndependentOfContext("MACRO(A *volatile a);");
8278   verifyIndependentOfContext("MACRO(A *__volatile a);");
8279   verifyIndependentOfContext("MACRO(A *__volatile__ a);");
8280   verifyIndependentOfContext("MACRO(A *_Nonnull a);");
8281   verifyIndependentOfContext("MACRO(A *_Nullable a);");
8282   verifyIndependentOfContext("MACRO(A *_Null_unspecified a);");
8283   verifyIndependentOfContext("MACRO(A *__attribute__((foo)) a);");
8284   verifyIndependentOfContext("MACRO(A *__attribute((foo)) a);");
8285   verifyIndependentOfContext("MACRO(A *[[clang::attr]] a);");
8286   verifyIndependentOfContext("MACRO(A *[[clang::attr(\"foo\")]] a);");
8287   verifyIndependentOfContext("MACRO(A *__ptr32 a);");
8288   verifyIndependentOfContext("MACRO(A *__ptr64 a);");
8289   verifyIndependentOfContext("MACRO(A *__capability);");
8290   verifyIndependentOfContext("MACRO(A &__capability);");
8291   verifyFormat("MACRO(A *__my_qualifier);");               // type declaration
8292   verifyFormat("void f() { MACRO(A * __my_qualifier); }"); // multiplication
8293   // If we add __my_qualifier to AttributeMacros it should always be parsed as
8294   // a type declaration:
8295   verifyFormat("MACRO(A *__my_qualifier);", CustomQualifier);
8296   verifyFormat("void f() { MACRO(A *__my_qualifier); }", CustomQualifier);
8297   // Also check that TypenameMacros prevents parsing it as multiplication:
8298   verifyIndependentOfContext("MACRO(LIST(uint64_t) * a);"); // multiplication
8299   verifyIndependentOfContext("MACRO(LIST(uint64_t) *a);", TypeMacros); // type
8300 
8301   verifyIndependentOfContext("MACRO('0' <= c && c <= '9');");
8302   verifyFormat("void f() { f(float{1}, a * a); }");
8303   // FIXME: Is there a way to make this work?
8304   // verifyIndependentOfContext("MACRO(A *a);");
8305   verifyFormat("MACRO(A &B);");
8306   verifyFormat("MACRO(A *B);");
8307   verifyFormat("void f() { MACRO(A * B); }");
8308   verifyFormat("void f() { MACRO(A & B); }");
8309 
8310   // This lambda was mis-formatted after D88956 (treating it as a binop):
8311   verifyFormat("auto x = [](const decltype(x) &ptr) {};");
8312   verifyFormat("auto x = [](const decltype(x) *ptr) {};");
8313   verifyFormat("#define lambda [](const decltype(x) &ptr) {}");
8314   verifyFormat("#define lambda [](const decltype(x) *ptr) {}");
8315 
8316   verifyFormat("DatumHandle const *operator->() const { return input_; }");
8317   verifyFormat("return options != nullptr && operator==(*options);");
8318 
8319   EXPECT_EQ("#define OP(x)                                    \\\n"
8320             "  ostream &operator<<(ostream &s, const A &a) {  \\\n"
8321             "    return s << a.DebugString();                 \\\n"
8322             "  }",
8323             format("#define OP(x) \\\n"
8324                    "  ostream &operator<<(ostream &s, const A &a) { \\\n"
8325                    "    return s << a.DebugString(); \\\n"
8326                    "  }",
8327                    getLLVMStyleWithColumns(50)));
8328 
8329   // FIXME: We cannot handle this case yet; we might be able to figure out that
8330   // foo<x> d > v; doesn't make sense.
8331   verifyFormat("foo<a<b && c> d> v;");
8332 
8333   FormatStyle PointerMiddle = getLLVMStyle();
8334   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
8335   verifyFormat("delete *x;", PointerMiddle);
8336   verifyFormat("int * x;", PointerMiddle);
8337   verifyFormat("int *[] x;", PointerMiddle);
8338   verifyFormat("template <int * y> f() {}", PointerMiddle);
8339   verifyFormat("int * f(int * a) {}", PointerMiddle);
8340   verifyFormat("int main(int argc, char ** argv) {}", PointerMiddle);
8341   verifyFormat("Test::Test(int b) : a(b * b) {}", PointerMiddle);
8342   verifyFormat("A<int *> a;", PointerMiddle);
8343   verifyFormat("A<int **> a;", PointerMiddle);
8344   verifyFormat("A<int *, int *> a;", PointerMiddle);
8345   verifyFormat("A<int *[]> a;", PointerMiddle);
8346   verifyFormat("A = new SomeType *[Length]();", PointerMiddle);
8347   verifyFormat("A = new SomeType *[Length];", PointerMiddle);
8348   verifyFormat("T ** t = new T *;", PointerMiddle);
8349 
8350   // Member function reference qualifiers aren't binary operators.
8351   verifyFormat("string // break\n"
8352                "operator()() & {}");
8353   verifyFormat("string // break\n"
8354                "operator()() && {}");
8355   verifyGoogleFormat("template <typename T>\n"
8356                      "auto x() & -> int {}");
8357 }
8358 
8359 TEST_F(FormatTest, UnderstandsAttributes) {
8360   verifyFormat("SomeType s __attribute__((unused)) (InitValue);");
8361   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa __attribute__((unused))\n"
8362                "aaaaaaaaaaaaaaaaaaaaaaa(int i);");
8363   FormatStyle AfterType = getLLVMStyle();
8364   AfterType.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
8365   verifyFormat("__attribute__((nodebug)) void\n"
8366                "foo() {}\n",
8367                AfterType);
8368   verifyFormat("__unused void\n"
8369                "foo() {}",
8370                AfterType);
8371 
8372   FormatStyle CustomAttrs = getLLVMStyle();
8373   CustomAttrs.AttributeMacros.push_back("__unused");
8374   CustomAttrs.AttributeMacros.push_back("__attr1");
8375   CustomAttrs.AttributeMacros.push_back("__attr2");
8376   CustomAttrs.AttributeMacros.push_back("no_underscore_attr");
8377   verifyFormat("vector<SomeType *__attribute((foo))> v;");
8378   verifyFormat("vector<SomeType *__attribute__((foo))> v;");
8379   verifyFormat("vector<SomeType * __not_attribute__((foo))> v;");
8380   // Check that it is parsed as a multiplication without AttributeMacros and
8381   // as a pointer qualifier when we add __attr1/__attr2 to AttributeMacros.
8382   verifyFormat("vector<SomeType * __attr1> v;");
8383   verifyFormat("vector<SomeType __attr1 *> v;");
8384   verifyFormat("vector<SomeType __attr1 *const> v;");
8385   verifyFormat("vector<SomeType __attr1 * __attr2> v;");
8386   verifyFormat("vector<SomeType *__attr1> v;", CustomAttrs);
8387   verifyFormat("vector<SomeType *__attr2> v;", CustomAttrs);
8388   verifyFormat("vector<SomeType *no_underscore_attr> v;", CustomAttrs);
8389   verifyFormat("vector<SomeType __attr1 *> v;", CustomAttrs);
8390   verifyFormat("vector<SomeType __attr1 *const> v;", CustomAttrs);
8391   verifyFormat("vector<SomeType __attr1 *__attr2> v;", CustomAttrs);
8392   verifyFormat("vector<SomeType __attr1 *no_underscore_attr> v;", CustomAttrs);
8393 
8394   // Check that these are not parsed as function declarations:
8395   CustomAttrs.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8396   CustomAttrs.BreakBeforeBraces = FormatStyle::BS_Allman;
8397   verifyFormat("SomeType s(InitValue);", CustomAttrs);
8398   verifyFormat("SomeType s{InitValue};", CustomAttrs);
8399   verifyFormat("SomeType *__unused s(InitValue);", CustomAttrs);
8400   verifyFormat("SomeType *__unused s{InitValue};", CustomAttrs);
8401   verifyFormat("SomeType s __unused(InitValue);", CustomAttrs);
8402   verifyFormat("SomeType s __unused{InitValue};", CustomAttrs);
8403   verifyFormat("SomeType *__capability s(InitValue);", CustomAttrs);
8404   verifyFormat("SomeType *__capability s{InitValue};", CustomAttrs);
8405 }
8406 
8407 TEST_F(FormatTest, UnderstandsPointerQualifiersInCast) {
8408   // Check that qualifiers on pointers don't break parsing of casts.
8409   verifyFormat("x = (foo *const)*v;");
8410   verifyFormat("x = (foo *volatile)*v;");
8411   verifyFormat("x = (foo *restrict)*v;");
8412   verifyFormat("x = (foo *__attribute__((foo)))*v;");
8413   verifyFormat("x = (foo *_Nonnull)*v;");
8414   verifyFormat("x = (foo *_Nullable)*v;");
8415   verifyFormat("x = (foo *_Null_unspecified)*v;");
8416   verifyFormat("x = (foo *_Nonnull)*v;");
8417   verifyFormat("x = (foo *[[clang::attr]])*v;");
8418   verifyFormat("x = (foo *[[clang::attr(\"foo\")]])*v;");
8419   verifyFormat("x = (foo *__ptr32)*v;");
8420   verifyFormat("x = (foo *__ptr64)*v;");
8421   verifyFormat("x = (foo *__capability)*v;");
8422 
8423   // Check that we handle multiple trailing qualifiers and skip them all to
8424   // determine that the expression is a cast to a pointer type.
8425   FormatStyle LongPointerRight = getLLVMStyleWithColumns(999);
8426   FormatStyle LongPointerLeft = getLLVMStyleWithColumns(999);
8427   LongPointerLeft.PointerAlignment = FormatStyle::PAS_Left;
8428   StringRef AllQualifiers =
8429       "const volatile restrict __attribute__((foo)) _Nonnull _Null_unspecified "
8430       "_Nonnull [[clang::attr]] __ptr32 __ptr64 __capability";
8431   verifyFormat(("x = (foo *" + AllQualifiers + ")*v;").str(), LongPointerRight);
8432   verifyFormat(("x = (foo* " + AllQualifiers + ")*v;").str(), LongPointerLeft);
8433 
8434   // Also check that address-of is not parsed as a binary bitwise-and:
8435   verifyFormat("x = (foo *const)&v;");
8436   verifyFormat(("x = (foo *" + AllQualifiers + ")&v;").str(), LongPointerRight);
8437   verifyFormat(("x = (foo* " + AllQualifiers + ")&v;").str(), LongPointerLeft);
8438 
8439   // Check custom qualifiers:
8440   FormatStyle CustomQualifier = getLLVMStyleWithColumns(999);
8441   CustomQualifier.AttributeMacros.push_back("__my_qualifier");
8442   verifyFormat("x = (foo * __my_qualifier) * v;"); // not parsed as qualifier.
8443   verifyFormat("x = (foo *__my_qualifier)*v;", CustomQualifier);
8444   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)*v;").str(),
8445                CustomQualifier);
8446   verifyFormat(("x = (foo *" + AllQualifiers + " __my_qualifier)&v;").str(),
8447                CustomQualifier);
8448 
8449   // Check that unknown identifiers result in binary operator parsing:
8450   verifyFormat("x = (foo * __unknown_qualifier) * v;");
8451   verifyFormat("x = (foo * __unknown_qualifier) & v;");
8452 }
8453 
8454 TEST_F(FormatTest, UnderstandsSquareAttributes) {
8455   verifyFormat("SomeType s [[unused]] (InitValue);");
8456   verifyFormat("SomeType s [[gnu::unused]] (InitValue);");
8457   verifyFormat("SomeType s [[using gnu: unused]] (InitValue);");
8458   verifyFormat("[[gsl::suppress(\"clang-tidy-check-name\")]] void f() {}");
8459   verifyFormat("void f() [[deprecated(\"so sorry\")]];");
8460   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8461                "    [[unused]] aaaaaaaaaaaaaaaaaaaaaaa(int i);");
8462   verifyFormat("[[nodiscard]] bool f() { return false; }");
8463   verifyFormat("class [[nodiscard]] f {\npublic:\n  f() {}\n}");
8464   verifyFormat("class [[deprecated(\"so sorry\")]] f {\npublic:\n  f() {}\n}");
8465   verifyFormat("class [[gnu::unused]] f {\npublic:\n  f() {}\n}");
8466 
8467   // Make sure we do not mistake attributes for array subscripts.
8468   verifyFormat("int a() {}\n"
8469                "[[unused]] int b() {}\n");
8470   verifyFormat("NSArray *arr;\n"
8471                "arr[[Foo() bar]];");
8472 
8473   // On the other hand, we still need to correctly find array subscripts.
8474   verifyFormat("int a = std::vector<int>{1, 2, 3}[0];");
8475 
8476   // Make sure that we do not mistake Objective-C method inside array literals
8477   // as attributes, even if those method names are also keywords.
8478   verifyFormat("@[ [foo bar] ];");
8479   verifyFormat("@[ [NSArray class] ];");
8480   verifyFormat("@[ [foo enum] ];");
8481 
8482   verifyFormat("template <typename T> [[nodiscard]] int a() { return 1; }");
8483 
8484   // Make sure we do not parse attributes as lambda introducers.
8485   FormatStyle MultiLineFunctions = getLLVMStyle();
8486   MultiLineFunctions.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
8487   verifyFormat("[[unused]] int b() {\n"
8488                "  return 42;\n"
8489                "}\n",
8490                MultiLineFunctions);
8491 }
8492 
8493 TEST_F(FormatTest, AttributeClass) {
8494   FormatStyle Style = getChromiumStyle(FormatStyle::LK_Cpp);
8495   verifyFormat("class S {\n"
8496                "  S(S&&) = default;\n"
8497                "};",
8498                Style);
8499   verifyFormat("class [[nodiscard]] S {\n"
8500                "  S(S&&) = default;\n"
8501                "};",
8502                Style);
8503   verifyFormat("class __attribute((maybeunused)) S {\n"
8504                "  S(S&&) = default;\n"
8505                "};",
8506                Style);
8507   verifyFormat("struct S {\n"
8508                "  S(S&&) = default;\n"
8509                "};",
8510                Style);
8511   verifyFormat("struct [[nodiscard]] S {\n"
8512                "  S(S&&) = default;\n"
8513                "};",
8514                Style);
8515 }
8516 
8517 TEST_F(FormatTest, AttributesAfterMacro) {
8518   FormatStyle Style = getLLVMStyle();
8519   verifyFormat("MACRO;\n"
8520                "__attribute__((maybe_unused)) int foo() {\n"
8521                "  //...\n"
8522                "}");
8523 
8524   verifyFormat("MACRO;\n"
8525                "[[nodiscard]] int foo() {\n"
8526                "  //...\n"
8527                "}");
8528 
8529   EXPECT_EQ("MACRO\n\n"
8530             "__attribute__((maybe_unused)) int foo() {\n"
8531             "  //...\n"
8532             "}",
8533             format("MACRO\n\n"
8534                    "__attribute__((maybe_unused)) int foo() {\n"
8535                    "  //...\n"
8536                    "}"));
8537 
8538   EXPECT_EQ("MACRO\n\n"
8539             "[[nodiscard]] int foo() {\n"
8540             "  //...\n"
8541             "}",
8542             format("MACRO\n\n"
8543                    "[[nodiscard]] int foo() {\n"
8544                    "  //...\n"
8545                    "}"));
8546 }
8547 
8548 TEST_F(FormatTest, AttributePenaltyBreaking) {
8549   FormatStyle Style = getLLVMStyle();
8550   verifyFormat("void ABCDEFGH::ABCDEFGHIJKLMN(\n"
8551                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
8552                Style);
8553   verifyFormat("void ABCDEFGH::ABCDEFGHIJK(\n"
8554                "    [[maybe_unused]] const shared_ptr<ALongTypeName> &C d) {}",
8555                Style);
8556   verifyFormat("void ABCDEFGH::ABCDEFGH([[maybe_unused]] const "
8557                "shared_ptr<ALongTypeName> &C d) {\n}",
8558                Style);
8559 }
8560 
8561 TEST_F(FormatTest, UnderstandsEllipsis) {
8562   FormatStyle Style = getLLVMStyle();
8563   verifyFormat("int printf(const char *fmt, ...);");
8564   verifyFormat("template <class... Ts> void Foo(Ts... ts) { Foo(ts...); }");
8565   verifyFormat("template <class... Ts> void Foo(Ts *...ts) {}");
8566 
8567   verifyFormat("template <int *...PP> a;", Style);
8568 
8569   Style.PointerAlignment = FormatStyle::PAS_Left;
8570   verifyFormat("template <class... Ts> void Foo(Ts*... ts) {}", Style);
8571 
8572   verifyFormat("template <int*... PP> a;", Style);
8573 
8574   Style.PointerAlignment = FormatStyle::PAS_Middle;
8575   verifyFormat("template <int *... PP> a;", Style);
8576 }
8577 
8578 TEST_F(FormatTest, AdaptivelyFormatsPointersAndReferences) {
8579   EXPECT_EQ("int *a;\n"
8580             "int *a;\n"
8581             "int *a;",
8582             format("int *a;\n"
8583                    "int* a;\n"
8584                    "int *a;",
8585                    getGoogleStyle()));
8586   EXPECT_EQ("int* a;\n"
8587             "int* a;\n"
8588             "int* a;",
8589             format("int* a;\n"
8590                    "int* a;\n"
8591                    "int *a;",
8592                    getGoogleStyle()));
8593   EXPECT_EQ("int *a;\n"
8594             "int *a;\n"
8595             "int *a;",
8596             format("int *a;\n"
8597                    "int * a;\n"
8598                    "int *  a;",
8599                    getGoogleStyle()));
8600   EXPECT_EQ("auto x = [] {\n"
8601             "  int *a;\n"
8602             "  int *a;\n"
8603             "  int *a;\n"
8604             "};",
8605             format("auto x=[]{int *a;\n"
8606                    "int * a;\n"
8607                    "int *  a;};",
8608                    getGoogleStyle()));
8609 }
8610 
8611 TEST_F(FormatTest, UnderstandsRvalueReferences) {
8612   verifyFormat("int f(int &&a) {}");
8613   verifyFormat("int f(int a, char &&b) {}");
8614   verifyFormat("void f() { int &&a = b; }");
8615   verifyGoogleFormat("int f(int a, char&& b) {}");
8616   verifyGoogleFormat("void f() { int&& a = b; }");
8617 
8618   verifyIndependentOfContext("A<int &&> a;");
8619   verifyIndependentOfContext("A<int &&, int &&> a;");
8620   verifyGoogleFormat("A<int&&> a;");
8621   verifyGoogleFormat("A<int&&, int&&> a;");
8622 
8623   // Not rvalue references:
8624   verifyFormat("template <bool B, bool C> class A {\n"
8625                "  static_assert(B && C, \"Something is wrong\");\n"
8626                "};");
8627   verifyGoogleFormat("#define IF(a, b, c) if (a && (b == c))");
8628   verifyGoogleFormat("#define WHILE(a, b, c) while (a && (b == c))");
8629   verifyFormat("#define A(a, b) (a && b)");
8630 }
8631 
8632 TEST_F(FormatTest, FormatsBinaryOperatorsPrecedingEquals) {
8633   verifyFormat("void f() {\n"
8634                "  x[aaaaaaaaa -\n"
8635                "    b] = 23;\n"
8636                "}",
8637                getLLVMStyleWithColumns(15));
8638 }
8639 
8640 TEST_F(FormatTest, FormatsCasts) {
8641   verifyFormat("Type *A = static_cast<Type *>(P);");
8642   verifyFormat("Type *A = (Type *)P;");
8643   verifyFormat("Type *A = (vector<Type *, int *>)P;");
8644   verifyFormat("int a = (int)(2.0f);");
8645   verifyFormat("int a = (int)2.0f;");
8646   verifyFormat("x[(int32)y];");
8647   verifyFormat("x = (int32)y;");
8648   verifyFormat("#define AA(X) sizeof(((X *)NULL)->a)");
8649   verifyFormat("int a = (int)*b;");
8650   verifyFormat("int a = (int)2.0f;");
8651   verifyFormat("int a = (int)~0;");
8652   verifyFormat("int a = (int)++a;");
8653   verifyFormat("int a = (int)sizeof(int);");
8654   verifyFormat("int a = (int)+2;");
8655   verifyFormat("my_int a = (my_int)2.0f;");
8656   verifyFormat("my_int a = (my_int)sizeof(int);");
8657   verifyFormat("return (my_int)aaa;");
8658   verifyFormat("#define x ((int)-1)");
8659   verifyFormat("#define LENGTH(x, y) (x) - (y) + 1");
8660   verifyFormat("#define p(q) ((int *)&q)");
8661   verifyFormat("fn(a)(b) + 1;");
8662 
8663   verifyFormat("void f() { my_int a = (my_int)*b; }");
8664   verifyFormat("void f() { return P ? (my_int)*P : (my_int)0; }");
8665   verifyFormat("my_int a = (my_int)~0;");
8666   verifyFormat("my_int a = (my_int)++a;");
8667   verifyFormat("my_int a = (my_int)-2;");
8668   verifyFormat("my_int a = (my_int)1;");
8669   verifyFormat("my_int a = (my_int *)1;");
8670   verifyFormat("my_int a = (const my_int)-1;");
8671   verifyFormat("my_int a = (const my_int *)-1;");
8672   verifyFormat("my_int a = (my_int)(my_int)-1;");
8673   verifyFormat("my_int a = (ns::my_int)-2;");
8674   verifyFormat("case (my_int)ONE:");
8675   verifyFormat("auto x = (X)this;");
8676   // Casts in Obj-C style calls used to not be recognized as such.
8677   verifyFormat("int a = [(type*)[((type*)val) arg] arg];", getGoogleStyle());
8678 
8679   // FIXME: single value wrapped with paren will be treated as cast.
8680   verifyFormat("void f(int i = (kValue)*kMask) {}");
8681 
8682   verifyFormat("{ (void)F; }");
8683 
8684   // Don't break after a cast's
8685   verifyFormat("int aaaaaaaaaaaaaaaaaaaaaaaaaaa =\n"
8686                "    (aaaaaaaaaaaaaaaaaaaaaaaaaa *)(aaaaaaaaaaaaaaaaaaaaaa +\n"
8687                "                                   bbbbbbbbbbbbbbbbbbbbbb);");
8688 
8689   // These are not casts.
8690   verifyFormat("void f(int *) {}");
8691   verifyFormat("f(foo)->b;");
8692   verifyFormat("f(foo).b;");
8693   verifyFormat("f(foo)(b);");
8694   verifyFormat("f(foo)[b];");
8695   verifyFormat("[](foo) { return 4; }(bar);");
8696   verifyFormat("(*funptr)(foo)[4];");
8697   verifyFormat("funptrs[4](foo)[4];");
8698   verifyFormat("void f(int *);");
8699   verifyFormat("void f(int *) = 0;");
8700   verifyFormat("void f(SmallVector<int>) {}");
8701   verifyFormat("void f(SmallVector<int>);");
8702   verifyFormat("void f(SmallVector<int>) = 0;");
8703   verifyFormat("void f(int i = (kA * kB) & kMask) {}");
8704   verifyFormat("int a = sizeof(int) * b;");
8705   verifyFormat("int a = alignof(int) * b;", getGoogleStyle());
8706   verifyFormat("template <> void f<int>(int i) SOME_ANNOTATION;");
8707   verifyFormat("f(\"%\" SOME_MACRO(ll) \"d\");");
8708   verifyFormat("aaaaa &operator=(const aaaaa &) LLVM_DELETED_FUNCTION;");
8709 
8710   // These are not casts, but at some point were confused with casts.
8711   verifyFormat("virtual void foo(int *) override;");
8712   verifyFormat("virtual void foo(char &) const;");
8713   verifyFormat("virtual void foo(int *a, char *) const;");
8714   verifyFormat("int a = sizeof(int *) + b;");
8715   verifyFormat("int a = alignof(int *) + b;", getGoogleStyle());
8716   verifyFormat("bool b = f(g<int>) && c;");
8717   verifyFormat("typedef void (*f)(int i) func;");
8718   verifyFormat("void operator++(int) noexcept;");
8719   verifyFormat("void operator++(int &) noexcept;");
8720   verifyFormat("void operator delete(void *, std::size_t, const std::nothrow_t "
8721                "&) noexcept;");
8722   verifyFormat(
8723       "void operator delete(std::size_t, const std::nothrow_t &) noexcept;");
8724   verifyFormat("void operator delete(const std::nothrow_t &) noexcept;");
8725   verifyFormat("void operator delete(std::nothrow_t &) noexcept;");
8726   verifyFormat("void operator delete(nothrow_t &) noexcept;");
8727   verifyFormat("void operator delete(foo &) noexcept;");
8728   verifyFormat("void operator delete(foo) noexcept;");
8729   verifyFormat("void operator delete(int) noexcept;");
8730   verifyFormat("void operator delete(int &) noexcept;");
8731   verifyFormat("void operator delete(int &) volatile noexcept;");
8732   verifyFormat("void operator delete(int &) const");
8733   verifyFormat("void operator delete(int &) = default");
8734   verifyFormat("void operator delete(int &) = delete");
8735   verifyFormat("void operator delete(int &) [[noreturn]]");
8736   verifyFormat("void operator delete(int &) throw();");
8737   verifyFormat("void operator delete(int &) throw(int);");
8738   verifyFormat("auto operator delete(int &) -> int;");
8739   verifyFormat("auto operator delete(int &) override");
8740   verifyFormat("auto operator delete(int &) final");
8741 
8742   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa *foo = (aaaaaaaaaaaaaaaaa *)\n"
8743                "    bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;");
8744   // FIXME: The indentation here is not ideal.
8745   verifyFormat(
8746       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8747       "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = (*cccccccccccccccc)\n"
8748       "        [dddddddddddddddddddddddddddddddddddddddddddddddddddddddd];");
8749 }
8750 
8751 TEST_F(FormatTest, FormatsFunctionTypes) {
8752   verifyFormat("A<bool()> a;");
8753   verifyFormat("A<SomeType()> a;");
8754   verifyFormat("A<void (*)(int, std::string)> a;");
8755   verifyFormat("A<void *(int)>;");
8756   verifyFormat("void *(*a)(int *, SomeType *);");
8757   verifyFormat("int (*func)(void *);");
8758   verifyFormat("void f() { int (*func)(void *); }");
8759   verifyFormat("template <class CallbackClass>\n"
8760                "using MyCallback = void (CallbackClass::*)(SomeObject *Data);");
8761 
8762   verifyGoogleFormat("A<void*(int*, SomeType*)>;");
8763   verifyGoogleFormat("void* (*a)(int);");
8764   verifyGoogleFormat(
8765       "template <class CallbackClass>\n"
8766       "using MyCallback = void (CallbackClass::*)(SomeObject* Data);");
8767 
8768   // Other constructs can look somewhat like function types:
8769   verifyFormat("A<sizeof(*x)> a;");
8770   verifyFormat("#define DEREF_AND_CALL_F(x) f(*x)");
8771   verifyFormat("some_var = function(*some_pointer_var)[0];");
8772   verifyFormat("void f() { function(*some_pointer_var)[0] = 10; }");
8773   verifyFormat("int x = f(&h)();");
8774   verifyFormat("returnsFunction(&param1, &param2)(param);");
8775   verifyFormat("std::function<\n"
8776                "    LooooooooooongTemplatedType<\n"
8777                "        SomeType>*(\n"
8778                "        LooooooooooooooooongType type)>\n"
8779                "    function;",
8780                getGoogleStyleWithColumns(40));
8781 }
8782 
8783 TEST_F(FormatTest, FormatsPointersToArrayTypes) {
8784   verifyFormat("A (*foo_)[6];");
8785   verifyFormat("vector<int> (*foo_)[6];");
8786 }
8787 
8788 TEST_F(FormatTest, BreaksLongVariableDeclarations) {
8789   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8790                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
8791   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType const\n"
8792                "    LoooooooooooooooooooooooooooooooooooooooongVariable;");
8793   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8794                "    *LoooooooooooooooooooooooooooooooooooooooongVariable;");
8795 
8796   // Different ways of ()-initializiation.
8797   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8798                "    LoooooooooooooooooooooooooooooooooooooooongVariable(1);");
8799   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8800                "    LoooooooooooooooooooooooooooooooooooooooongVariable(a);");
8801   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8802                "    LoooooooooooooooooooooooooooooooooooooooongVariable({});");
8803   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType\n"
8804                "    LoooooooooooooooooooooooooooooooooooooongVariable([A a]);");
8805 
8806   // Lambdas should not confuse the variable declaration heuristic.
8807   verifyFormat("LooooooooooooooooongType\n"
8808                "    variable(nullptr, [](A *a) {});",
8809                getLLVMStyleWithColumns(40));
8810 }
8811 
8812 TEST_F(FormatTest, BreaksLongDeclarations) {
8813   verifyFormat("typedef LoooooooooooooooooooooooooooooooooooooooongType\n"
8814                "    AnotherNameForTheLongType;");
8815   verifyFormat("typedef LongTemplateType<aaaaaaaaaaaaaaaaaaa()>\n"
8816                "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;");
8817   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8818                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
8819   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType *\n"
8820                "LoooooooooooooooooooooooooooooooongFunctionDeclaration();");
8821   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8822                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8823   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType MACRO\n"
8824                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8825   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
8826                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8827   verifyFormat("decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
8828                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8829   verifyFormat("typeof(LoooooooooooooooooooooooooooooooooooooooooongName)\n"
8830                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8831   verifyFormat("_Atomic(LooooooooooooooooooooooooooooooooooooooooongName)\n"
8832                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8833   verifyFormat("__underlying_type(LooooooooooooooooooooooooooooooongName)\n"
8834                "LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}");
8835   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8836                "LooooooooooooooooooooooooooongFunctionDeclaration(T... t);");
8837   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8838                "LooooooooooooooooooooooooooongFunctionDeclaration(T /*t*/) {}");
8839   FormatStyle Indented = getLLVMStyle();
8840   Indented.IndentWrappedFunctionNames = true;
8841   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8842                "    LoooooooooooooooooooooooooooooooongFunctionDeclaration();",
8843                Indented);
8844   verifyFormat(
8845       "LoooooooooooooooooooooooooooooooooooooooongReturnType\n"
8846       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8847       Indented);
8848   verifyFormat(
8849       "LoooooooooooooooooooooooooooooooooooooooongReturnType const\n"
8850       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8851       Indented);
8852   verifyFormat(
8853       "decltype(LoooooooooooooooooooooooooooooooooooooooongName)\n"
8854       "    LooooooooooooooooooooooooooooooooooongFunctionDefinition() {}",
8855       Indented);
8856 
8857   // FIXME: Without the comment, this breaks after "(".
8858   verifyFormat("LoooooooooooooooooooooooooooooooooooooooongType  // break\n"
8859                "    (*LoooooooooooooooooooooooooooongFunctionTypeVarialbe)();",
8860                getGoogleStyle());
8861 
8862   verifyFormat("int *someFunction(int LoooooooooooooooooooongParam1,\n"
8863                "                  int LoooooooooooooooooooongParam2) {}");
8864   verifyFormat(
8865       "TypeSpecDecl *TypeSpecDecl::Create(ASTContext &C, DeclContext *DC,\n"
8866       "                                   SourceLocation L, IdentifierIn *II,\n"
8867       "                                   Type *T) {}");
8868   verifyFormat("ReallyLongReturnType<TemplateParam1, TemplateParam2>\n"
8869                "ReallyReaaallyLongFunctionName(\n"
8870                "    const std::string &SomeParameter,\n"
8871                "    const SomeType<string, SomeOtherTemplateParameter>\n"
8872                "        &ReallyReallyLongParameterName,\n"
8873                "    const SomeType<string, SomeOtherTemplateParameter>\n"
8874                "        &AnotherLongParameterName) {}");
8875   verifyFormat("template <typename A>\n"
8876                "SomeLoooooooooooooooooooooongType<\n"
8877                "    typename some_namespace::SomeOtherType<A>::Type>\n"
8878                "Function() {}");
8879 
8880   verifyGoogleFormat(
8881       "aaaaaaaaaaaaaaaa::aaaaaaaaaaaaaaaa<aaaaaaaaaaaaa, aaaaaaaaaaaa>\n"
8882       "    aaaaaaaaaaaaaaaaaaaaaaa;");
8883   verifyGoogleFormat(
8884       "TypeSpecDecl* TypeSpecDecl::Create(ASTContext& C, DeclContext* DC,\n"
8885       "                                   SourceLocation L) {}");
8886   verifyGoogleFormat(
8887       "some_namespace::LongReturnType\n"
8888       "long_namespace::SomeVeryLongClass::SomeVeryLongFunction(\n"
8889       "    int first_long_parameter, int second_parameter) {}");
8890 
8891   verifyGoogleFormat("template <typename T>\n"
8892                      "aaaaaaaa::aaaaa::aaaaaa<T, aaaaaaaaaaaaaaaaaaaaaaaaa>\n"
8893                      "aaaaaaaaaaaaaaaaaaaaaaaa<T>::aaaaaaa() {}");
8894   verifyGoogleFormat("A<A<A>> aaaaaaaaaa(int aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
8895                      "                   int aaaaaaaaaaaaaaaaaaaaaaa);");
8896 
8897   verifyFormat("typedef size_t (*aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa)(\n"
8898                "    const aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
8899                "        *aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8900   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8901                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>\n"
8902                "        aaaaaaaaaaaaaaaaaaaaaaaa);");
8903   verifyFormat("void aaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
8904                "    vector<aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<\n"
8905                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>>\n"
8906                "        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
8907 
8908   verifyFormat("template <typename T> // Templates on own line.\n"
8909                "static int            // Some comment.\n"
8910                "MyFunction(int a);",
8911                getLLVMStyle());
8912 }
8913 
8914 TEST_F(FormatTest, FormatsAccessModifiers) {
8915   FormatStyle Style = getLLVMStyle();
8916   EXPECT_EQ(Style.EmptyLineBeforeAccessModifier,
8917             FormatStyle::ELBAMS_LogicalBlock);
8918   verifyFormat("struct foo {\n"
8919                "private:\n"
8920                "  void f() {}\n"
8921                "\n"
8922                "private:\n"
8923                "  int i;\n"
8924                "\n"
8925                "protected:\n"
8926                "  int j;\n"
8927                "};\n",
8928                Style);
8929   verifyFormat("struct foo {\n"
8930                "private:\n"
8931                "  void f() {}\n"
8932                "\n"
8933                "private:\n"
8934                "  int i;\n"
8935                "\n"
8936                "protected:\n"
8937                "  int j;\n"
8938                "};\n",
8939                "struct foo {\n"
8940                "private:\n"
8941                "  void f() {}\n"
8942                "private:\n"
8943                "  int i;\n"
8944                "protected:\n"
8945                "  int j;\n"
8946                "};\n",
8947                Style);
8948   verifyFormat("struct foo { /* comment */\n"
8949                "private:\n"
8950                "  int i;\n"
8951                "  // comment\n"
8952                "private:\n"
8953                "  int j;\n"
8954                "};\n",
8955                Style);
8956   verifyFormat("struct foo {\n"
8957                "#ifdef FOO\n"
8958                "#endif\n"
8959                "private:\n"
8960                "  int i;\n"
8961                "#ifdef FOO\n"
8962                "private:\n"
8963                "#endif\n"
8964                "  int j;\n"
8965                "};\n",
8966                Style);
8967   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
8968   verifyFormat("struct foo {\n"
8969                "private:\n"
8970                "  void f() {}\n"
8971                "private:\n"
8972                "  int i;\n"
8973                "protected:\n"
8974                "  int j;\n"
8975                "};\n",
8976                Style);
8977   verifyFormat("struct foo {\n"
8978                "private:\n"
8979                "  void f() {}\n"
8980                "private:\n"
8981                "  int i;\n"
8982                "protected:\n"
8983                "  int j;\n"
8984                "};\n",
8985                "struct foo {\n"
8986                "\n"
8987                "private:\n"
8988                "  void f() {}\n"
8989                "\n"
8990                "private:\n"
8991                "  int i;\n"
8992                "\n"
8993                "protected:\n"
8994                "  int j;\n"
8995                "};\n",
8996                Style);
8997   verifyFormat("struct foo { /* comment */\n"
8998                "private:\n"
8999                "  int i;\n"
9000                "  // comment\n"
9001                "private:\n"
9002                "  int j;\n"
9003                "};\n",
9004                "struct foo { /* comment */\n"
9005                "\n"
9006                "private:\n"
9007                "  int i;\n"
9008                "  // comment\n"
9009                "\n"
9010                "private:\n"
9011                "  int j;\n"
9012                "};\n",
9013                Style);
9014   verifyFormat("struct foo {\n"
9015                "#ifdef FOO\n"
9016                "#endif\n"
9017                "private:\n"
9018                "  int i;\n"
9019                "#ifdef FOO\n"
9020                "private:\n"
9021                "#endif\n"
9022                "  int j;\n"
9023                "};\n",
9024                "struct foo {\n"
9025                "#ifdef FOO\n"
9026                "#endif\n"
9027                "\n"
9028                "private:\n"
9029                "  int i;\n"
9030                "#ifdef FOO\n"
9031                "\n"
9032                "private:\n"
9033                "#endif\n"
9034                "  int j;\n"
9035                "};\n",
9036                Style);
9037   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9038   verifyFormat("struct foo {\n"
9039                "private:\n"
9040                "  void f() {}\n"
9041                "\n"
9042                "private:\n"
9043                "  int i;\n"
9044                "\n"
9045                "protected:\n"
9046                "  int j;\n"
9047                "};\n",
9048                Style);
9049   verifyFormat("struct foo {\n"
9050                "private:\n"
9051                "  void f() {}\n"
9052                "\n"
9053                "private:\n"
9054                "  int i;\n"
9055                "\n"
9056                "protected:\n"
9057                "  int j;\n"
9058                "};\n",
9059                "struct foo {\n"
9060                "private:\n"
9061                "  void f() {}\n"
9062                "private:\n"
9063                "  int i;\n"
9064                "protected:\n"
9065                "  int j;\n"
9066                "};\n",
9067                Style);
9068   verifyFormat("struct foo { /* comment */\n"
9069                "private:\n"
9070                "  int i;\n"
9071                "  // comment\n"
9072                "\n"
9073                "private:\n"
9074                "  int j;\n"
9075                "};\n",
9076                "struct foo { /* comment */\n"
9077                "private:\n"
9078                "  int i;\n"
9079                "  // comment\n"
9080                "\n"
9081                "private:\n"
9082                "  int j;\n"
9083                "};\n",
9084                Style);
9085   verifyFormat("struct foo {\n"
9086                "#ifdef FOO\n"
9087                "#endif\n"
9088                "\n"
9089                "private:\n"
9090                "  int i;\n"
9091                "#ifdef FOO\n"
9092                "\n"
9093                "private:\n"
9094                "#endif\n"
9095                "  int j;\n"
9096                "};\n",
9097                "struct foo {\n"
9098                "#ifdef FOO\n"
9099                "#endif\n"
9100                "private:\n"
9101                "  int i;\n"
9102                "#ifdef FOO\n"
9103                "private:\n"
9104                "#endif\n"
9105                "  int j;\n"
9106                "};\n",
9107                Style);
9108   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9109   EXPECT_EQ("struct foo {\n"
9110             "\n"
9111             "private:\n"
9112             "  void f() {}\n"
9113             "\n"
9114             "private:\n"
9115             "  int i;\n"
9116             "\n"
9117             "protected:\n"
9118             "  int j;\n"
9119             "};\n",
9120             format("struct foo {\n"
9121                    "\n"
9122                    "private:\n"
9123                    "  void f() {}\n"
9124                    "\n"
9125                    "private:\n"
9126                    "  int i;\n"
9127                    "\n"
9128                    "protected:\n"
9129                    "  int j;\n"
9130                    "};\n",
9131                    Style));
9132   verifyFormat("struct foo {\n"
9133                "private:\n"
9134                "  void f() {}\n"
9135                "private:\n"
9136                "  int i;\n"
9137                "protected:\n"
9138                "  int j;\n"
9139                "};\n",
9140                Style);
9141   EXPECT_EQ("struct foo { /* comment */\n"
9142             "\n"
9143             "private:\n"
9144             "  int i;\n"
9145             "  // comment\n"
9146             "\n"
9147             "private:\n"
9148             "  int j;\n"
9149             "};\n",
9150             format("struct foo { /* comment */\n"
9151                    "\n"
9152                    "private:\n"
9153                    "  int i;\n"
9154                    "  // comment\n"
9155                    "\n"
9156                    "private:\n"
9157                    "  int j;\n"
9158                    "};\n",
9159                    Style));
9160   verifyFormat("struct foo { /* comment */\n"
9161                "private:\n"
9162                "  int i;\n"
9163                "  // comment\n"
9164                "private:\n"
9165                "  int j;\n"
9166                "};\n",
9167                Style);
9168   EXPECT_EQ("struct foo {\n"
9169             "#ifdef FOO\n"
9170             "#endif\n"
9171             "\n"
9172             "private:\n"
9173             "  int i;\n"
9174             "#ifdef FOO\n"
9175             "\n"
9176             "private:\n"
9177             "#endif\n"
9178             "  int j;\n"
9179             "};\n",
9180             format("struct foo {\n"
9181                    "#ifdef FOO\n"
9182                    "#endif\n"
9183                    "\n"
9184                    "private:\n"
9185                    "  int i;\n"
9186                    "#ifdef FOO\n"
9187                    "\n"
9188                    "private:\n"
9189                    "#endif\n"
9190                    "  int j;\n"
9191                    "};\n",
9192                    Style));
9193   verifyFormat("struct foo {\n"
9194                "#ifdef FOO\n"
9195                "#endif\n"
9196                "private:\n"
9197                "  int i;\n"
9198                "#ifdef FOO\n"
9199                "private:\n"
9200                "#endif\n"
9201                "  int j;\n"
9202                "};\n",
9203                Style);
9204 
9205   FormatStyle NoEmptyLines = getLLVMStyle();
9206   NoEmptyLines.MaxEmptyLinesToKeep = 0;
9207   verifyFormat("struct foo {\n"
9208                "private:\n"
9209                "  void f() {}\n"
9210                "\n"
9211                "private:\n"
9212                "  int i;\n"
9213                "\n"
9214                "public:\n"
9215                "protected:\n"
9216                "  int j;\n"
9217                "};\n",
9218                NoEmptyLines);
9219 
9220   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9221   verifyFormat("struct foo {\n"
9222                "private:\n"
9223                "  void f() {}\n"
9224                "private:\n"
9225                "  int i;\n"
9226                "public:\n"
9227                "protected:\n"
9228                "  int j;\n"
9229                "};\n",
9230                NoEmptyLines);
9231 
9232   NoEmptyLines.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9233   verifyFormat("struct foo {\n"
9234                "private:\n"
9235                "  void f() {}\n"
9236                "\n"
9237                "private:\n"
9238                "  int i;\n"
9239                "\n"
9240                "public:\n"
9241                "\n"
9242                "protected:\n"
9243                "  int j;\n"
9244                "};\n",
9245                NoEmptyLines);
9246 }
9247 
9248 TEST_F(FormatTest, FormatsAfterAccessModifiers) {
9249 
9250   FormatStyle Style = getLLVMStyle();
9251   EXPECT_EQ(Style.EmptyLineAfterAccessModifier, FormatStyle::ELAAMS_Never);
9252   verifyFormat("struct foo {\n"
9253                "private:\n"
9254                "  void f() {}\n"
9255                "\n"
9256                "private:\n"
9257                "  int i;\n"
9258                "\n"
9259                "protected:\n"
9260                "  int j;\n"
9261                "};\n",
9262                Style);
9263 
9264   // Check if lines are removed.
9265   verifyFormat("struct foo {\n"
9266                "private:\n"
9267                "  void f() {}\n"
9268                "\n"
9269                "private:\n"
9270                "  int i;\n"
9271                "\n"
9272                "protected:\n"
9273                "  int j;\n"
9274                "};\n",
9275                "struct foo {\n"
9276                "private:\n"
9277                "\n"
9278                "  void f() {}\n"
9279                "\n"
9280                "private:\n"
9281                "\n"
9282                "  int i;\n"
9283                "\n"
9284                "protected:\n"
9285                "\n"
9286                "  int j;\n"
9287                "};\n",
9288                Style);
9289 
9290   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9291   verifyFormat("struct foo {\n"
9292                "private:\n"
9293                "\n"
9294                "  void f() {}\n"
9295                "\n"
9296                "private:\n"
9297                "\n"
9298                "  int i;\n"
9299                "\n"
9300                "protected:\n"
9301                "\n"
9302                "  int j;\n"
9303                "};\n",
9304                Style);
9305 
9306   // Check if lines are added.
9307   verifyFormat("struct foo {\n"
9308                "private:\n"
9309                "\n"
9310                "  void f() {}\n"
9311                "\n"
9312                "private:\n"
9313                "\n"
9314                "  int i;\n"
9315                "\n"
9316                "protected:\n"
9317                "\n"
9318                "  int j;\n"
9319                "};\n",
9320                "struct foo {\n"
9321                "private:\n"
9322                "  void f() {}\n"
9323                "\n"
9324                "private:\n"
9325                "  int i;\n"
9326                "\n"
9327                "protected:\n"
9328                "  int j;\n"
9329                "};\n",
9330                Style);
9331 
9332   // Leave tests rely on the code layout, test::messUp can not be used.
9333   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9334   Style.MaxEmptyLinesToKeep = 0u;
9335   verifyFormat("struct foo {\n"
9336                "private:\n"
9337                "  void f() {}\n"
9338                "\n"
9339                "private:\n"
9340                "  int i;\n"
9341                "\n"
9342                "protected:\n"
9343                "  int j;\n"
9344                "};\n",
9345                Style);
9346 
9347   // Check if MaxEmptyLinesToKeep is respected.
9348   EXPECT_EQ("struct foo {\n"
9349             "private:\n"
9350             "  void f() {}\n"
9351             "\n"
9352             "private:\n"
9353             "  int i;\n"
9354             "\n"
9355             "protected:\n"
9356             "  int j;\n"
9357             "};\n",
9358             format("struct foo {\n"
9359                    "private:\n"
9360                    "\n\n\n"
9361                    "  void f() {}\n"
9362                    "\n"
9363                    "private:\n"
9364                    "\n\n\n"
9365                    "  int i;\n"
9366                    "\n"
9367                    "protected:\n"
9368                    "\n\n\n"
9369                    "  int j;\n"
9370                    "};\n",
9371                    Style));
9372 
9373   Style.MaxEmptyLinesToKeep = 1u;
9374   EXPECT_EQ("struct foo {\n"
9375             "private:\n"
9376             "\n"
9377             "  void f() {}\n"
9378             "\n"
9379             "private:\n"
9380             "\n"
9381             "  int i;\n"
9382             "\n"
9383             "protected:\n"
9384             "\n"
9385             "  int j;\n"
9386             "};\n",
9387             format("struct foo {\n"
9388                    "private:\n"
9389                    "\n"
9390                    "  void f() {}\n"
9391                    "\n"
9392                    "private:\n"
9393                    "\n"
9394                    "  int i;\n"
9395                    "\n"
9396                    "protected:\n"
9397                    "\n"
9398                    "  int j;\n"
9399                    "};\n",
9400                    Style));
9401   // Check if no lines are kept.
9402   EXPECT_EQ("struct foo {\n"
9403             "private:\n"
9404             "  void f() {}\n"
9405             "\n"
9406             "private:\n"
9407             "  int i;\n"
9408             "\n"
9409             "protected:\n"
9410             "  int j;\n"
9411             "};\n",
9412             format("struct foo {\n"
9413                    "private:\n"
9414                    "  void f() {}\n"
9415                    "\n"
9416                    "private:\n"
9417                    "  int i;\n"
9418                    "\n"
9419                    "protected:\n"
9420                    "  int j;\n"
9421                    "};\n",
9422                    Style));
9423   // Check if MaxEmptyLinesToKeep is respected.
9424   EXPECT_EQ("struct foo {\n"
9425             "private:\n"
9426             "\n"
9427             "  void f() {}\n"
9428             "\n"
9429             "private:\n"
9430             "\n"
9431             "  int i;\n"
9432             "\n"
9433             "protected:\n"
9434             "\n"
9435             "  int j;\n"
9436             "};\n",
9437             format("struct foo {\n"
9438                    "private:\n"
9439                    "\n\n\n"
9440                    "  void f() {}\n"
9441                    "\n"
9442                    "private:\n"
9443                    "\n\n\n"
9444                    "  int i;\n"
9445                    "\n"
9446                    "protected:\n"
9447                    "\n\n\n"
9448                    "  int j;\n"
9449                    "};\n",
9450                    Style));
9451 
9452   Style.MaxEmptyLinesToKeep = 10u;
9453   EXPECT_EQ("struct foo {\n"
9454             "private:\n"
9455             "\n\n\n"
9456             "  void f() {}\n"
9457             "\n"
9458             "private:\n"
9459             "\n\n\n"
9460             "  int i;\n"
9461             "\n"
9462             "protected:\n"
9463             "\n\n\n"
9464             "  int j;\n"
9465             "};\n",
9466             format("struct foo {\n"
9467                    "private:\n"
9468                    "\n\n\n"
9469                    "  void f() {}\n"
9470                    "\n"
9471                    "private:\n"
9472                    "\n\n\n"
9473                    "  int i;\n"
9474                    "\n"
9475                    "protected:\n"
9476                    "\n\n\n"
9477                    "  int j;\n"
9478                    "};\n",
9479                    Style));
9480 
9481   // Test with comments.
9482   Style = getLLVMStyle();
9483   verifyFormat("struct foo {\n"
9484                "private:\n"
9485                "  // comment\n"
9486                "  void f() {}\n"
9487                "\n"
9488                "private: /* comment */\n"
9489                "  int i;\n"
9490                "};\n",
9491                Style);
9492   verifyFormat("struct foo {\n"
9493                "private:\n"
9494                "  // comment\n"
9495                "  void f() {}\n"
9496                "\n"
9497                "private: /* comment */\n"
9498                "  int i;\n"
9499                "};\n",
9500                "struct foo {\n"
9501                "private:\n"
9502                "\n"
9503                "  // comment\n"
9504                "  void f() {}\n"
9505                "\n"
9506                "private: /* comment */\n"
9507                "\n"
9508                "  int i;\n"
9509                "};\n",
9510                Style);
9511 
9512   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9513   verifyFormat("struct foo {\n"
9514                "private:\n"
9515                "\n"
9516                "  // comment\n"
9517                "  void f() {}\n"
9518                "\n"
9519                "private: /* comment */\n"
9520                "\n"
9521                "  int i;\n"
9522                "};\n",
9523                "struct foo {\n"
9524                "private:\n"
9525                "  // comment\n"
9526                "  void f() {}\n"
9527                "\n"
9528                "private: /* comment */\n"
9529                "  int i;\n"
9530                "};\n",
9531                Style);
9532   verifyFormat("struct foo {\n"
9533                "private:\n"
9534                "\n"
9535                "  // comment\n"
9536                "  void f() {}\n"
9537                "\n"
9538                "private: /* comment */\n"
9539                "\n"
9540                "  int i;\n"
9541                "};\n",
9542                Style);
9543 
9544   // Test with preprocessor defines.
9545   Style = getLLVMStyle();
9546   verifyFormat("struct foo {\n"
9547                "private:\n"
9548                "#ifdef FOO\n"
9549                "#endif\n"
9550                "  void f() {}\n"
9551                "};\n",
9552                Style);
9553   verifyFormat("struct foo {\n"
9554                "private:\n"
9555                "#ifdef FOO\n"
9556                "#endif\n"
9557                "  void f() {}\n"
9558                "};\n",
9559                "struct foo {\n"
9560                "private:\n"
9561                "\n"
9562                "#ifdef FOO\n"
9563                "#endif\n"
9564                "  void f() {}\n"
9565                "};\n",
9566                Style);
9567 
9568   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9569   verifyFormat("struct foo {\n"
9570                "private:\n"
9571                "\n"
9572                "#ifdef FOO\n"
9573                "#endif\n"
9574                "  void f() {}\n"
9575                "};\n",
9576                "struct foo {\n"
9577                "private:\n"
9578                "#ifdef FOO\n"
9579                "#endif\n"
9580                "  void f() {}\n"
9581                "};\n",
9582                Style);
9583   verifyFormat("struct foo {\n"
9584                "private:\n"
9585                "\n"
9586                "#ifdef FOO\n"
9587                "#endif\n"
9588                "  void f() {}\n"
9589                "};\n",
9590                Style);
9591 }
9592 
9593 TEST_F(FormatTest, FormatsAfterAndBeforeAccessModifiersInteraction) {
9594   // Combined tests of EmptyLineAfterAccessModifier and
9595   // EmptyLineBeforeAccessModifier.
9596   FormatStyle Style = getLLVMStyle();
9597   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9598   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9599   verifyFormat("struct foo {\n"
9600                "private:\n"
9601                "\n"
9602                "protected:\n"
9603                "};\n",
9604                Style);
9605 
9606   Style.MaxEmptyLinesToKeep = 10u;
9607   // Both remove all new lines.
9608   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9609   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
9610   verifyFormat("struct foo {\n"
9611                "private:\n"
9612                "protected:\n"
9613                "};\n",
9614                "struct foo {\n"
9615                "private:\n"
9616                "\n\n\n"
9617                "protected:\n"
9618                "};\n",
9619                Style);
9620 
9621   // Leave tests rely on the code layout, test::messUp can not be used.
9622   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9623   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9624   Style.MaxEmptyLinesToKeep = 10u;
9625   EXPECT_EQ("struct foo {\n"
9626             "private:\n"
9627             "\n\n\n"
9628             "protected:\n"
9629             "};\n",
9630             format("struct foo {\n"
9631                    "private:\n"
9632                    "\n\n\n"
9633                    "protected:\n"
9634                    "};\n",
9635                    Style));
9636   Style.MaxEmptyLinesToKeep = 3u;
9637   EXPECT_EQ("struct foo {\n"
9638             "private:\n"
9639             "\n\n\n"
9640             "protected:\n"
9641             "};\n",
9642             format("struct foo {\n"
9643                    "private:\n"
9644                    "\n\n\n"
9645                    "protected:\n"
9646                    "};\n",
9647                    Style));
9648   Style.MaxEmptyLinesToKeep = 1u;
9649   EXPECT_EQ("struct foo {\n"
9650             "private:\n"
9651             "\n\n\n"
9652             "protected:\n"
9653             "};\n",
9654             format("struct foo {\n"
9655                    "private:\n"
9656                    "\n\n\n"
9657                    "protected:\n"
9658                    "};\n",
9659                    Style)); // Based on new lines in original document and not
9660                             // on the setting.
9661 
9662   Style.MaxEmptyLinesToKeep = 10u;
9663   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9664   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9665   // Newlines are kept if they are greater than zero,
9666   // test::messUp removes all new lines which changes the logic
9667   EXPECT_EQ("struct foo {\n"
9668             "private:\n"
9669             "\n\n\n"
9670             "protected:\n"
9671             "};\n",
9672             format("struct foo {\n"
9673                    "private:\n"
9674                    "\n\n\n"
9675                    "protected:\n"
9676                    "};\n",
9677                    Style));
9678 
9679   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9680   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9681   // test::messUp removes all new lines which changes the logic
9682   EXPECT_EQ("struct foo {\n"
9683             "private:\n"
9684             "\n\n\n"
9685             "protected:\n"
9686             "};\n",
9687             format("struct foo {\n"
9688                    "private:\n"
9689                    "\n\n\n"
9690                    "protected:\n"
9691                    "};\n",
9692                    Style));
9693 
9694   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Leave;
9695   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
9696   EXPECT_EQ("struct foo {\n"
9697             "private:\n"
9698             "\n\n\n"
9699             "protected:\n"
9700             "};\n",
9701             format("struct foo {\n"
9702                    "private:\n"
9703                    "\n\n\n"
9704                    "protected:\n"
9705                    "};\n",
9706                    Style)); // test::messUp removes all new lines which changes
9707                             // the logic.
9708 
9709   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9710   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9711   verifyFormat("struct foo {\n"
9712                "private:\n"
9713                "protected:\n"
9714                "};\n",
9715                "struct foo {\n"
9716                "private:\n"
9717                "\n\n\n"
9718                "protected:\n"
9719                "};\n",
9720                Style);
9721 
9722   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Always;
9723   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
9724   EXPECT_EQ("struct foo {\n"
9725             "private:\n"
9726             "\n\n\n"
9727             "protected:\n"
9728             "};\n",
9729             format("struct foo {\n"
9730                    "private:\n"
9731                    "\n\n\n"
9732                    "protected:\n"
9733                    "};\n",
9734                    Style)); // test::messUp removes all new lines which changes
9735                             // the logic.
9736 
9737   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_Never;
9738   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9739   verifyFormat("struct foo {\n"
9740                "private:\n"
9741                "protected:\n"
9742                "};\n",
9743                "struct foo {\n"
9744                "private:\n"
9745                "\n\n\n"
9746                "protected:\n"
9747                "};\n",
9748                Style);
9749 
9750   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
9751   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Always;
9752   verifyFormat("struct foo {\n"
9753                "private:\n"
9754                "protected:\n"
9755                "};\n",
9756                "struct foo {\n"
9757                "private:\n"
9758                "\n\n\n"
9759                "protected:\n"
9760                "};\n",
9761                Style);
9762 
9763   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
9764   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Leave;
9765   verifyFormat("struct foo {\n"
9766                "private:\n"
9767                "protected:\n"
9768                "};\n",
9769                "struct foo {\n"
9770                "private:\n"
9771                "\n\n\n"
9772                "protected:\n"
9773                "};\n",
9774                Style);
9775 
9776   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
9777   Style.EmptyLineAfterAccessModifier = FormatStyle::ELAAMS_Never;
9778   verifyFormat("struct foo {\n"
9779                "private:\n"
9780                "protected:\n"
9781                "};\n",
9782                "struct foo {\n"
9783                "private:\n"
9784                "\n\n\n"
9785                "protected:\n"
9786                "};\n",
9787                Style);
9788 }
9789 
9790 TEST_F(FormatTest, FormatsArrays) {
9791   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
9792                "                         [bbbbbbbbbbbbbbbbbbbbbbbbb] = c;");
9793   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaa(aaaaaaaaaaaa)]\n"
9794                "                         [bbbbbbbbbbb(bbbbbbbbbbbb)] = c;");
9795   verifyFormat("if (aaaaaaaaaaaaaaaaaaaaaaaa &&\n"
9796                "    aaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaa][aaaaaaaaaaaaa]) {\n}");
9797   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9798                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
9799   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9800                "    [a][bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = cccccccc;");
9801   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n"
9802                "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]\n"
9803                "    [bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb] = ccccccccccc;");
9804   verifyFormat(
9805       "llvm::outs() << \"aaaaaaaaaaaa: \"\n"
9806       "             << (*aaaaaaaiaaaaaaa)[aaaaaaaaaaaaaaaaaaaaaaaaa]\n"
9807       "                                  [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa];");
9808   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaaaaaaa][a]\n"
9809                "    .aaaaaaaaaaaaaaaaaaaaaa();");
9810 
9811   verifyGoogleFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa<int>\n"
9812                      "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa[aaaaaaaaaaaa];");
9813   verifyFormat(
9814       "aaaaaaaaaaa aaaaaaaaaaaaaaa = aaaaaaaaaaaaaaaaaaaaaaaaaa->aaaaaaaaa[0]\n"
9815       "                                  .aaaaaaa[0]\n"
9816       "                                  .aaaaaaaaaaaaaaaaaaaaaa();");
9817   verifyFormat("a[::b::c];");
9818 
9819   verifyNoCrash("a[,Y?)]", getLLVMStyleWithColumns(10));
9820 
9821   FormatStyle NoColumnLimit = getLLVMStyleWithColumns(0);
9822   verifyFormat("aaaaa[bbbbbb].cccccc()", NoColumnLimit);
9823 }
9824 
9825 TEST_F(FormatTest, LineStartsWithSpecialCharacter) {
9826   verifyFormat("(a)->b();");
9827   verifyFormat("--a;");
9828 }
9829 
9830 TEST_F(FormatTest, HandlesIncludeDirectives) {
9831   verifyFormat("#include <string>\n"
9832                "#include <a/b/c.h>\n"
9833                "#include \"a/b/string\"\n"
9834                "#include \"string.h\"\n"
9835                "#include \"string.h\"\n"
9836                "#include <a-a>\n"
9837                "#include < path with space >\n"
9838                "#include_next <test.h>"
9839                "#include \"abc.h\" // this is included for ABC\n"
9840                "#include \"some long include\" // with a comment\n"
9841                "#include \"some very long include path\"\n"
9842                "#include <some/very/long/include/path>\n",
9843                getLLVMStyleWithColumns(35));
9844   EXPECT_EQ("#include \"a.h\"", format("#include  \"a.h\""));
9845   EXPECT_EQ("#include <a>", format("#include<a>"));
9846 
9847   verifyFormat("#import <string>");
9848   verifyFormat("#import <a/b/c.h>");
9849   verifyFormat("#import \"a/b/string\"");
9850   verifyFormat("#import \"string.h\"");
9851   verifyFormat("#import \"string.h\"");
9852   verifyFormat("#if __has_include(<strstream>)\n"
9853                "#include <strstream>\n"
9854                "#endif");
9855 
9856   verifyFormat("#define MY_IMPORT <a/b>");
9857 
9858   verifyFormat("#if __has_include(<a/b>)");
9859   verifyFormat("#if __has_include_next(<a/b>)");
9860   verifyFormat("#define F __has_include(<a/b>)");
9861   verifyFormat("#define F __has_include_next(<a/b>)");
9862 
9863   // Protocol buffer definition or missing "#".
9864   verifyFormat("import \"aaaaaaaaaaaaaaaaa/aaaaaaaaaaaaaaa\";",
9865                getLLVMStyleWithColumns(30));
9866 
9867   FormatStyle Style = getLLVMStyle();
9868   Style.AlwaysBreakBeforeMultilineStrings = true;
9869   Style.ColumnLimit = 0;
9870   verifyFormat("#import \"abc.h\"", Style);
9871 
9872   // But 'import' might also be a regular C++ namespace.
9873   verifyFormat("import::SomeFunction(aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
9874                "                     aaaaaaaaaaaaaaaaaaaaaaaaaaaaa);");
9875 }
9876 
9877 //===----------------------------------------------------------------------===//
9878 // Error recovery tests.
9879 //===----------------------------------------------------------------------===//
9880 
9881 TEST_F(FormatTest, IncompleteParameterLists) {
9882   FormatStyle NoBinPacking = getLLVMStyle();
9883   NoBinPacking.BinPackParameters = false;
9884   verifyFormat("void aaaaaaaaaaaaaaaaaa(int level,\n"
9885                "                        double *min_x,\n"
9886                "                        double *max_x,\n"
9887                "                        double *min_y,\n"
9888                "                        double *max_y,\n"
9889                "                        double *min_z,\n"
9890                "                        double *max_z, ) {}",
9891                NoBinPacking);
9892 }
9893 
9894 TEST_F(FormatTest, IncorrectCodeTrailingStuff) {
9895   verifyFormat("void f() { return; }\n42");
9896   verifyFormat("void f() {\n"
9897                "  if (0)\n"
9898                "    return;\n"
9899                "}\n"
9900                "42");
9901   verifyFormat("void f() { return }\n42");
9902   verifyFormat("void f() {\n"
9903                "  if (0)\n"
9904                "    return\n"
9905                "}\n"
9906                "42");
9907 }
9908 
9909 TEST_F(FormatTest, IncorrectCodeMissingSemicolon) {
9910   EXPECT_EQ("void f() { return }", format("void  f ( )  {  return  }"));
9911   EXPECT_EQ("void f() {\n"
9912             "  if (a)\n"
9913             "    return\n"
9914             "}",
9915             format("void  f  (  )  {  if  ( a )  return  }"));
9916   EXPECT_EQ("namespace N {\n"
9917             "void f()\n"
9918             "}",
9919             format("namespace  N  {  void f()  }"));
9920   EXPECT_EQ("namespace N {\n"
9921             "void f() {}\n"
9922             "void g()\n"
9923             "} // namespace N",
9924             format("namespace N  { void f( ) { } void g( ) }"));
9925 }
9926 
9927 TEST_F(FormatTest, IndentationWithinColumnLimitNotPossible) {
9928   verifyFormat("int aaaaaaaa =\n"
9929                "    // Overlylongcomment\n"
9930                "    b;",
9931                getLLVMStyleWithColumns(20));
9932   verifyFormat("function(\n"
9933                "    ShortArgument,\n"
9934                "    LoooooooooooongArgument);\n",
9935                getLLVMStyleWithColumns(20));
9936 }
9937 
9938 TEST_F(FormatTest, IncorrectAccessSpecifier) {
9939   verifyFormat("public:");
9940   verifyFormat("class A {\n"
9941                "public\n"
9942                "  void f() {}\n"
9943                "};");
9944   verifyFormat("public\n"
9945                "int qwerty;");
9946   verifyFormat("public\n"
9947                "B {}");
9948   verifyFormat("public\n"
9949                "{}");
9950   verifyFormat("public\n"
9951                "B { int x; }");
9952 }
9953 
9954 TEST_F(FormatTest, IncorrectCodeUnbalancedBraces) {
9955   verifyFormat("{");
9956   verifyFormat("#})");
9957   verifyNoCrash("(/**/[:!] ?[).");
9958 }
9959 
9960 TEST_F(FormatTest, IncorrectUnbalancedBracesInMacrosWithUnicode) {
9961   // Found by oss-fuzz:
9962   // https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=8212
9963   FormatStyle Style = getGoogleStyle(FormatStyle::LK_Cpp);
9964   Style.ColumnLimit = 60;
9965   verifyNoCrash(
9966       "\x23\x47\xff\x20\x28\xff\x3c\xff\x3f\xff\x20\x2f\x7b\x7a\xff\x20"
9967       "\xff\xff\xff\xca\xb5\xff\xff\xff\xff\x3a\x7b\x7d\xff\x20\xff\x20"
9968       "\xff\x74\xff\x20\x7d\x7d\xff\x7b\x3a\xff\x20\x71\xff\x20\xff\x0a",
9969       Style);
9970 }
9971 
9972 TEST_F(FormatTest, IncorrectCodeDoNoWhile) {
9973   verifyFormat("do {\n}");
9974   verifyFormat("do {\n}\n"
9975                "f();");
9976   verifyFormat("do {\n}\n"
9977                "wheeee(fun);");
9978   verifyFormat("do {\n"
9979                "  f();\n"
9980                "}");
9981 }
9982 
9983 TEST_F(FormatTest, IncorrectCodeMissingParens) {
9984   verifyFormat("if {\n  foo;\n  foo();\n}");
9985   verifyFormat("switch {\n  foo;\n  foo();\n}");
9986   verifyIncompleteFormat("for {\n  foo;\n  foo();\n}");
9987   verifyFormat("while {\n  foo;\n  foo();\n}");
9988   verifyFormat("do {\n  foo;\n  foo();\n} while;");
9989 }
9990 
9991 TEST_F(FormatTest, DoesNotTouchUnwrappedLinesWithErrors) {
9992   verifyIncompleteFormat("namespace {\n"
9993                          "class Foo { Foo (\n"
9994                          "};\n"
9995                          "} // namespace");
9996 }
9997 
9998 TEST_F(FormatTest, IncorrectCodeErrorDetection) {
9999   EXPECT_EQ("{\n  {}\n", format("{\n{\n}\n"));
10000   EXPECT_EQ("{\n  {}\n", format("{\n  {\n}\n"));
10001   EXPECT_EQ("{\n  {}\n", format("{\n  {\n  }\n"));
10002   EXPECT_EQ("{\n  {}\n}\n}\n", format("{\n  {\n    }\n  }\n}\n"));
10003 
10004   EXPECT_EQ("{\n"
10005             "  {\n"
10006             "    breakme(\n"
10007             "        qwe);\n"
10008             "  }\n",
10009             format("{\n"
10010                    "    {\n"
10011                    " breakme(qwe);\n"
10012                    "}\n",
10013                    getLLVMStyleWithColumns(10)));
10014 }
10015 
10016 TEST_F(FormatTest, LayoutCallsInsideBraceInitializers) {
10017   verifyFormat("int x = {\n"
10018                "    avariable,\n"
10019                "    b(alongervariable)};",
10020                getLLVMStyleWithColumns(25));
10021 }
10022 
10023 TEST_F(FormatTest, LayoutBraceInitializersInReturnStatement) {
10024   verifyFormat("return (a)(b){1, 2, 3};");
10025 }
10026 
10027 TEST_F(FormatTest, LayoutCxx11BraceInitializers) {
10028   verifyFormat("vector<int> x{1, 2, 3, 4};");
10029   verifyFormat("vector<int> x{\n"
10030                "    1,\n"
10031                "    2,\n"
10032                "    3,\n"
10033                "    4,\n"
10034                "};");
10035   verifyFormat("vector<T> x{{}, {}, {}, {}};");
10036   verifyFormat("f({1, 2});");
10037   verifyFormat("auto v = Foo{-1};");
10038   verifyFormat("f({1, 2}, {{2, 3}, {4, 5}}, c, {d});");
10039   verifyFormat("Class::Class : member{1, 2, 3} {}");
10040   verifyFormat("new vector<int>{1, 2, 3};");
10041   verifyFormat("new int[3]{1, 2, 3};");
10042   verifyFormat("new int{1};");
10043   verifyFormat("return {arg1, arg2};");
10044   verifyFormat("return {arg1, SomeType{parameter}};");
10045   verifyFormat("int count = set<int>{f(), g(), h()}.size();");
10046   verifyFormat("new T{arg1, arg2};");
10047   verifyFormat("f(MyMap[{composite, key}]);");
10048   verifyFormat("class Class {\n"
10049                "  T member = {arg1, arg2};\n"
10050                "};");
10051   verifyFormat("vector<int> foo = {::SomeGlobalFunction()};");
10052   verifyFormat("const struct A a = {.a = 1, .b = 2};");
10053   verifyFormat("const struct A a = {[0] = 1, [1] = 2};");
10054   verifyFormat("static_assert(std::is_integral<int>{} + 0, \"\");");
10055   verifyFormat("int a = std::is_integral<int>{} + 0;");
10056 
10057   verifyFormat("int foo(int i) { return fo1{}(i); }");
10058   verifyFormat("int foo(int i) { return fo1{}(i); }");
10059   verifyFormat("auto i = decltype(x){};");
10060   verifyFormat("auto i = typeof(x){};");
10061   verifyFormat("auto i = _Atomic(x){};");
10062   verifyFormat("std::vector<int> v = {1, 0 /* comment */};");
10063   verifyFormat("Node n{1, Node{1000}, //\n"
10064                "       2};");
10065   verifyFormat("Aaaa aaaaaaa{\n"
10066                "    {\n"
10067                "        aaaa,\n"
10068                "    },\n"
10069                "};");
10070   verifyFormat("class C : public D {\n"
10071                "  SomeClass SC{2};\n"
10072                "};");
10073   verifyFormat("class C : public A {\n"
10074                "  class D : public B {\n"
10075                "    void f() { int i{2}; }\n"
10076                "  };\n"
10077                "};");
10078   verifyFormat("#define A {a, a},");
10079 
10080   // Avoid breaking between equal sign and opening brace
10081   FormatStyle AvoidBreakingFirstArgument = getLLVMStyle();
10082   AvoidBreakingFirstArgument.PenaltyBreakBeforeFirstCallParameter = 200;
10083   verifyFormat("const std::unordered_map<std::string, int> MyHashTable =\n"
10084                "    {{\"aaaaaaaaaaaaaaaaaaaaa\", 0},\n"
10085                "     {\"bbbbbbbbbbbbbbbbbbbbb\", 1},\n"
10086                "     {\"ccccccccccccccccccccc\", 2}};",
10087                AvoidBreakingFirstArgument);
10088 
10089   // Binpacking only if there is no trailing comma
10090   verifyFormat("const Aaaaaa aaaaa = {aaaaaaaaaa, bbbbbbbbbb,\n"
10091                "                      cccccccccc, dddddddddd};",
10092                getLLVMStyleWithColumns(50));
10093   verifyFormat("const Aaaaaa aaaaa = {\n"
10094                "    aaaaaaaaaaa,\n"
10095                "    bbbbbbbbbbb,\n"
10096                "    ccccccccccc,\n"
10097                "    ddddddddddd,\n"
10098                "};",
10099                getLLVMStyleWithColumns(50));
10100 
10101   // Cases where distinguising braced lists and blocks is hard.
10102   verifyFormat("vector<int> v{12} GUARDED_BY(mutex);");
10103   verifyFormat("void f() {\n"
10104                "  return; // comment\n"
10105                "}\n"
10106                "SomeType t;");
10107   verifyFormat("void f() {\n"
10108                "  if (a) {\n"
10109                "    f();\n"
10110                "  }\n"
10111                "}\n"
10112                "SomeType t;");
10113 
10114   // In combination with BinPackArguments = false.
10115   FormatStyle NoBinPacking = getLLVMStyle();
10116   NoBinPacking.BinPackArguments = false;
10117   verifyFormat("const Aaaaaa aaaaa = {aaaaa,\n"
10118                "                      bbbbb,\n"
10119                "                      ccccc,\n"
10120                "                      ddddd,\n"
10121                "                      eeeee,\n"
10122                "                      ffffff,\n"
10123                "                      ggggg,\n"
10124                "                      hhhhhh,\n"
10125                "                      iiiiii,\n"
10126                "                      jjjjjj,\n"
10127                "                      kkkkkk};",
10128                NoBinPacking);
10129   verifyFormat("const Aaaaaa aaaaa = {\n"
10130                "    aaaaa,\n"
10131                "    bbbbb,\n"
10132                "    ccccc,\n"
10133                "    ddddd,\n"
10134                "    eeeee,\n"
10135                "    ffffff,\n"
10136                "    ggggg,\n"
10137                "    hhhhhh,\n"
10138                "    iiiiii,\n"
10139                "    jjjjjj,\n"
10140                "    kkkkkk,\n"
10141                "};",
10142                NoBinPacking);
10143   verifyFormat(
10144       "const Aaaaaa aaaaa = {\n"
10145       "    aaaaa,  bbbbb,  ccccc,  ddddd,  eeeee,  ffffff, ggggg, hhhhhh,\n"
10146       "    iiiiii, jjjjjj, kkkkkk, aaaaa,  bbbbb,  ccccc,  ddddd, eeeee,\n"
10147       "    ffffff, ggggg,  hhhhhh, iiiiii, jjjjjj, kkkkkk,\n"
10148       "};",
10149       NoBinPacking);
10150 
10151   NoBinPacking.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
10152   EXPECT_EQ("static uint8 CddDp83848Reg[] = {\n"
10153             "    CDDDP83848_BMCR_REGISTER,\n"
10154             "    CDDDP83848_BMSR_REGISTER,\n"
10155             "    CDDDP83848_RBR_REGISTER};",
10156             format("static uint8 CddDp83848Reg[] = {CDDDP83848_BMCR_REGISTER,\n"
10157                    "                                CDDDP83848_BMSR_REGISTER,\n"
10158                    "                                CDDDP83848_RBR_REGISTER};",
10159                    NoBinPacking));
10160 
10161   // FIXME: The alignment of these trailing comments might be bad. Then again,
10162   // this might be utterly useless in real code.
10163   verifyFormat("Constructor::Constructor()\n"
10164                "    : some_value{         //\n"
10165                "                 aaaaaaa, //\n"
10166                "                 bbbbbbb} {}");
10167 
10168   // In braced lists, the first comment is always assumed to belong to the
10169   // first element. Thus, it can be moved to the next or previous line as
10170   // appropriate.
10171   EXPECT_EQ("function({// First element:\n"
10172             "          1,\n"
10173             "          // Second element:\n"
10174             "          2});",
10175             format("function({\n"
10176                    "    // First element:\n"
10177                    "    1,\n"
10178                    "    // Second element:\n"
10179                    "    2});"));
10180   EXPECT_EQ("std::vector<int> MyNumbers{\n"
10181             "    // First element:\n"
10182             "    1,\n"
10183             "    // Second element:\n"
10184             "    2};",
10185             format("std::vector<int> MyNumbers{// First element:\n"
10186                    "                           1,\n"
10187                    "                           // Second element:\n"
10188                    "                           2};",
10189                    getLLVMStyleWithColumns(30)));
10190   // A trailing comma should still lead to an enforced line break and no
10191   // binpacking.
10192   EXPECT_EQ("vector<int> SomeVector = {\n"
10193             "    // aaa\n"
10194             "    1,\n"
10195             "    2,\n"
10196             "};",
10197             format("vector<int> SomeVector = { // aaa\n"
10198                    "    1, 2, };"));
10199 
10200   // C++11 brace initializer list l-braces should not be treated any differently
10201   // when breaking before lambda bodies is enabled
10202   FormatStyle BreakBeforeLambdaBody = getLLVMStyle();
10203   BreakBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
10204   BreakBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
10205   BreakBeforeLambdaBody.AlwaysBreakBeforeMultilineStrings = true;
10206   verifyFormat(
10207       "std::runtime_error{\n"
10208       "    \"Long string which will force a break onto the next line...\"};",
10209       BreakBeforeLambdaBody);
10210 
10211   FormatStyle ExtraSpaces = getLLVMStyle();
10212   ExtraSpaces.Cpp11BracedListStyle = false;
10213   ExtraSpaces.ColumnLimit = 75;
10214   verifyFormat("vector<int> x{ 1, 2, 3, 4 };", ExtraSpaces);
10215   verifyFormat("vector<T> x{ {}, {}, {}, {} };", ExtraSpaces);
10216   verifyFormat("f({ 1, 2 });", ExtraSpaces);
10217   verifyFormat("auto v = Foo{ 1 };", ExtraSpaces);
10218   verifyFormat("f({ 1, 2 }, { { 2, 3 }, { 4, 5 } }, c, { d });", ExtraSpaces);
10219   verifyFormat("Class::Class : member{ 1, 2, 3 } {}", ExtraSpaces);
10220   verifyFormat("new vector<int>{ 1, 2, 3 };", ExtraSpaces);
10221   verifyFormat("new int[3]{ 1, 2, 3 };", ExtraSpaces);
10222   verifyFormat("return { arg1, arg2 };", ExtraSpaces);
10223   verifyFormat("return { arg1, SomeType{ parameter } };", ExtraSpaces);
10224   verifyFormat("int count = set<int>{ f(), g(), h() }.size();", ExtraSpaces);
10225   verifyFormat("new T{ arg1, arg2 };", ExtraSpaces);
10226   verifyFormat("f(MyMap[{ composite, key }]);", ExtraSpaces);
10227   verifyFormat("class Class {\n"
10228                "  T member = { arg1, arg2 };\n"
10229                "};",
10230                ExtraSpaces);
10231   verifyFormat(
10232       "foo = aaaaaaaaaaa ? vector<int>{ aaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10233       "                                 aaaaaaaaaaaaaaaaaaaa, aaaaa }\n"
10234       "                  : vector<int>{ bbbbbbbbbbbbbbbbbbbbbbbbbbb,\n"
10235       "                                 bbbbbbbbbbbbbbbbbbbb, bbbbb };",
10236       ExtraSpaces);
10237   verifyFormat("DoSomethingWithVector({} /* No data */);", ExtraSpaces);
10238   verifyFormat("DoSomethingWithVector({ {} /* No data */ }, { { 1, 2 } });",
10239                ExtraSpaces);
10240   verifyFormat(
10241       "someFunction(OtherParam,\n"
10242       "             BracedList{ // comment 1 (Forcing interesting break)\n"
10243       "                         param1, param2,\n"
10244       "                         // comment 2\n"
10245       "                         param3, param4 });",
10246       ExtraSpaces);
10247   verifyFormat(
10248       "std::this_thread::sleep_for(\n"
10249       "    std::chrono::nanoseconds{ std::chrono::seconds{ 1 } } / 5);",
10250       ExtraSpaces);
10251   verifyFormat("std::vector<MyValues> aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa{\n"
10252                "    aaaaaaa,\n"
10253                "    aaaaaaaaaa,\n"
10254                "    aaaaa,\n"
10255                "    aaaaaaaaaaaaaaa,\n"
10256                "    aaa,\n"
10257                "    aaaaaaaaaa,\n"
10258                "    a,\n"
10259                "    aaaaaaaaaaaaaaaaaaaaa,\n"
10260                "    aaaaaaaaaaaa,\n"
10261                "    aaaaaaaaaaaaaaaaaaa + aaaaaaaaaaaaaaaaaaa,\n"
10262                "    aaaaaaa,\n"
10263                "    a};");
10264   verifyFormat("vector<int> foo = { ::SomeGlobalFunction() };", ExtraSpaces);
10265   verifyFormat("const struct A a = { .a = 1, .b = 2 };", ExtraSpaces);
10266   verifyFormat("const struct A a = { [0] = 1, [1] = 2 };", ExtraSpaces);
10267 
10268   // Avoid breaking between initializer/equal sign and opening brace
10269   ExtraSpaces.PenaltyBreakBeforeFirstCallParameter = 200;
10270   verifyFormat("const std::unordered_map<std::string, int> MyHashTable = {\n"
10271                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
10272                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
10273                "  { \"ccccccccccccccccccccc\", 2 }\n"
10274                "};",
10275                ExtraSpaces);
10276   verifyFormat("const std::unordered_map<std::string, int> MyHashTable{\n"
10277                "  { \"aaaaaaaaaaaaaaaaaaaaa\", 0 },\n"
10278                "  { \"bbbbbbbbbbbbbbbbbbbbb\", 1 },\n"
10279                "  { \"ccccccccccccccccccccc\", 2 }\n"
10280                "};",
10281                ExtraSpaces);
10282 
10283   FormatStyle SpaceBeforeBrace = getLLVMStyle();
10284   SpaceBeforeBrace.SpaceBeforeCpp11BracedList = true;
10285   verifyFormat("vector<int> x {1, 2, 3, 4};", SpaceBeforeBrace);
10286   verifyFormat("f({}, {{}, {}}, MyMap[{k, v}]);", SpaceBeforeBrace);
10287 
10288   FormatStyle SpaceBetweenBraces = getLLVMStyle();
10289   SpaceBetweenBraces.SpacesInAngles = true;
10290   SpaceBetweenBraces.SpacesInParentheses = true;
10291   SpaceBetweenBraces.SpacesInSquareBrackets = true;
10292   verifyFormat("vector< int > x{ 1, 2, 3, 4 };", SpaceBetweenBraces);
10293   verifyFormat("f( {}, { {}, {} }, MyMap[ { k, v } ] );", SpaceBetweenBraces);
10294   verifyFormat("vector< int > x{ // comment 1\n"
10295                "                 1, 2, 3, 4 };",
10296                SpaceBetweenBraces);
10297   SpaceBetweenBraces.ColumnLimit = 20;
10298   EXPECT_EQ("vector< int > x{\n"
10299             "    1, 2, 3, 4 };",
10300             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
10301   SpaceBetweenBraces.ColumnLimit = 24;
10302   EXPECT_EQ("vector< int > x{ 1, 2,\n"
10303             "                 3, 4 };",
10304             format("vector<int>x{1,2,3,4};", SpaceBetweenBraces));
10305   EXPECT_EQ("vector< int > x{\n"
10306             "    1,\n"
10307             "    2,\n"
10308             "    3,\n"
10309             "    4,\n"
10310             "};",
10311             format("vector<int>x{1,2,3,4,};", SpaceBetweenBraces));
10312   verifyFormat("vector< int > x{};", SpaceBetweenBraces);
10313   SpaceBetweenBraces.SpaceInEmptyParentheses = true;
10314   verifyFormat("vector< int > x{ };", SpaceBetweenBraces);
10315 }
10316 
10317 TEST_F(FormatTest, FormatSpacesInAngles) {
10318   FormatStyle SpaceInAngles = getLLVMStyle();
10319   SpaceInAngles.SpacesInAngles = true;
10320   verifyFormat("vector< ::std::string > x1;", SpaceInAngles);
10321   verifyFormat("Foo< int, Bar > x2;", SpaceInAngles);
10322   verifyFormat("Foo< ::int, ::Bar > x3;", SpaceInAngles);
10323 
10324   SpaceInAngles.SpacesInAngles = false;
10325   verifyFormat("vector<::std::string> x4;", SpaceInAngles);
10326   verifyFormat("vector<int> x5;", SpaceInAngles);
10327   verifyFormat("Foo<int, Bar> x6;", SpaceInAngles);
10328   verifyFormat("Foo<::int, ::Bar> x7;", SpaceInAngles);
10329 }
10330 
10331 TEST_F(FormatTest, FormatsBracedListsInColumnLayout) {
10332   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10333                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10334                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10335                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10336                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10337                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
10338   verifyFormat("vector<int> x = {1, 22, 333, 4444, 55555, 666666, 7777777, //\n"
10339                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10340                "                 1, 22, 333, 4444, 55555, //\n"
10341                "                 1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10342                "                 1, 22, 333, 4444, 55555, 666666, 7777777};");
10343   verifyFormat(
10344       "vector<int> x = {1,       22, 333, 4444, 55555, 666666, 7777777,\n"
10345       "                 1,       22, 333, 4444, 55555, 666666, 7777777,\n"
10346       "                 1,       22, 333, 4444, 55555, 666666, // comment\n"
10347       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
10348       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
10349       "                 7777777, 1,  22,  333,  4444,  55555,  666666,\n"
10350       "                 7777777};");
10351   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
10352                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
10353                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
10354   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
10355                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
10356                "    // Separating comment.\n"
10357                "    X86::R8, X86::R9, X86::R10, X86::R11, 0};");
10358   verifyFormat("static const uint16_t CallerSavedRegs64Bittttt[] = {\n"
10359                "    // Leading comment\n"
10360                "    X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,\n"
10361                "    X86::R8,  X86::R9,  X86::R10, X86::R11, 0};");
10362   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
10363                "                 1, 1, 1, 1};",
10364                getLLVMStyleWithColumns(39));
10365   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
10366                "                 1, 1, 1, 1};",
10367                getLLVMStyleWithColumns(38));
10368   verifyFormat("vector<int> aaaaaaaaaaaaaaaaaaaaaa = {\n"
10369                "    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};",
10370                getLLVMStyleWithColumns(43));
10371   verifyFormat(
10372       "static unsigned SomeValues[10][3] = {\n"
10373       "    {1, 4, 0},  {4, 9, 0},  {4, 5, 9},  {8, 5, 4}, {1, 8, 4},\n"
10374       "    {10, 1, 6}, {11, 0, 9}, {2, 11, 9}, {5, 2, 9}, {11, 2, 7}};");
10375   verifyFormat("static auto fields = new vector<string>{\n"
10376                "    \"aaaaaaaaaaaaa\",\n"
10377                "    \"aaaaaaaaaaaaa\",\n"
10378                "    \"aaaaaaaaaaaa\",\n"
10379                "    \"aaaaaaaaaaaaaa\",\n"
10380                "    \"aaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
10381                "    \"aaaaaaaaaaaa\",\n"
10382                "    \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\n"
10383                "};");
10384   verifyFormat("vector<int> x = {1, 2, 3, 4, aaaaaaaaaaaaaaaaa, 6};");
10385   verifyFormat("vector<int> x = {1, aaaaaaaaaaaaaaaaaaaaaa,\n"
10386                "                 2, bbbbbbbbbbbbbbbbbbbbbb,\n"
10387                "                 3, cccccccccccccccccccccc};",
10388                getLLVMStyleWithColumns(60));
10389 
10390   // Trailing commas.
10391   verifyFormat("vector<int> x = {\n"
10392                "    1, 1, 1, 1, 1, 1, 1, 1,\n"
10393                "};",
10394                getLLVMStyleWithColumns(39));
10395   verifyFormat("vector<int> x = {\n"
10396                "    1, 1, 1, 1, 1, 1, 1, 1, //\n"
10397                "};",
10398                getLLVMStyleWithColumns(39));
10399   verifyFormat("vector<int> x = {1, 1, 1, 1,\n"
10400                "                 1, 1, 1, 1,\n"
10401                "                 /**/ /**/};",
10402                getLLVMStyleWithColumns(39));
10403 
10404   // Trailing comment in the first line.
10405   verifyFormat("vector<int> iiiiiiiiiiiiiii = {                      //\n"
10406                "    1111111111, 2222222222, 33333333333, 4444444444, //\n"
10407                "    111111111,  222222222,  3333333333,  444444444,  //\n"
10408                "    11111111,   22222222,   333333333,   44444444};");
10409   // Trailing comment in the last line.
10410   verifyFormat("int aaaaa[] = {\n"
10411                "    1, 2, 3, // comment\n"
10412                "    4, 5, 6  // comment\n"
10413                "};");
10414 
10415   // With nested lists, we should either format one item per line or all nested
10416   // lists one on line.
10417   // FIXME: For some nested lists, we can do better.
10418   verifyFormat("return {{aaaaaaaaaaaaaaaaaaaaa},\n"
10419                "        {aaaaaaaaaaaaaaaaaaa},\n"
10420                "        {aaaaaaaaaaaaaaaaaaaaa},\n"
10421                "        {aaaaaaaaaaaaaaaaa}};",
10422                getLLVMStyleWithColumns(60));
10423   verifyFormat(
10424       "SomeStruct my_struct_array = {\n"
10425       "    {aaaaaa, aaaaaaaa, aaaaaaaaaa, aaaaaaaaa, aaaaaaaaa, aaaaaaaaaa,\n"
10426       "     aaaaaaaaaaaaa, aaaaaaa, aaa},\n"
10427       "    {aaa, aaa},\n"
10428       "    {aaa, aaa},\n"
10429       "    {aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaaa, aaa},\n"
10430       "    {aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaa,\n"
10431       "     aaaaaaaaaaaa, a, aaaaaaaaaa, aaaaaaaaa, aaa}};");
10432 
10433   // No column layout should be used here.
10434   verifyFormat("aaaaaaaaaaaaaaa = {aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, 0, 0,\n"
10435                "                   bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb};");
10436 
10437   verifyNoCrash("a<,");
10438 
10439   // No braced initializer here.
10440   verifyFormat("void f() {\n"
10441                "  struct Dummy {};\n"
10442                "  f(v);\n"
10443                "}");
10444 
10445   // Long lists should be formatted in columns even if they are nested.
10446   verifyFormat(
10447       "vector<int> x = function({1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10448       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10449       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10450       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10451       "                          1, 22, 333, 4444, 55555, 666666, 7777777,\n"
10452       "                          1, 22, 333, 4444, 55555, 666666, 7777777});");
10453 
10454   // Allow "single-column" layout even if that violates the column limit. There
10455   // isn't going to be a better way.
10456   verifyFormat("std::vector<int> a = {\n"
10457                "    aaaaaaaa,\n"
10458                "    aaaaaaaa,\n"
10459                "    aaaaaaaa,\n"
10460                "    aaaaaaaa,\n"
10461                "    aaaaaaaaaa,\n"
10462                "    aaaaaaaa,\n"
10463                "    aaaaaaaaaaaaaaaaaaaaaaaaaaa};",
10464                getLLVMStyleWithColumns(30));
10465   verifyFormat("vector<int> aaaa = {\n"
10466                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10467                "    aaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n"
10468                "    aaaaaa.aaaaaaa,\n"
10469                "    aaaaaa.aaaaaaa,\n"
10470                "    aaaaaa.aaaaaaa,\n"
10471                "    aaaaaa.aaaaaaa,\n"
10472                "};");
10473 
10474   // Don't create hanging lists.
10475   verifyFormat("someFunction(Param, {List1, List2,\n"
10476                "                     List3});",
10477                getLLVMStyleWithColumns(35));
10478   verifyFormat("someFunction(Param, Param,\n"
10479                "             {List1, List2,\n"
10480                "              List3});",
10481                getLLVMStyleWithColumns(35));
10482   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaa, {},\n"
10483                "                               aaaaaaaaaaaaaaaaaaaaaaa);");
10484 }
10485 
10486 TEST_F(FormatTest, PullTrivialFunctionDefinitionsIntoSingleLine) {
10487   FormatStyle DoNotMerge = getLLVMStyle();
10488   DoNotMerge.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10489 
10490   verifyFormat("void f() { return 42; }");
10491   verifyFormat("void f() {\n"
10492                "  return 42;\n"
10493                "}",
10494                DoNotMerge);
10495   verifyFormat("void f() {\n"
10496                "  // Comment\n"
10497                "}");
10498   verifyFormat("{\n"
10499                "#error {\n"
10500                "  int a;\n"
10501                "}");
10502   verifyFormat("{\n"
10503                "  int a;\n"
10504                "#error {\n"
10505                "}");
10506   verifyFormat("void f() {} // comment");
10507   verifyFormat("void f() { int a; } // comment");
10508   verifyFormat("void f() {\n"
10509                "} // comment",
10510                DoNotMerge);
10511   verifyFormat("void f() {\n"
10512                "  int a;\n"
10513                "} // comment",
10514                DoNotMerge);
10515   verifyFormat("void f() {\n"
10516                "} // comment",
10517                getLLVMStyleWithColumns(15));
10518 
10519   verifyFormat("void f() { return 42; }", getLLVMStyleWithColumns(23));
10520   verifyFormat("void f() {\n  return 42;\n}", getLLVMStyleWithColumns(22));
10521 
10522   verifyFormat("void f() {}", getLLVMStyleWithColumns(11));
10523   verifyFormat("void f() {\n}", getLLVMStyleWithColumns(10));
10524   verifyFormat("class C {\n"
10525                "  C()\n"
10526                "      : iiiiiiii(nullptr),\n"
10527                "        kkkkkkk(nullptr),\n"
10528                "        mmmmmmm(nullptr),\n"
10529                "        nnnnnnn(nullptr) {}\n"
10530                "};",
10531                getGoogleStyle());
10532 
10533   FormatStyle NoColumnLimit = getLLVMStyle();
10534   NoColumnLimit.ColumnLimit = 0;
10535   EXPECT_EQ("A() : b(0) {}", format("A():b(0){}", NoColumnLimit));
10536   EXPECT_EQ("class C {\n"
10537             "  A() : b(0) {}\n"
10538             "};",
10539             format("class C{A():b(0){}};", NoColumnLimit));
10540   EXPECT_EQ("A()\n"
10541             "    : b(0) {\n"
10542             "}",
10543             format("A()\n:b(0)\n{\n}", NoColumnLimit));
10544 
10545   FormatStyle DoNotMergeNoColumnLimit = NoColumnLimit;
10546   DoNotMergeNoColumnLimit.AllowShortFunctionsOnASingleLine =
10547       FormatStyle::SFS_None;
10548   EXPECT_EQ("A()\n"
10549             "    : b(0) {\n"
10550             "}",
10551             format("A():b(0){}", DoNotMergeNoColumnLimit));
10552   EXPECT_EQ("A()\n"
10553             "    : b(0) {\n"
10554             "}",
10555             format("A()\n:b(0)\n{\n}", DoNotMergeNoColumnLimit));
10556 
10557   verifyFormat("#define A          \\\n"
10558                "  void f() {       \\\n"
10559                "    int i;         \\\n"
10560                "  }",
10561                getLLVMStyleWithColumns(20));
10562   verifyFormat("#define A           \\\n"
10563                "  void f() { int i; }",
10564                getLLVMStyleWithColumns(21));
10565   verifyFormat("#define A            \\\n"
10566                "  void f() {         \\\n"
10567                "    int i;           \\\n"
10568                "  }                  \\\n"
10569                "  int j;",
10570                getLLVMStyleWithColumns(22));
10571   verifyFormat("#define A             \\\n"
10572                "  void f() { int i; } \\\n"
10573                "  int j;",
10574                getLLVMStyleWithColumns(23));
10575 }
10576 
10577 TEST_F(FormatTest, PullEmptyFunctionDefinitionsIntoSingleLine) {
10578   FormatStyle MergeEmptyOnly = getLLVMStyle();
10579   MergeEmptyOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
10580   verifyFormat("class C {\n"
10581                "  int f() {}\n"
10582                "};",
10583                MergeEmptyOnly);
10584   verifyFormat("class C {\n"
10585                "  int f() {\n"
10586                "    return 42;\n"
10587                "  }\n"
10588                "};",
10589                MergeEmptyOnly);
10590   verifyFormat("int f() {}", MergeEmptyOnly);
10591   verifyFormat("int f() {\n"
10592                "  return 42;\n"
10593                "}",
10594                MergeEmptyOnly);
10595 
10596   // Also verify behavior when BraceWrapping.AfterFunction = true
10597   MergeEmptyOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
10598   MergeEmptyOnly.BraceWrapping.AfterFunction = true;
10599   verifyFormat("int f() {}", MergeEmptyOnly);
10600   verifyFormat("class C {\n"
10601                "  int f() {}\n"
10602                "};",
10603                MergeEmptyOnly);
10604 }
10605 
10606 TEST_F(FormatTest, PullInlineFunctionDefinitionsIntoSingleLine) {
10607   FormatStyle MergeInlineOnly = getLLVMStyle();
10608   MergeInlineOnly.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
10609   verifyFormat("class C {\n"
10610                "  int f() { return 42; }\n"
10611                "};",
10612                MergeInlineOnly);
10613   verifyFormat("int f() {\n"
10614                "  return 42;\n"
10615                "}",
10616                MergeInlineOnly);
10617 
10618   // SFS_Inline implies SFS_Empty
10619   verifyFormat("class C {\n"
10620                "  int f() {}\n"
10621                "};",
10622                MergeInlineOnly);
10623   verifyFormat("int f() {}", MergeInlineOnly);
10624 
10625   // Also verify behavior when BraceWrapping.AfterFunction = true
10626   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
10627   MergeInlineOnly.BraceWrapping.AfterFunction = true;
10628   verifyFormat("class C {\n"
10629                "  int f() { return 42; }\n"
10630                "};",
10631                MergeInlineOnly);
10632   verifyFormat("int f()\n"
10633                "{\n"
10634                "  return 42;\n"
10635                "}",
10636                MergeInlineOnly);
10637 
10638   // SFS_Inline implies SFS_Empty
10639   verifyFormat("int f() {}", MergeInlineOnly);
10640   verifyFormat("class C {\n"
10641                "  int f() {}\n"
10642                "};",
10643                MergeInlineOnly);
10644 }
10645 
10646 TEST_F(FormatTest, PullInlineOnlyFunctionDefinitionsIntoSingleLine) {
10647   FormatStyle MergeInlineOnly = getLLVMStyle();
10648   MergeInlineOnly.AllowShortFunctionsOnASingleLine =
10649       FormatStyle::SFS_InlineOnly;
10650   verifyFormat("class C {\n"
10651                "  int f() { return 42; }\n"
10652                "};",
10653                MergeInlineOnly);
10654   verifyFormat("int f() {\n"
10655                "  return 42;\n"
10656                "}",
10657                MergeInlineOnly);
10658 
10659   // SFS_InlineOnly does not imply SFS_Empty
10660   verifyFormat("class C {\n"
10661                "  int f() {}\n"
10662                "};",
10663                MergeInlineOnly);
10664   verifyFormat("int f() {\n"
10665                "}",
10666                MergeInlineOnly);
10667 
10668   // Also verify behavior when BraceWrapping.AfterFunction = true
10669   MergeInlineOnly.BreakBeforeBraces = FormatStyle::BS_Custom;
10670   MergeInlineOnly.BraceWrapping.AfterFunction = true;
10671   verifyFormat("class C {\n"
10672                "  int f() { return 42; }\n"
10673                "};",
10674                MergeInlineOnly);
10675   verifyFormat("int f()\n"
10676                "{\n"
10677                "  return 42;\n"
10678                "}",
10679                MergeInlineOnly);
10680 
10681   // SFS_InlineOnly does not imply SFS_Empty
10682   verifyFormat("int f()\n"
10683                "{\n"
10684                "}",
10685                MergeInlineOnly);
10686   verifyFormat("class C {\n"
10687                "  int f() {}\n"
10688                "};",
10689                MergeInlineOnly);
10690 }
10691 
10692 TEST_F(FormatTest, SplitEmptyFunction) {
10693   FormatStyle Style = getLLVMStyle();
10694   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
10695   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10696   Style.BraceWrapping.AfterFunction = true;
10697   Style.BraceWrapping.SplitEmptyFunction = false;
10698   Style.ColumnLimit = 40;
10699 
10700   verifyFormat("int f()\n"
10701                "{}",
10702                Style);
10703   verifyFormat("int f()\n"
10704                "{\n"
10705                "  return 42;\n"
10706                "}",
10707                Style);
10708   verifyFormat("int f()\n"
10709                "{\n"
10710                "  // some comment\n"
10711                "}",
10712                Style);
10713 
10714   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Empty;
10715   verifyFormat("int f() {}", Style);
10716   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10717                "{}",
10718                Style);
10719   verifyFormat("int f()\n"
10720                "{\n"
10721                "  return 0;\n"
10722                "}",
10723                Style);
10724 
10725   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
10726   verifyFormat("class Foo {\n"
10727                "  int f() {}\n"
10728                "};\n",
10729                Style);
10730   verifyFormat("class Foo {\n"
10731                "  int f() { return 0; }\n"
10732                "};\n",
10733                Style);
10734   verifyFormat("class Foo {\n"
10735                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10736                "  {}\n"
10737                "};\n",
10738                Style);
10739   verifyFormat("class Foo {\n"
10740                "  int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10741                "  {\n"
10742                "    return 0;\n"
10743                "  }\n"
10744                "};\n",
10745                Style);
10746 
10747   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
10748   verifyFormat("int f() {}", Style);
10749   verifyFormat("int f() { return 0; }", Style);
10750   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10751                "{}",
10752                Style);
10753   verifyFormat("int aaaaaaaaaaaaaa(int bbbbbbbbbbbbbb)\n"
10754                "{\n"
10755                "  return 0;\n"
10756                "}",
10757                Style);
10758 }
10759 TEST_F(FormatTest, KeepShortFunctionAfterPPElse) {
10760   FormatStyle Style = getLLVMStyle();
10761   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
10762   verifyFormat("#ifdef A\n"
10763                "int f() {}\n"
10764                "#else\n"
10765                "int g() {}\n"
10766                "#endif",
10767                Style);
10768 }
10769 
10770 TEST_F(FormatTest, SplitEmptyClass) {
10771   FormatStyle Style = getLLVMStyle();
10772   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10773   Style.BraceWrapping.AfterClass = true;
10774   Style.BraceWrapping.SplitEmptyRecord = false;
10775 
10776   verifyFormat("class Foo\n"
10777                "{};",
10778                Style);
10779   verifyFormat("/* something */ class Foo\n"
10780                "{};",
10781                Style);
10782   verifyFormat("template <typename X> class Foo\n"
10783                "{};",
10784                Style);
10785   verifyFormat("class Foo\n"
10786                "{\n"
10787                "  Foo();\n"
10788                "};",
10789                Style);
10790   verifyFormat("typedef class Foo\n"
10791                "{\n"
10792                "} Foo_t;",
10793                Style);
10794 
10795   Style.BraceWrapping.SplitEmptyRecord = true;
10796   Style.BraceWrapping.AfterStruct = true;
10797   verifyFormat("class rep\n"
10798                "{\n"
10799                "};",
10800                Style);
10801   verifyFormat("struct rep\n"
10802                "{\n"
10803                "};",
10804                Style);
10805   verifyFormat("template <typename T> class rep\n"
10806                "{\n"
10807                "};",
10808                Style);
10809   verifyFormat("template <typename T> struct rep\n"
10810                "{\n"
10811                "};",
10812                Style);
10813   verifyFormat("class rep\n"
10814                "{\n"
10815                "  int x;\n"
10816                "};",
10817                Style);
10818   verifyFormat("struct rep\n"
10819                "{\n"
10820                "  int x;\n"
10821                "};",
10822                Style);
10823   verifyFormat("template <typename T> class rep\n"
10824                "{\n"
10825                "  int x;\n"
10826                "};",
10827                Style);
10828   verifyFormat("template <typename T> struct rep\n"
10829                "{\n"
10830                "  int x;\n"
10831                "};",
10832                Style);
10833   verifyFormat("template <typename T> class rep // Foo\n"
10834                "{\n"
10835                "  int x;\n"
10836                "};",
10837                Style);
10838   verifyFormat("template <typename T> struct rep // Bar\n"
10839                "{\n"
10840                "  int x;\n"
10841                "};",
10842                Style);
10843 
10844   verifyFormat("template <typename T> class rep<T>\n"
10845                "{\n"
10846                "  int x;\n"
10847                "};",
10848                Style);
10849 
10850   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
10851                "{\n"
10852                "  int x;\n"
10853                "};",
10854                Style);
10855   verifyFormat("template <typename T> class rep<std::complex<T>>\n"
10856                "{\n"
10857                "};",
10858                Style);
10859 
10860   verifyFormat("#include \"stdint.h\"\n"
10861                "namespace rep {}",
10862                Style);
10863   verifyFormat("#include <stdint.h>\n"
10864                "namespace rep {}",
10865                Style);
10866   verifyFormat("#include <stdint.h>\n"
10867                "namespace rep {}",
10868                "#include <stdint.h>\n"
10869                "namespace rep {\n"
10870                "\n"
10871                "\n"
10872                "}",
10873                Style);
10874 }
10875 
10876 TEST_F(FormatTest, SplitEmptyStruct) {
10877   FormatStyle Style = getLLVMStyle();
10878   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10879   Style.BraceWrapping.AfterStruct = true;
10880   Style.BraceWrapping.SplitEmptyRecord = false;
10881 
10882   verifyFormat("struct Foo\n"
10883                "{};",
10884                Style);
10885   verifyFormat("/* something */ struct Foo\n"
10886                "{};",
10887                Style);
10888   verifyFormat("template <typename X> struct Foo\n"
10889                "{};",
10890                Style);
10891   verifyFormat("struct Foo\n"
10892                "{\n"
10893                "  Foo();\n"
10894                "};",
10895                Style);
10896   verifyFormat("typedef struct Foo\n"
10897                "{\n"
10898                "} Foo_t;",
10899                Style);
10900   // typedef struct Bar {} Bar_t;
10901 }
10902 
10903 TEST_F(FormatTest, SplitEmptyUnion) {
10904   FormatStyle Style = getLLVMStyle();
10905   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10906   Style.BraceWrapping.AfterUnion = true;
10907   Style.BraceWrapping.SplitEmptyRecord = false;
10908 
10909   verifyFormat("union Foo\n"
10910                "{};",
10911                Style);
10912   verifyFormat("/* something */ union Foo\n"
10913                "{};",
10914                Style);
10915   verifyFormat("union Foo\n"
10916                "{\n"
10917                "  A,\n"
10918                "};",
10919                Style);
10920   verifyFormat("typedef union Foo\n"
10921                "{\n"
10922                "} Foo_t;",
10923                Style);
10924 }
10925 
10926 TEST_F(FormatTest, SplitEmptyNamespace) {
10927   FormatStyle Style = getLLVMStyle();
10928   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10929   Style.BraceWrapping.AfterNamespace = true;
10930   Style.BraceWrapping.SplitEmptyNamespace = false;
10931 
10932   verifyFormat("namespace Foo\n"
10933                "{};",
10934                Style);
10935   verifyFormat("/* something */ namespace Foo\n"
10936                "{};",
10937                Style);
10938   verifyFormat("inline namespace Foo\n"
10939                "{};",
10940                Style);
10941   verifyFormat("/* something */ inline namespace Foo\n"
10942                "{};",
10943                Style);
10944   verifyFormat("export namespace Foo\n"
10945                "{};",
10946                Style);
10947   verifyFormat("namespace Foo\n"
10948                "{\n"
10949                "void Bar();\n"
10950                "};",
10951                Style);
10952 }
10953 
10954 TEST_F(FormatTest, NeverMergeShortRecords) {
10955   FormatStyle Style = getLLVMStyle();
10956 
10957   verifyFormat("class Foo {\n"
10958                "  Foo();\n"
10959                "};",
10960                Style);
10961   verifyFormat("typedef class Foo {\n"
10962                "  Foo();\n"
10963                "} Foo_t;",
10964                Style);
10965   verifyFormat("struct Foo {\n"
10966                "  Foo();\n"
10967                "};",
10968                Style);
10969   verifyFormat("typedef struct Foo {\n"
10970                "  Foo();\n"
10971                "} Foo_t;",
10972                Style);
10973   verifyFormat("union Foo {\n"
10974                "  A,\n"
10975                "};",
10976                Style);
10977   verifyFormat("typedef union Foo {\n"
10978                "  A,\n"
10979                "} Foo_t;",
10980                Style);
10981   verifyFormat("namespace Foo {\n"
10982                "void Bar();\n"
10983                "};",
10984                Style);
10985 
10986   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
10987   Style.BraceWrapping.AfterClass = true;
10988   Style.BraceWrapping.AfterStruct = true;
10989   Style.BraceWrapping.AfterUnion = true;
10990   Style.BraceWrapping.AfterNamespace = true;
10991   verifyFormat("class Foo\n"
10992                "{\n"
10993                "  Foo();\n"
10994                "};",
10995                Style);
10996   verifyFormat("typedef class Foo\n"
10997                "{\n"
10998                "  Foo();\n"
10999                "} Foo_t;",
11000                Style);
11001   verifyFormat("struct Foo\n"
11002                "{\n"
11003                "  Foo();\n"
11004                "};",
11005                Style);
11006   verifyFormat("typedef struct Foo\n"
11007                "{\n"
11008                "  Foo();\n"
11009                "} Foo_t;",
11010                Style);
11011   verifyFormat("union Foo\n"
11012                "{\n"
11013                "  A,\n"
11014                "};",
11015                Style);
11016   verifyFormat("typedef union Foo\n"
11017                "{\n"
11018                "  A,\n"
11019                "} Foo_t;",
11020                Style);
11021   verifyFormat("namespace Foo\n"
11022                "{\n"
11023                "void Bar();\n"
11024                "};",
11025                Style);
11026 }
11027 
11028 TEST_F(FormatTest, UnderstandContextOfRecordTypeKeywords) {
11029   // Elaborate type variable declarations.
11030   verifyFormat("struct foo a = {bar};\nint n;");
11031   verifyFormat("class foo a = {bar};\nint n;");
11032   verifyFormat("union foo a = {bar};\nint n;");
11033 
11034   // Elaborate types inside function definitions.
11035   verifyFormat("struct foo f() {}\nint n;");
11036   verifyFormat("class foo f() {}\nint n;");
11037   verifyFormat("union foo f() {}\nint n;");
11038 
11039   // Templates.
11040   verifyFormat("template <class X> void f() {}\nint n;");
11041   verifyFormat("template <struct X> void f() {}\nint n;");
11042   verifyFormat("template <union X> void f() {}\nint n;");
11043 
11044   // Actual definitions...
11045   verifyFormat("struct {\n} n;");
11046   verifyFormat(
11047       "template <template <class T, class Y>, class Z> class X {\n} n;");
11048   verifyFormat("union Z {\n  int n;\n} x;");
11049   verifyFormat("class MACRO Z {\n} n;");
11050   verifyFormat("class MACRO(X) Z {\n} n;");
11051   verifyFormat("class __attribute__(X) Z {\n} n;");
11052   verifyFormat("class __declspec(X) Z {\n} n;");
11053   verifyFormat("class A##B##C {\n} n;");
11054   verifyFormat("class alignas(16) Z {\n} n;");
11055   verifyFormat("class MACRO(X) alignas(16) Z {\n} n;");
11056   verifyFormat("class MACROA MACRO(X) Z {\n} n;");
11057 
11058   // Redefinition from nested context:
11059   verifyFormat("class A::B::C {\n} n;");
11060 
11061   // Template definitions.
11062   verifyFormat(
11063       "template <typename F>\n"
11064       "Matcher(const Matcher<F> &Other,\n"
11065       "        typename enable_if_c<is_base_of<F, T>::value &&\n"
11066       "                             !is_same<F, T>::value>::type * = 0)\n"
11067       "    : Implementation(new ImplicitCastMatcher<F>(Other)) {}");
11068 
11069   // FIXME: This is still incorrectly handled at the formatter side.
11070   verifyFormat("template <> struct X < 15, i<3 && 42 < 50 && 33 < 28> {};");
11071   verifyFormat("int i = SomeFunction(a<b, a> b);");
11072 
11073   // FIXME:
11074   // This now gets parsed incorrectly as class definition.
11075   // verifyFormat("class A<int> f() {\n}\nint n;");
11076 
11077   // Elaborate types where incorrectly parsing the structural element would
11078   // break the indent.
11079   verifyFormat("if (true)\n"
11080                "  class X x;\n"
11081                "else\n"
11082                "  f();\n");
11083 
11084   // This is simply incomplete. Formatting is not important, but must not crash.
11085   verifyFormat("class A:");
11086 }
11087 
11088 TEST_F(FormatTest, DoNotInterfereWithErrorAndWarning) {
11089   EXPECT_EQ("#error Leave     all         white!!!!! space* alone!\n",
11090             format("#error Leave     all         white!!!!! space* alone!\n"));
11091   EXPECT_EQ(
11092       "#warning Leave     all         white!!!!! space* alone!\n",
11093       format("#warning Leave     all         white!!!!! space* alone!\n"));
11094   EXPECT_EQ("#error 1", format("  #  error   1"));
11095   EXPECT_EQ("#warning 1", format("  #  warning 1"));
11096 }
11097 
11098 TEST_F(FormatTest, FormatHashIfExpressions) {
11099   verifyFormat("#if AAAA && BBBB");
11100   verifyFormat("#if (AAAA && BBBB)");
11101   verifyFormat("#elif (AAAA && BBBB)");
11102   // FIXME: Come up with a better indentation for #elif.
11103   verifyFormat(
11104       "#if !defined(AAAAAAA) && (defined CCCCCC || defined DDDDDD) &&  \\\n"
11105       "    defined(BBBBBBBB)\n"
11106       "#elif !defined(AAAAAA) && (defined CCCCC || defined DDDDDD) &&  \\\n"
11107       "    defined(BBBBBBBB)\n"
11108       "#endif",
11109       getLLVMStyleWithColumns(65));
11110 }
11111 
11112 TEST_F(FormatTest, MergeHandlingInTheFaceOfPreprocessorDirectives) {
11113   FormatStyle AllowsMergedIf = getGoogleStyle();
11114   AllowsMergedIf.AllowShortIfStatementsOnASingleLine =
11115       FormatStyle::SIS_WithoutElse;
11116   verifyFormat("void f() { f(); }\n#error E", AllowsMergedIf);
11117   verifyFormat("if (true) return 42;\n#error E", AllowsMergedIf);
11118   verifyFormat("if (true)\n#error E\n  return 42;", AllowsMergedIf);
11119   EXPECT_EQ("if (true) return 42;",
11120             format("if (true)\nreturn 42;", AllowsMergedIf));
11121   FormatStyle ShortMergedIf = AllowsMergedIf;
11122   ShortMergedIf.ColumnLimit = 25;
11123   verifyFormat("#define A \\\n"
11124                "  if (true) return 42;",
11125                ShortMergedIf);
11126   verifyFormat("#define A \\\n"
11127                "  f();    \\\n"
11128                "  if (true)\n"
11129                "#define B",
11130                ShortMergedIf);
11131   verifyFormat("#define A \\\n"
11132                "  f();    \\\n"
11133                "  if (true)\n"
11134                "g();",
11135                ShortMergedIf);
11136   verifyFormat("{\n"
11137                "#ifdef A\n"
11138                "  // Comment\n"
11139                "  if (true) continue;\n"
11140                "#endif\n"
11141                "  // Comment\n"
11142                "  if (true) continue;\n"
11143                "}",
11144                ShortMergedIf);
11145   ShortMergedIf.ColumnLimit = 33;
11146   verifyFormat("#define A \\\n"
11147                "  if constexpr (true) return 42;",
11148                ShortMergedIf);
11149   verifyFormat("#define A \\\n"
11150                "  if CONSTEXPR (true) return 42;",
11151                ShortMergedIf);
11152   ShortMergedIf.ColumnLimit = 29;
11153   verifyFormat("#define A                   \\\n"
11154                "  if (aaaaaaaaaa) return 1; \\\n"
11155                "  return 2;",
11156                ShortMergedIf);
11157   ShortMergedIf.ColumnLimit = 28;
11158   verifyFormat("#define A         \\\n"
11159                "  if (aaaaaaaaaa) \\\n"
11160                "    return 1;     \\\n"
11161                "  return 2;",
11162                ShortMergedIf);
11163   verifyFormat("#define A                \\\n"
11164                "  if constexpr (aaaaaaa) \\\n"
11165                "    return 1;            \\\n"
11166                "  return 2;",
11167                ShortMergedIf);
11168   verifyFormat("#define A                \\\n"
11169                "  if CONSTEXPR (aaaaaaa) \\\n"
11170                "    return 1;            \\\n"
11171                "  return 2;",
11172                ShortMergedIf);
11173 }
11174 
11175 TEST_F(FormatTest, FormatStarDependingOnContext) {
11176   verifyFormat("void f(int *a);");
11177   verifyFormat("void f() { f(fint * b); }");
11178   verifyFormat("class A {\n  void f(int *a);\n};");
11179   verifyFormat("class A {\n  int *a;\n};");
11180   verifyFormat("namespace a {\n"
11181                "namespace b {\n"
11182                "class A {\n"
11183                "  void f() {}\n"
11184                "  int *a;\n"
11185                "};\n"
11186                "} // namespace b\n"
11187                "} // namespace a");
11188 }
11189 
11190 TEST_F(FormatTest, SpecialTokensAtEndOfLine) {
11191   verifyFormat("while");
11192   verifyFormat("operator");
11193 }
11194 
11195 TEST_F(FormatTest, SkipsDeeplyNestedLines) {
11196   // This code would be painfully slow to format if we didn't skip it.
11197   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
11198                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11199                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11200                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11201                    "A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(A(\n"
11202                    "A(1, 1)\n"
11203                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n" // 10x
11204                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11205                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11206                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11207                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11208                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11209                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11210                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11211                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1)\n"
11212                    ", 1), 1), 1), 1), 1), 1), 1), 1), 1), 1);\n");
11213   // Deeply nested part is untouched, rest is formatted.
11214   EXPECT_EQ(std::string("int i;\n") + Code + "int j;\n",
11215             format(std::string("int    i;\n") + Code + "int    j;\n",
11216                    getLLVMStyle(), SC_ExpectIncomplete));
11217 }
11218 
11219 //===----------------------------------------------------------------------===//
11220 // Objective-C tests.
11221 //===----------------------------------------------------------------------===//
11222 
11223 TEST_F(FormatTest, FormatForObjectiveCMethodDecls) {
11224   verifyFormat("- (void)sendAction:(SEL)aSelector to:(BOOL)anObject;");
11225   EXPECT_EQ("- (NSUInteger)indexOfObject:(id)anObject;",
11226             format("-(NSUInteger)indexOfObject:(id)anObject;"));
11227   EXPECT_EQ("- (NSInteger)Mthod1;", format("-(NSInteger)Mthod1;"));
11228   EXPECT_EQ("+ (id)Mthod2;", format("+(id)Mthod2;"));
11229   EXPECT_EQ("- (NSInteger)Method3:(id)anObject;",
11230             format("-(NSInteger)Method3:(id)anObject;"));
11231   EXPECT_EQ("- (NSInteger)Method4:(id)anObject;",
11232             format("-(NSInteger)Method4:(id)anObject;"));
11233   EXPECT_EQ("- (NSInteger)Method5:(id)anObject:(id)AnotherObject;",
11234             format("-(NSInteger)Method5:(id)anObject:(id)AnotherObject;"));
11235   EXPECT_EQ("- (id)Method6:(id)A:(id)B:(id)C:(id)D;",
11236             format("- (id)Method6:(id)A:(id)B:(id)C:(id)D;"));
11237   EXPECT_EQ("- (void)sendAction:(SEL)aSelector to:(id)anObject "
11238             "forAllCells:(BOOL)flag;",
11239             format("- (void)sendAction:(SEL)aSelector to:(id)anObject "
11240                    "forAllCells:(BOOL)flag;"));
11241 
11242   // Very long objectiveC method declaration.
11243   verifyFormat("- (void)aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:\n"
11244                "    (SoooooooooooooooooooooomeType *)bbbbbbbbbb;");
11245   verifyFormat("- (NSUInteger)indexOfObject:(id)anObject\n"
11246                "                    inRange:(NSRange)range\n"
11247                "                   outRange:(NSRange)out_range\n"
11248                "                  outRange1:(NSRange)out_range1\n"
11249                "                  outRange2:(NSRange)out_range2\n"
11250                "                  outRange3:(NSRange)out_range3\n"
11251                "                  outRange4:(NSRange)out_range4\n"
11252                "                  outRange5:(NSRange)out_range5\n"
11253                "                  outRange6:(NSRange)out_range6\n"
11254                "                  outRange7:(NSRange)out_range7\n"
11255                "                  outRange8:(NSRange)out_range8\n"
11256                "                  outRange9:(NSRange)out_range9;");
11257 
11258   // When the function name has to be wrapped.
11259   FormatStyle Style = getLLVMStyle();
11260   // ObjC ignores IndentWrappedFunctionNames when wrapping methods
11261   // and always indents instead.
11262   Style.IndentWrappedFunctionNames = false;
11263   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
11264                "    veryLooooooooooongName:(NSString)aaaaaaaaaaaaaa\n"
11265                "               anotherName:(NSString)bbbbbbbbbbbbbb {\n"
11266                "}",
11267                Style);
11268   Style.IndentWrappedFunctionNames = true;
11269   verifyFormat("- (SomeLooooooooooooooooooooongType *)\n"
11270                "    veryLooooooooooongName:(NSString)cccccccccccccc\n"
11271                "               anotherName:(NSString)dddddddddddddd {\n"
11272                "}",
11273                Style);
11274 
11275   verifyFormat("- (int)sum:(vector<int>)numbers;");
11276   verifyGoogleFormat("- (void)setDelegate:(id<Protocol>)delegate;");
11277   // FIXME: In LLVM style, there should be a space in front of a '<' for ObjC
11278   // protocol lists (but not for template classes):
11279   // verifyFormat("- (void)setDelegate:(id <Protocol>)delegate;");
11280 
11281   verifyFormat("- (int (*)())foo:(int (*)())f;");
11282   verifyGoogleFormat("- (int (*)())foo:(int (*)())foo;");
11283 
11284   // If there's no return type (very rare in practice!), LLVM and Google style
11285   // agree.
11286   verifyFormat("- foo;");
11287   verifyFormat("- foo:(int)f;");
11288   verifyGoogleFormat("- foo:(int)foo;");
11289 }
11290 
11291 TEST_F(FormatTest, BreaksStringLiterals) {
11292   EXPECT_EQ("\"some text \"\n"
11293             "\"other\";",
11294             format("\"some text other\";", getLLVMStyleWithColumns(12)));
11295   EXPECT_EQ("\"some text \"\n"
11296             "\"other\";",
11297             format("\\\n\"some text other\";", getLLVMStyleWithColumns(12)));
11298   EXPECT_EQ(
11299       "#define A  \\\n"
11300       "  \"some \"  \\\n"
11301       "  \"text \"  \\\n"
11302       "  \"other\";",
11303       format("#define A \"some text other\";", getLLVMStyleWithColumns(12)));
11304   EXPECT_EQ(
11305       "#define A  \\\n"
11306       "  \"so \"    \\\n"
11307       "  \"text \"  \\\n"
11308       "  \"other\";",
11309       format("#define A \"so text other\";", getLLVMStyleWithColumns(12)));
11310 
11311   EXPECT_EQ("\"some text\"",
11312             format("\"some text\"", getLLVMStyleWithColumns(1)));
11313   EXPECT_EQ("\"some text\"",
11314             format("\"some text\"", getLLVMStyleWithColumns(11)));
11315   EXPECT_EQ("\"some \"\n"
11316             "\"text\"",
11317             format("\"some text\"", getLLVMStyleWithColumns(10)));
11318   EXPECT_EQ("\"some \"\n"
11319             "\"text\"",
11320             format("\"some text\"", getLLVMStyleWithColumns(7)));
11321   EXPECT_EQ("\"some\"\n"
11322             "\" tex\"\n"
11323             "\"t\"",
11324             format("\"some text\"", getLLVMStyleWithColumns(6)));
11325   EXPECT_EQ("\"some\"\n"
11326             "\" tex\"\n"
11327             "\" and\"",
11328             format("\"some tex and\"", getLLVMStyleWithColumns(6)));
11329   EXPECT_EQ("\"some\"\n"
11330             "\"/tex\"\n"
11331             "\"/and\"",
11332             format("\"some/tex/and\"", getLLVMStyleWithColumns(6)));
11333 
11334   EXPECT_EQ("variable =\n"
11335             "    \"long string \"\n"
11336             "    \"literal\";",
11337             format("variable = \"long string literal\";",
11338                    getLLVMStyleWithColumns(20)));
11339 
11340   EXPECT_EQ("variable = f(\n"
11341             "    \"long string \"\n"
11342             "    \"literal\",\n"
11343             "    short,\n"
11344             "    loooooooooooooooooooong);",
11345             format("variable = f(\"long string literal\", short, "
11346                    "loooooooooooooooooooong);",
11347                    getLLVMStyleWithColumns(20)));
11348 
11349   EXPECT_EQ(
11350       "f(g(\"long string \"\n"
11351       "    \"literal\"),\n"
11352       "  b);",
11353       format("f(g(\"long string literal\"), b);", getLLVMStyleWithColumns(20)));
11354   EXPECT_EQ("f(g(\"long string \"\n"
11355             "    \"literal\",\n"
11356             "    a),\n"
11357             "  b);",
11358             format("f(g(\"long string literal\", a), b);",
11359                    getLLVMStyleWithColumns(20)));
11360   EXPECT_EQ(
11361       "f(\"one two\".split(\n"
11362       "    variable));",
11363       format("f(\"one two\".split(variable));", getLLVMStyleWithColumns(20)));
11364   EXPECT_EQ("f(\"one two three four five six \"\n"
11365             "  \"seven\".split(\n"
11366             "      really_looooong_variable));",
11367             format("f(\"one two three four five six seven\"."
11368                    "split(really_looooong_variable));",
11369                    getLLVMStyleWithColumns(33)));
11370 
11371   EXPECT_EQ("f(\"some \"\n"
11372             "  \"text\",\n"
11373             "  other);",
11374             format("f(\"some text\", other);", getLLVMStyleWithColumns(10)));
11375 
11376   // Only break as a last resort.
11377   verifyFormat(
11378       "aaaaaaaaaaaaaaaaaaaa(\n"
11379       "    aaaaaaaaaaaaaaaaaaaa,\n"
11380       "    aaaaaa(\"aaa aaaaa aaa aaa aaaaa aaa aaaaa aaa aaa aaaaaa\"));");
11381 
11382   EXPECT_EQ("\"splitmea\"\n"
11383             "\"trandomp\"\n"
11384             "\"oint\"",
11385             format("\"splitmeatrandompoint\"", getLLVMStyleWithColumns(10)));
11386 
11387   EXPECT_EQ("\"split/\"\n"
11388             "\"pathat/\"\n"
11389             "\"slashes\"",
11390             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
11391 
11392   EXPECT_EQ("\"split/\"\n"
11393             "\"pathat/\"\n"
11394             "\"slashes\"",
11395             format("\"split/pathat/slashes\"", getLLVMStyleWithColumns(10)));
11396   EXPECT_EQ("\"split at \"\n"
11397             "\"spaces/at/\"\n"
11398             "\"slashes.at.any$\"\n"
11399             "\"non-alphanumeric%\"\n"
11400             "\"1111111111characte\"\n"
11401             "\"rs\"",
11402             format("\"split at "
11403                    "spaces/at/"
11404                    "slashes.at."
11405                    "any$non-"
11406                    "alphanumeric%"
11407                    "1111111111characte"
11408                    "rs\"",
11409                    getLLVMStyleWithColumns(20)));
11410 
11411   // Verify that splitting the strings understands
11412   // Style::AlwaysBreakBeforeMultilineStrings.
11413   EXPECT_EQ("aaaaaaaaaaaa(\n"
11414             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa \"\n"
11415             "    \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\");",
11416             format("aaaaaaaaaaaa(\"aaaaaaaaaaaaaaaaaaaaaaaaaa "
11417                    "aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
11418                    "aaaaaaaaaaaaaaaaaaaaaa\");",
11419                    getGoogleStyle()));
11420   EXPECT_EQ("return \"aaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
11421             "       \"aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaa\";",
11422             format("return \"aaaaaaaaaaaaaaaaaaaaaa "
11423                    "aaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa "
11424                    "aaaaaaaaaaaaaaaaaaaaaa\";",
11425                    getGoogleStyle()));
11426   EXPECT_EQ("llvm::outs() << \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
11427             "                \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
11428             format("llvm::outs() << "
11429                    "\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaa"
11430                    "aaaaaaaaaaaaaaaaaaa\";"));
11431   EXPECT_EQ("ffff(\n"
11432             "    {\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \"\n"
11433             "     \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
11434             format("ffff({\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa "
11435                    "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"});",
11436                    getGoogleStyle()));
11437 
11438   FormatStyle Style = getLLVMStyleWithColumns(12);
11439   Style.BreakStringLiterals = false;
11440   EXPECT_EQ("\"some text other\";", format("\"some text other\";", Style));
11441 
11442   FormatStyle AlignLeft = getLLVMStyleWithColumns(12);
11443   AlignLeft.AlignEscapedNewlines = FormatStyle::ENAS_Left;
11444   EXPECT_EQ("#define A \\\n"
11445             "  \"some \" \\\n"
11446             "  \"text \" \\\n"
11447             "  \"other\";",
11448             format("#define A \"some text other\";", AlignLeft));
11449 }
11450 
11451 TEST_F(FormatTest, BreaksStringLiteralsAtColumnLimit) {
11452   EXPECT_EQ("C a = \"some more \"\n"
11453             "      \"text\";",
11454             format("C a = \"some more text\";", getLLVMStyleWithColumns(18)));
11455 }
11456 
11457 TEST_F(FormatTest, FullyRemoveEmptyLines) {
11458   FormatStyle NoEmptyLines = getLLVMStyleWithColumns(80);
11459   NoEmptyLines.MaxEmptyLinesToKeep = 0;
11460   EXPECT_EQ("int i = a(b());",
11461             format("int i=a(\n\n b(\n\n\n )\n\n);", NoEmptyLines));
11462 }
11463 
11464 TEST_F(FormatTest, BreaksStringLiteralsWithTabs) {
11465   EXPECT_EQ(
11466       "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
11467       "(\n"
11468       "    \"x\t\");",
11469       format("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
11470              "aaaaaaa("
11471              "\"x\t\");"));
11472 }
11473 
11474 TEST_F(FormatTest, BreaksWideAndNSStringLiterals) {
11475   EXPECT_EQ(
11476       "u8\"utf8 string \"\n"
11477       "u8\"literal\";",
11478       format("u8\"utf8 string literal\";", getGoogleStyleWithColumns(16)));
11479   EXPECT_EQ(
11480       "u\"utf16 string \"\n"
11481       "u\"literal\";",
11482       format("u\"utf16 string literal\";", getGoogleStyleWithColumns(16)));
11483   EXPECT_EQ(
11484       "U\"utf32 string \"\n"
11485       "U\"literal\";",
11486       format("U\"utf32 string literal\";", getGoogleStyleWithColumns(16)));
11487   EXPECT_EQ("L\"wide string \"\n"
11488             "L\"literal\";",
11489             format("L\"wide string literal\";", getGoogleStyleWithColumns(16)));
11490   EXPECT_EQ("@\"NSString \"\n"
11491             "@\"literal\";",
11492             format("@\"NSString literal\";", getGoogleStyleWithColumns(19)));
11493   verifyFormat(R"(NSString *s = @"那那那那";)", getLLVMStyleWithColumns(26));
11494 
11495   // This input makes clang-format try to split the incomplete unicode escape
11496   // sequence, which used to lead to a crasher.
11497   verifyNoCrash(
11498       "aaaaaaaaaaaaaaaaaaaa = L\"\\udff\"'; // aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
11499       getLLVMStyleWithColumns(60));
11500 }
11501 
11502 TEST_F(FormatTest, DoesNotBreakRawStringLiterals) {
11503   FormatStyle Style = getGoogleStyleWithColumns(15);
11504   EXPECT_EQ("R\"x(raw literal)x\";", format("R\"x(raw literal)x\";", Style));
11505   EXPECT_EQ("uR\"x(raw literal)x\";", format("uR\"x(raw literal)x\";", Style));
11506   EXPECT_EQ("LR\"x(raw literal)x\";", format("LR\"x(raw literal)x\";", Style));
11507   EXPECT_EQ("UR\"x(raw literal)x\";", format("UR\"x(raw literal)x\";", Style));
11508   EXPECT_EQ("u8R\"x(raw literal)x\";",
11509             format("u8R\"x(raw literal)x\";", Style));
11510 }
11511 
11512 TEST_F(FormatTest, BreaksStringLiteralsWithin_TMacro) {
11513   FormatStyle Style = getLLVMStyleWithColumns(20);
11514   EXPECT_EQ(
11515       "_T(\"aaaaaaaaaaaaaa\")\n"
11516       "_T(\"aaaaaaaaaaaaaa\")\n"
11517       "_T(\"aaaaaaaaaaaa\")",
11518       format("  _T(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\")", Style));
11519   EXPECT_EQ("f(x,\n"
11520             "  _T(\"aaaaaaaaaaaa\")\n"
11521             "  _T(\"aaa\"),\n"
11522             "  z);",
11523             format("f(x, _T(\"aaaaaaaaaaaaaaa\"), z);", Style));
11524 
11525   // FIXME: Handle embedded spaces in one iteration.
11526   //  EXPECT_EQ("_T(\"aaaaaaaaaaaaa\")\n"
11527   //            "_T(\"aaaaaaaaaaaaa\")\n"
11528   //            "_T(\"aaaaaaaaaaaaa\")\n"
11529   //            "_T(\"a\")",
11530   //            format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
11531   //                   getLLVMStyleWithColumns(20)));
11532   EXPECT_EQ(
11533       "_T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )",
11534       format("  _T ( \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\" )", Style));
11535   EXPECT_EQ("f(\n"
11536             "#if !TEST\n"
11537             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
11538             "#endif\n"
11539             ");",
11540             format("f(\n"
11541                    "#if !TEST\n"
11542                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\")\n"
11543                    "#endif\n"
11544                    ");"));
11545   EXPECT_EQ("f(\n"
11546             "\n"
11547             "    _T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));",
11548             format("f(\n"
11549                    "\n"
11550                    "_T(\"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXn\"));"));
11551 }
11552 
11553 TEST_F(FormatTest, BreaksStringLiteralOperands) {
11554   // In a function call with two operands, the second can be broken with no line
11555   // break before it.
11556   EXPECT_EQ(
11557       "func(a, \"long long \"\n"
11558       "        \"long long\");",
11559       format("func(a, \"long long long long\");", getLLVMStyleWithColumns(24)));
11560   // In a function call with three operands, the second must be broken with a
11561   // line break before it.
11562   EXPECT_EQ("func(a,\n"
11563             "     \"long long long \"\n"
11564             "     \"long\",\n"
11565             "     c);",
11566             format("func(a, \"long long long long\", c);",
11567                    getLLVMStyleWithColumns(24)));
11568   // In a function call with three operands, the third must be broken with a
11569   // line break before it.
11570   EXPECT_EQ("func(a, b,\n"
11571             "     \"long long long \"\n"
11572             "     \"long\");",
11573             format("func(a, b, \"long long long long\");",
11574                    getLLVMStyleWithColumns(24)));
11575   // In a function call with three operands, both the second and the third must
11576   // be broken with a line break before them.
11577   EXPECT_EQ("func(a,\n"
11578             "     \"long long long \"\n"
11579             "     \"long\",\n"
11580             "     \"long long long \"\n"
11581             "     \"long\");",
11582             format("func(a, \"long long long long\", \"long long long long\");",
11583                    getLLVMStyleWithColumns(24)));
11584   // In a chain of << with two operands, the second can be broken with no line
11585   // break before it.
11586   EXPECT_EQ("a << \"line line \"\n"
11587             "     \"line\";",
11588             format("a << \"line line line\";", getLLVMStyleWithColumns(20)));
11589   // In a chain of << with three operands, the second can be broken with no line
11590   // break before it.
11591   EXPECT_EQ(
11592       "abcde << \"line \"\n"
11593       "         \"line line\"\n"
11594       "      << c;",
11595       format("abcde << \"line line line\" << c;", getLLVMStyleWithColumns(20)));
11596   // In a chain of << with three operands, the third must be broken with a line
11597   // break before it.
11598   EXPECT_EQ(
11599       "a << b\n"
11600       "  << \"line line \"\n"
11601       "     \"line\";",
11602       format("a << b << \"line line line\";", getLLVMStyleWithColumns(20)));
11603   // In a chain of << with three operands, the second can be broken with no line
11604   // break before it and the third must be broken with a line break before it.
11605   EXPECT_EQ("abcd << \"line line \"\n"
11606             "        \"line\"\n"
11607             "     << \"line line \"\n"
11608             "        \"line\";",
11609             format("abcd << \"line line line\" << \"line line line\";",
11610                    getLLVMStyleWithColumns(20)));
11611   // In a chain of binary operators with two operands, the second can be broken
11612   // with no line break before it.
11613   EXPECT_EQ(
11614       "abcd + \"line line \"\n"
11615       "       \"line line\";",
11616       format("abcd + \"line line line line\";", getLLVMStyleWithColumns(20)));
11617   // In a chain of binary operators with three operands, the second must be
11618   // broken with a line break before it.
11619   EXPECT_EQ("abcd +\n"
11620             "    \"line line \"\n"
11621             "    \"line line\" +\n"
11622             "    e;",
11623             format("abcd + \"line line line line\" + e;",
11624                    getLLVMStyleWithColumns(20)));
11625   // In a function call with two operands, with AlignAfterOpenBracket enabled,
11626   // the first must be broken with a line break before it.
11627   FormatStyle Style = getLLVMStyleWithColumns(25);
11628   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
11629   EXPECT_EQ("someFunction(\n"
11630             "    \"long long long \"\n"
11631             "    \"long\",\n"
11632             "    a);",
11633             format("someFunction(\"long long long long\", a);", Style));
11634 }
11635 
11636 TEST_F(FormatTest, DontSplitStringLiteralsWithEscapedNewlines) {
11637   EXPECT_EQ(
11638       "aaaaaaaaaaa = \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11639       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11640       "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";",
11641       format("aaaaaaaaaaa  =  \"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11642              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\\\n"
11643              "  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\";"));
11644 }
11645 
11646 TEST_F(FormatTest, CountsCharactersInMultilineRawStringLiterals) {
11647   EXPECT_EQ("f(g(R\"x(raw literal)x\", a), b);",
11648             format("f(g(R\"x(raw literal)x\",   a), b);", getGoogleStyle()));
11649   EXPECT_EQ("fffffffffff(g(R\"x(\n"
11650             "multiline raw string literal xxxxxxxxxxxxxx\n"
11651             ")x\",\n"
11652             "              a),\n"
11653             "            b);",
11654             format("fffffffffff(g(R\"x(\n"
11655                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11656                    ")x\", a), b);",
11657                    getGoogleStyleWithColumns(20)));
11658   EXPECT_EQ("fffffffffff(\n"
11659             "    g(R\"x(qqq\n"
11660             "multiline raw string literal xxxxxxxxxxxxxx\n"
11661             ")x\",\n"
11662             "      a),\n"
11663             "    b);",
11664             format("fffffffffff(g(R\"x(qqq\n"
11665                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11666                    ")x\", a), b);",
11667                    getGoogleStyleWithColumns(20)));
11668 
11669   EXPECT_EQ("fffffffffff(R\"x(\n"
11670             "multiline raw string literal xxxxxxxxxxxxxx\n"
11671             ")x\");",
11672             format("fffffffffff(R\"x(\n"
11673                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11674                    ")x\");",
11675                    getGoogleStyleWithColumns(20)));
11676   EXPECT_EQ("fffffffffff(R\"x(\n"
11677             "multiline raw string literal xxxxxxxxxxxxxx\n"
11678             ")x\" + bbbbbb);",
11679             format("fffffffffff(R\"x(\n"
11680                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11681                    ")x\" +   bbbbbb);",
11682                    getGoogleStyleWithColumns(20)));
11683   EXPECT_EQ("fffffffffff(\n"
11684             "    R\"x(\n"
11685             "multiline raw string literal xxxxxxxxxxxxxx\n"
11686             ")x\" +\n"
11687             "    bbbbbb);",
11688             format("fffffffffff(\n"
11689                    " R\"x(\n"
11690                    "multiline raw string literal xxxxxxxxxxxxxx\n"
11691                    ")x\" + bbbbbb);",
11692                    getGoogleStyleWithColumns(20)));
11693   EXPECT_EQ("fffffffffff(R\"(single line raw string)\" + bbbbbb);",
11694             format("fffffffffff(\n"
11695                    " R\"(single line raw string)\" + bbbbbb);"));
11696 }
11697 
11698 TEST_F(FormatTest, SkipsUnknownStringLiterals) {
11699   verifyFormat("string a = \"unterminated;");
11700   EXPECT_EQ("function(\"unterminated,\n"
11701             "         OtherParameter);",
11702             format("function(  \"unterminated,\n"
11703                    "    OtherParameter);"));
11704 }
11705 
11706 TEST_F(FormatTest, DoesNotTryToParseUDLiteralsInPreCpp11Code) {
11707   FormatStyle Style = getLLVMStyle();
11708   Style.Standard = FormatStyle::LS_Cpp03;
11709   EXPECT_EQ("#define x(_a) printf(\"foo\" _a);",
11710             format("#define x(_a) printf(\"foo\"_a);", Style));
11711 }
11712 
11713 TEST_F(FormatTest, CppLexVersion) {
11714   FormatStyle Style = getLLVMStyle();
11715   // Formatting of x * y differs if x is a type.
11716   verifyFormat("void foo() { MACRO(a * b); }", Style);
11717   verifyFormat("void foo() { MACRO(int *b); }", Style);
11718 
11719   // LLVM style uses latest lexer.
11720   verifyFormat("void foo() { MACRO(char8_t *b); }", Style);
11721   Style.Standard = FormatStyle::LS_Cpp17;
11722   // But in c++17, char8_t isn't a keyword.
11723   verifyFormat("void foo() { MACRO(char8_t * b); }", Style);
11724 }
11725 
11726 TEST_F(FormatTest, UnderstandsCpp1y) { verifyFormat("int bi{1'000'000};"); }
11727 
11728 TEST_F(FormatTest, BreakStringLiteralsBeforeUnbreakableTokenSequence) {
11729   EXPECT_EQ("someFunction(\"aaabbbcccd\"\n"
11730             "             \"ddeeefff\");",
11731             format("someFunction(\"aaabbbcccdddeeefff\");",
11732                    getLLVMStyleWithColumns(25)));
11733   EXPECT_EQ("someFunction1234567890(\n"
11734             "    \"aaabbbcccdddeeefff\");",
11735             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
11736                    getLLVMStyleWithColumns(26)));
11737   EXPECT_EQ("someFunction1234567890(\n"
11738             "    \"aaabbbcccdddeeeff\"\n"
11739             "    \"f\");",
11740             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
11741                    getLLVMStyleWithColumns(25)));
11742   EXPECT_EQ("someFunction1234567890(\n"
11743             "    \"aaabbbcccdddeeeff\"\n"
11744             "    \"f\");",
11745             format("someFunction1234567890(\"aaabbbcccdddeeefff\");",
11746                    getLLVMStyleWithColumns(24)));
11747   EXPECT_EQ("someFunction(\n"
11748             "    \"aaabbbcc ddde \"\n"
11749             "    \"efff\");",
11750             format("someFunction(\"aaabbbcc ddde efff\");",
11751                    getLLVMStyleWithColumns(25)));
11752   EXPECT_EQ("someFunction(\"aaabbbccc \"\n"
11753             "             \"ddeeefff\");",
11754             format("someFunction(\"aaabbbccc ddeeefff\");",
11755                    getLLVMStyleWithColumns(25)));
11756   EXPECT_EQ("someFunction1234567890(\n"
11757             "    \"aaabb \"\n"
11758             "    \"cccdddeeefff\");",
11759             format("someFunction1234567890(\"aaabb cccdddeeefff\");",
11760                    getLLVMStyleWithColumns(25)));
11761   EXPECT_EQ("#define A          \\\n"
11762             "  string s =       \\\n"
11763             "      \"123456789\"  \\\n"
11764             "      \"0\";         \\\n"
11765             "  int i;",
11766             format("#define A string s = \"1234567890\"; int i;",
11767                    getLLVMStyleWithColumns(20)));
11768   EXPECT_EQ("someFunction(\n"
11769             "    \"aaabbbcc \"\n"
11770             "    \"dddeeefff\");",
11771             format("someFunction(\"aaabbbcc dddeeefff\");",
11772                    getLLVMStyleWithColumns(25)));
11773 }
11774 
11775 TEST_F(FormatTest, DoNotBreakStringLiteralsInEscapeSequence) {
11776   EXPECT_EQ("\"\\a\"", format("\"\\a\"", getLLVMStyleWithColumns(3)));
11777   EXPECT_EQ("\"\\\"", format("\"\\\"", getLLVMStyleWithColumns(2)));
11778   EXPECT_EQ("\"test\"\n"
11779             "\"\\n\"",
11780             format("\"test\\n\"", getLLVMStyleWithColumns(7)));
11781   EXPECT_EQ("\"tes\\\\\"\n"
11782             "\"n\"",
11783             format("\"tes\\\\n\"", getLLVMStyleWithColumns(7)));
11784   EXPECT_EQ("\"\\\\\\\\\"\n"
11785             "\"\\n\"",
11786             format("\"\\\\\\\\\\n\"", getLLVMStyleWithColumns(7)));
11787   EXPECT_EQ("\"\\uff01\"", format("\"\\uff01\"", getLLVMStyleWithColumns(7)));
11788   EXPECT_EQ("\"\\uff01\"\n"
11789             "\"test\"",
11790             format("\"\\uff01test\"", getLLVMStyleWithColumns(8)));
11791   EXPECT_EQ("\"\\Uff01ff02\"",
11792             format("\"\\Uff01ff02\"", getLLVMStyleWithColumns(11)));
11793   EXPECT_EQ("\"\\x000000000001\"\n"
11794             "\"next\"",
11795             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(16)));
11796   EXPECT_EQ("\"\\x000000000001next\"",
11797             format("\"\\x000000000001next\"", getLLVMStyleWithColumns(15)));
11798   EXPECT_EQ("\"\\x000000000001\"",
11799             format("\"\\x000000000001\"", getLLVMStyleWithColumns(7)));
11800   EXPECT_EQ("\"test\"\n"
11801             "\"\\000000\"\n"
11802             "\"000001\"",
11803             format("\"test\\000000000001\"", getLLVMStyleWithColumns(9)));
11804   EXPECT_EQ("\"test\\000\"\n"
11805             "\"00000000\"\n"
11806             "\"1\"",
11807             format("\"test\\000000000001\"", getLLVMStyleWithColumns(10)));
11808 }
11809 
11810 TEST_F(FormatTest, DoNotCreateUnreasonableUnwrappedLines) {
11811   verifyFormat("void f() {\n"
11812                "  return g() {}\n"
11813                "  void h() {}");
11814   verifyFormat("int a[] = {void forgot_closing_brace(){f();\n"
11815                "g();\n"
11816                "}");
11817 }
11818 
11819 TEST_F(FormatTest, DoNotPrematurelyEndUnwrappedLineForReturnStatements) {
11820   verifyFormat(
11821       "void f() { return C{param1, param2}.SomeCall(param1, param2); }");
11822 }
11823 
11824 TEST_F(FormatTest, FormatsClosingBracesInEmptyNestedBlocks) {
11825   verifyFormat("class X {\n"
11826                "  void f() {\n"
11827                "  }\n"
11828                "};",
11829                getLLVMStyleWithColumns(12));
11830 }
11831 
11832 TEST_F(FormatTest, ConfigurableIndentWidth) {
11833   FormatStyle EightIndent = getLLVMStyleWithColumns(18);
11834   EightIndent.IndentWidth = 8;
11835   EightIndent.ContinuationIndentWidth = 8;
11836   verifyFormat("void f() {\n"
11837                "        someFunction();\n"
11838                "        if (true) {\n"
11839                "                f();\n"
11840                "        }\n"
11841                "}",
11842                EightIndent);
11843   verifyFormat("class X {\n"
11844                "        void f() {\n"
11845                "        }\n"
11846                "};",
11847                EightIndent);
11848   verifyFormat("int x[] = {\n"
11849                "        call(),\n"
11850                "        call()};",
11851                EightIndent);
11852 }
11853 
11854 TEST_F(FormatTest, ConfigurableFunctionDeclarationIndentAfterType) {
11855   verifyFormat("double\n"
11856                "f();",
11857                getLLVMStyleWithColumns(8));
11858 }
11859 
11860 TEST_F(FormatTest, ConfigurableUseOfTab) {
11861   FormatStyle Tab = getLLVMStyleWithColumns(42);
11862   Tab.IndentWidth = 8;
11863   Tab.UseTab = FormatStyle::UT_Always;
11864   Tab.AlignEscapedNewlines = FormatStyle::ENAS_Left;
11865 
11866   EXPECT_EQ("if (aaaaaaaa && // q\n"
11867             "    bb)\t\t// w\n"
11868             "\t;",
11869             format("if (aaaaaaaa &&// q\n"
11870                    "bb)// w\n"
11871                    ";",
11872                    Tab));
11873   EXPECT_EQ("if (aaa && bbb) // w\n"
11874             "\t;",
11875             format("if(aaa&&bbb)// w\n"
11876                    ";",
11877                    Tab));
11878 
11879   verifyFormat("class X {\n"
11880                "\tvoid f() {\n"
11881                "\t\tsomeFunction(parameter1,\n"
11882                "\t\t\t     parameter2);\n"
11883                "\t}\n"
11884                "};",
11885                Tab);
11886   verifyFormat("#define A                        \\\n"
11887                "\tvoid f() {               \\\n"
11888                "\t\tsomeFunction(    \\\n"
11889                "\t\t    parameter1,  \\\n"
11890                "\t\t    parameter2); \\\n"
11891                "\t}",
11892                Tab);
11893   verifyFormat("int a;\t      // x\n"
11894                "int bbbbbbbb; // x\n",
11895                Tab);
11896 
11897   Tab.TabWidth = 4;
11898   Tab.IndentWidth = 8;
11899   verifyFormat("class TabWidth4Indent8 {\n"
11900                "\t\tvoid f() {\n"
11901                "\t\t\t\tsomeFunction(parameter1,\n"
11902                "\t\t\t\t\t\t\t parameter2);\n"
11903                "\t\t}\n"
11904                "};",
11905                Tab);
11906 
11907   Tab.TabWidth = 4;
11908   Tab.IndentWidth = 4;
11909   verifyFormat("class TabWidth4Indent4 {\n"
11910                "\tvoid f() {\n"
11911                "\t\tsomeFunction(parameter1,\n"
11912                "\t\t\t\t\t parameter2);\n"
11913                "\t}\n"
11914                "};",
11915                Tab);
11916 
11917   Tab.TabWidth = 8;
11918   Tab.IndentWidth = 4;
11919   verifyFormat("class TabWidth8Indent4 {\n"
11920                "    void f() {\n"
11921                "\tsomeFunction(parameter1,\n"
11922                "\t\t     parameter2);\n"
11923                "    }\n"
11924                "};",
11925                Tab);
11926 
11927   Tab.TabWidth = 8;
11928   Tab.IndentWidth = 8;
11929   EXPECT_EQ("/*\n"
11930             "\t      a\t\tcomment\n"
11931             "\t      in multiple lines\n"
11932             "       */",
11933             format("   /*\t \t \n"
11934                    " \t \t a\t\tcomment\t \t\n"
11935                    " \t \t in multiple lines\t\n"
11936                    " \t  */",
11937                    Tab));
11938 
11939   Tab.UseTab = FormatStyle::UT_ForIndentation;
11940   verifyFormat("{\n"
11941                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11942                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11943                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11944                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11945                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11946                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
11947                "};",
11948                Tab);
11949   verifyFormat("enum AA {\n"
11950                "\ta1, // Force multiple lines\n"
11951                "\ta2,\n"
11952                "\ta3\n"
11953                "};",
11954                Tab);
11955   EXPECT_EQ("if (aaaaaaaa && // q\n"
11956             "    bb)         // w\n"
11957             "\t;",
11958             format("if (aaaaaaaa &&// q\n"
11959                    "bb)// w\n"
11960                    ";",
11961                    Tab));
11962   verifyFormat("class X {\n"
11963                "\tvoid f() {\n"
11964                "\t\tsomeFunction(parameter1,\n"
11965                "\t\t             parameter2);\n"
11966                "\t}\n"
11967                "};",
11968                Tab);
11969   verifyFormat("{\n"
11970                "\tQ(\n"
11971                "\t    {\n"
11972                "\t\t    int a;\n"
11973                "\t\t    someFunction(aaaaaaaa,\n"
11974                "\t\t                 bbbbbbb);\n"
11975                "\t    },\n"
11976                "\t    p);\n"
11977                "}",
11978                Tab);
11979   EXPECT_EQ("{\n"
11980             "\t/* aaaa\n"
11981             "\t   bbbb */\n"
11982             "}",
11983             format("{\n"
11984                    "/* aaaa\n"
11985                    "   bbbb */\n"
11986                    "}",
11987                    Tab));
11988   EXPECT_EQ("{\n"
11989             "\t/*\n"
11990             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
11991             "\t  bbbbbbbbbbbbb\n"
11992             "\t*/\n"
11993             "}",
11994             format("{\n"
11995                    "/*\n"
11996                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
11997                    "*/\n"
11998                    "}",
11999                    Tab));
12000   EXPECT_EQ("{\n"
12001             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12002             "\t// bbbbbbbbbbbbb\n"
12003             "}",
12004             format("{\n"
12005                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12006                    "}",
12007                    Tab));
12008   EXPECT_EQ("{\n"
12009             "\t/*\n"
12010             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12011             "\t  bbbbbbbbbbbbb\n"
12012             "\t*/\n"
12013             "}",
12014             format("{\n"
12015                    "\t/*\n"
12016                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12017                    "\t*/\n"
12018                    "}",
12019                    Tab));
12020   EXPECT_EQ("{\n"
12021             "\t/*\n"
12022             "\n"
12023             "\t*/\n"
12024             "}",
12025             format("{\n"
12026                    "\t/*\n"
12027                    "\n"
12028                    "\t*/\n"
12029                    "}",
12030                    Tab));
12031   EXPECT_EQ("{\n"
12032             "\t/*\n"
12033             " asdf\n"
12034             "\t*/\n"
12035             "}",
12036             format("{\n"
12037                    "\t/*\n"
12038                    " asdf\n"
12039                    "\t*/\n"
12040                    "}",
12041                    Tab));
12042 
12043   Tab.UseTab = FormatStyle::UT_Never;
12044   EXPECT_EQ("/*\n"
12045             "              a\t\tcomment\n"
12046             "              in multiple lines\n"
12047             "       */",
12048             format("   /*\t \t \n"
12049                    " \t \t a\t\tcomment\t \t\n"
12050                    " \t \t in multiple lines\t\n"
12051                    " \t  */",
12052                    Tab));
12053   EXPECT_EQ("/* some\n"
12054             "   comment */",
12055             format(" \t \t /* some\n"
12056                    " \t \t    comment */",
12057                    Tab));
12058   EXPECT_EQ("int a; /* some\n"
12059             "   comment */",
12060             format(" \t \t int a; /* some\n"
12061                    " \t \t    comment */",
12062                    Tab));
12063 
12064   EXPECT_EQ("int a; /* some\n"
12065             "comment */",
12066             format(" \t \t int\ta; /* some\n"
12067                    " \t \t    comment */",
12068                    Tab));
12069   EXPECT_EQ("f(\"\t\t\"); /* some\n"
12070             "    comment */",
12071             format(" \t \t f(\"\t\t\"); /* some\n"
12072                    " \t \t    comment */",
12073                    Tab));
12074   EXPECT_EQ("{\n"
12075             "        /*\n"
12076             "         * Comment\n"
12077             "         */\n"
12078             "        int i;\n"
12079             "}",
12080             format("{\n"
12081                    "\t/*\n"
12082                    "\t * Comment\n"
12083                    "\t */\n"
12084                    "\t int i;\n"
12085                    "}",
12086                    Tab));
12087 
12088   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
12089   Tab.TabWidth = 8;
12090   Tab.IndentWidth = 8;
12091   EXPECT_EQ("if (aaaaaaaa && // q\n"
12092             "    bb)         // w\n"
12093             "\t;",
12094             format("if (aaaaaaaa &&// q\n"
12095                    "bb)// w\n"
12096                    ";",
12097                    Tab));
12098   EXPECT_EQ("if (aaa && bbb) // w\n"
12099             "\t;",
12100             format("if(aaa&&bbb)// w\n"
12101                    ";",
12102                    Tab));
12103   verifyFormat("class X {\n"
12104                "\tvoid f() {\n"
12105                "\t\tsomeFunction(parameter1,\n"
12106                "\t\t\t     parameter2);\n"
12107                "\t}\n"
12108                "};",
12109                Tab);
12110   verifyFormat("#define A                        \\\n"
12111                "\tvoid f() {               \\\n"
12112                "\t\tsomeFunction(    \\\n"
12113                "\t\t    parameter1,  \\\n"
12114                "\t\t    parameter2); \\\n"
12115                "\t}",
12116                Tab);
12117   Tab.TabWidth = 4;
12118   Tab.IndentWidth = 8;
12119   verifyFormat("class TabWidth4Indent8 {\n"
12120                "\t\tvoid f() {\n"
12121                "\t\t\t\tsomeFunction(parameter1,\n"
12122                "\t\t\t\t\t\t\t parameter2);\n"
12123                "\t\t}\n"
12124                "};",
12125                Tab);
12126   Tab.TabWidth = 4;
12127   Tab.IndentWidth = 4;
12128   verifyFormat("class TabWidth4Indent4 {\n"
12129                "\tvoid f() {\n"
12130                "\t\tsomeFunction(parameter1,\n"
12131                "\t\t\t\t\t parameter2);\n"
12132                "\t}\n"
12133                "};",
12134                Tab);
12135   Tab.TabWidth = 8;
12136   Tab.IndentWidth = 4;
12137   verifyFormat("class TabWidth8Indent4 {\n"
12138                "    void f() {\n"
12139                "\tsomeFunction(parameter1,\n"
12140                "\t\t     parameter2);\n"
12141                "    }\n"
12142                "};",
12143                Tab);
12144   Tab.TabWidth = 8;
12145   Tab.IndentWidth = 8;
12146   EXPECT_EQ("/*\n"
12147             "\t      a\t\tcomment\n"
12148             "\t      in multiple lines\n"
12149             "       */",
12150             format("   /*\t \t \n"
12151                    " \t \t a\t\tcomment\t \t\n"
12152                    " \t \t in multiple lines\t\n"
12153                    " \t  */",
12154                    Tab));
12155   verifyFormat("{\n"
12156                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12157                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12158                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12159                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12160                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12161                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12162                "};",
12163                Tab);
12164   verifyFormat("enum AA {\n"
12165                "\ta1, // Force multiple lines\n"
12166                "\ta2,\n"
12167                "\ta3\n"
12168                "};",
12169                Tab);
12170   EXPECT_EQ("if (aaaaaaaa && // q\n"
12171             "    bb)         // w\n"
12172             "\t;",
12173             format("if (aaaaaaaa &&// q\n"
12174                    "bb)// w\n"
12175                    ";",
12176                    Tab));
12177   verifyFormat("class X {\n"
12178                "\tvoid f() {\n"
12179                "\t\tsomeFunction(parameter1,\n"
12180                "\t\t\t     parameter2);\n"
12181                "\t}\n"
12182                "};",
12183                Tab);
12184   verifyFormat("{\n"
12185                "\tQ(\n"
12186                "\t    {\n"
12187                "\t\t    int a;\n"
12188                "\t\t    someFunction(aaaaaaaa,\n"
12189                "\t\t\t\t bbbbbbb);\n"
12190                "\t    },\n"
12191                "\t    p);\n"
12192                "}",
12193                Tab);
12194   EXPECT_EQ("{\n"
12195             "\t/* aaaa\n"
12196             "\t   bbbb */\n"
12197             "}",
12198             format("{\n"
12199                    "/* aaaa\n"
12200                    "   bbbb */\n"
12201                    "}",
12202                    Tab));
12203   EXPECT_EQ("{\n"
12204             "\t/*\n"
12205             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12206             "\t  bbbbbbbbbbbbb\n"
12207             "\t*/\n"
12208             "}",
12209             format("{\n"
12210                    "/*\n"
12211                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12212                    "*/\n"
12213                    "}",
12214                    Tab));
12215   EXPECT_EQ("{\n"
12216             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12217             "\t// bbbbbbbbbbbbb\n"
12218             "}",
12219             format("{\n"
12220                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12221                    "}",
12222                    Tab));
12223   EXPECT_EQ("{\n"
12224             "\t/*\n"
12225             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12226             "\t  bbbbbbbbbbbbb\n"
12227             "\t*/\n"
12228             "}",
12229             format("{\n"
12230                    "\t/*\n"
12231                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12232                    "\t*/\n"
12233                    "}",
12234                    Tab));
12235   EXPECT_EQ("{\n"
12236             "\t/*\n"
12237             "\n"
12238             "\t*/\n"
12239             "}",
12240             format("{\n"
12241                    "\t/*\n"
12242                    "\n"
12243                    "\t*/\n"
12244                    "}",
12245                    Tab));
12246   EXPECT_EQ("{\n"
12247             "\t/*\n"
12248             " asdf\n"
12249             "\t*/\n"
12250             "}",
12251             format("{\n"
12252                    "\t/*\n"
12253                    " asdf\n"
12254                    "\t*/\n"
12255                    "}",
12256                    Tab));
12257   EXPECT_EQ("/* some\n"
12258             "   comment */",
12259             format(" \t \t /* some\n"
12260                    " \t \t    comment */",
12261                    Tab));
12262   EXPECT_EQ("int a; /* some\n"
12263             "   comment */",
12264             format(" \t \t int a; /* some\n"
12265                    " \t \t    comment */",
12266                    Tab));
12267   EXPECT_EQ("int a; /* some\n"
12268             "comment */",
12269             format(" \t \t int\ta; /* some\n"
12270                    " \t \t    comment */",
12271                    Tab));
12272   EXPECT_EQ("f(\"\t\t\"); /* some\n"
12273             "    comment */",
12274             format(" \t \t f(\"\t\t\"); /* some\n"
12275                    " \t \t    comment */",
12276                    Tab));
12277   EXPECT_EQ("{\n"
12278             "\t/*\n"
12279             "\t * Comment\n"
12280             "\t */\n"
12281             "\tint i;\n"
12282             "}",
12283             format("{\n"
12284                    "\t/*\n"
12285                    "\t * Comment\n"
12286                    "\t */\n"
12287                    "\t int i;\n"
12288                    "}",
12289                    Tab));
12290   Tab.TabWidth = 2;
12291   Tab.IndentWidth = 2;
12292   EXPECT_EQ("{\n"
12293             "\t/* aaaa\n"
12294             "\t\t bbbb */\n"
12295             "}",
12296             format("{\n"
12297                    "/* aaaa\n"
12298                    "\t bbbb */\n"
12299                    "}",
12300                    Tab));
12301   EXPECT_EQ("{\n"
12302             "\t/*\n"
12303             "\t\taaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12304             "\t\tbbbbbbbbbbbbb\n"
12305             "\t*/\n"
12306             "}",
12307             format("{\n"
12308                    "/*\n"
12309                    "\taaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12310                    "*/\n"
12311                    "}",
12312                    Tab));
12313   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
12314   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
12315   Tab.TabWidth = 4;
12316   Tab.IndentWidth = 4;
12317   verifyFormat("class Assign {\n"
12318                "\tvoid f() {\n"
12319                "\t\tint         x      = 123;\n"
12320                "\t\tint         random = 4;\n"
12321                "\t\tstd::string alphabet =\n"
12322                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
12323                "\t}\n"
12324                "};",
12325                Tab);
12326 
12327   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
12328   Tab.TabWidth = 8;
12329   Tab.IndentWidth = 8;
12330   EXPECT_EQ("if (aaaaaaaa && // q\n"
12331             "    bb)         // w\n"
12332             "\t;",
12333             format("if (aaaaaaaa &&// q\n"
12334                    "bb)// w\n"
12335                    ";",
12336                    Tab));
12337   EXPECT_EQ("if (aaa && bbb) // w\n"
12338             "\t;",
12339             format("if(aaa&&bbb)// w\n"
12340                    ";",
12341                    Tab));
12342   verifyFormat("class X {\n"
12343                "\tvoid f() {\n"
12344                "\t\tsomeFunction(parameter1,\n"
12345                "\t\t             parameter2);\n"
12346                "\t}\n"
12347                "};",
12348                Tab);
12349   verifyFormat("#define A                        \\\n"
12350                "\tvoid f() {               \\\n"
12351                "\t\tsomeFunction(    \\\n"
12352                "\t\t    parameter1,  \\\n"
12353                "\t\t    parameter2); \\\n"
12354                "\t}",
12355                Tab);
12356   Tab.TabWidth = 4;
12357   Tab.IndentWidth = 8;
12358   verifyFormat("class TabWidth4Indent8 {\n"
12359                "\t\tvoid f() {\n"
12360                "\t\t\t\tsomeFunction(parameter1,\n"
12361                "\t\t\t\t             parameter2);\n"
12362                "\t\t}\n"
12363                "};",
12364                Tab);
12365   Tab.TabWidth = 4;
12366   Tab.IndentWidth = 4;
12367   verifyFormat("class TabWidth4Indent4 {\n"
12368                "\tvoid f() {\n"
12369                "\t\tsomeFunction(parameter1,\n"
12370                "\t\t             parameter2);\n"
12371                "\t}\n"
12372                "};",
12373                Tab);
12374   Tab.TabWidth = 8;
12375   Tab.IndentWidth = 4;
12376   verifyFormat("class TabWidth8Indent4 {\n"
12377                "    void f() {\n"
12378                "\tsomeFunction(parameter1,\n"
12379                "\t             parameter2);\n"
12380                "    }\n"
12381                "};",
12382                Tab);
12383   Tab.TabWidth = 8;
12384   Tab.IndentWidth = 8;
12385   EXPECT_EQ("/*\n"
12386             "              a\t\tcomment\n"
12387             "              in multiple lines\n"
12388             "       */",
12389             format("   /*\t \t \n"
12390                    " \t \t a\t\tcomment\t \t\n"
12391                    " \t \t in multiple lines\t\n"
12392                    " \t  */",
12393                    Tab));
12394   verifyFormat("{\n"
12395                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12396                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12397                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12398                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12399                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12400                "\taaaaaaaaaaaaaaaaaaaaaaaaaaaa();\n"
12401                "};",
12402                Tab);
12403   verifyFormat("enum AA {\n"
12404                "\ta1, // Force multiple lines\n"
12405                "\ta2,\n"
12406                "\ta3\n"
12407                "};",
12408                Tab);
12409   EXPECT_EQ("if (aaaaaaaa && // q\n"
12410             "    bb)         // w\n"
12411             "\t;",
12412             format("if (aaaaaaaa &&// q\n"
12413                    "bb)// w\n"
12414                    ";",
12415                    Tab));
12416   verifyFormat("class X {\n"
12417                "\tvoid f() {\n"
12418                "\t\tsomeFunction(parameter1,\n"
12419                "\t\t             parameter2);\n"
12420                "\t}\n"
12421                "};",
12422                Tab);
12423   verifyFormat("{\n"
12424                "\tQ(\n"
12425                "\t    {\n"
12426                "\t\t    int a;\n"
12427                "\t\t    someFunction(aaaaaaaa,\n"
12428                "\t\t                 bbbbbbb);\n"
12429                "\t    },\n"
12430                "\t    p);\n"
12431                "}",
12432                Tab);
12433   EXPECT_EQ("{\n"
12434             "\t/* aaaa\n"
12435             "\t   bbbb */\n"
12436             "}",
12437             format("{\n"
12438                    "/* aaaa\n"
12439                    "   bbbb */\n"
12440                    "}",
12441                    Tab));
12442   EXPECT_EQ("{\n"
12443             "\t/*\n"
12444             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12445             "\t  bbbbbbbbbbbbb\n"
12446             "\t*/\n"
12447             "}",
12448             format("{\n"
12449                    "/*\n"
12450                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12451                    "*/\n"
12452                    "}",
12453                    Tab));
12454   EXPECT_EQ("{\n"
12455             "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12456             "\t// bbbbbbbbbbbbb\n"
12457             "}",
12458             format("{\n"
12459                    "\t// aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12460                    "}",
12461                    Tab));
12462   EXPECT_EQ("{\n"
12463             "\t/*\n"
12464             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12465             "\t  bbbbbbbbbbbbb\n"
12466             "\t*/\n"
12467             "}",
12468             format("{\n"
12469                    "\t/*\n"
12470                    "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12471                    "\t*/\n"
12472                    "}",
12473                    Tab));
12474   EXPECT_EQ("{\n"
12475             "\t/*\n"
12476             "\n"
12477             "\t*/\n"
12478             "}",
12479             format("{\n"
12480                    "\t/*\n"
12481                    "\n"
12482                    "\t*/\n"
12483                    "}",
12484                    Tab));
12485   EXPECT_EQ("{\n"
12486             "\t/*\n"
12487             " asdf\n"
12488             "\t*/\n"
12489             "}",
12490             format("{\n"
12491                    "\t/*\n"
12492                    " asdf\n"
12493                    "\t*/\n"
12494                    "}",
12495                    Tab));
12496   EXPECT_EQ("/* some\n"
12497             "   comment */",
12498             format(" \t \t /* some\n"
12499                    " \t \t    comment */",
12500                    Tab));
12501   EXPECT_EQ("int a; /* some\n"
12502             "   comment */",
12503             format(" \t \t int a; /* some\n"
12504                    " \t \t    comment */",
12505                    Tab));
12506   EXPECT_EQ("int a; /* some\n"
12507             "comment */",
12508             format(" \t \t int\ta; /* some\n"
12509                    " \t \t    comment */",
12510                    Tab));
12511   EXPECT_EQ("f(\"\t\t\"); /* some\n"
12512             "    comment */",
12513             format(" \t \t f(\"\t\t\"); /* some\n"
12514                    " \t \t    comment */",
12515                    Tab));
12516   EXPECT_EQ("{\n"
12517             "\t/*\n"
12518             "\t * Comment\n"
12519             "\t */\n"
12520             "\tint i;\n"
12521             "}",
12522             format("{\n"
12523                    "\t/*\n"
12524                    "\t * Comment\n"
12525                    "\t */\n"
12526                    "\t int i;\n"
12527                    "}",
12528                    Tab));
12529   Tab.TabWidth = 2;
12530   Tab.IndentWidth = 2;
12531   EXPECT_EQ("{\n"
12532             "\t/* aaaa\n"
12533             "\t   bbbb */\n"
12534             "}",
12535             format("{\n"
12536                    "/* aaaa\n"
12537                    "   bbbb */\n"
12538                    "}",
12539                    Tab));
12540   EXPECT_EQ("{\n"
12541             "\t/*\n"
12542             "\t  aaaaaaaaaaaaaaaaaaaaaaaaaa\n"
12543             "\t  bbbbbbbbbbbbb\n"
12544             "\t*/\n"
12545             "}",
12546             format("{\n"
12547                    "/*\n"
12548                    "  aaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbb\n"
12549                    "*/\n"
12550                    "}",
12551                    Tab));
12552   Tab.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
12553   Tab.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
12554   Tab.TabWidth = 4;
12555   Tab.IndentWidth = 4;
12556   verifyFormat("class Assign {\n"
12557                "\tvoid f() {\n"
12558                "\t\tint         x      = 123;\n"
12559                "\t\tint         random = 4;\n"
12560                "\t\tstd::string alphabet =\n"
12561                "\t\t\t\"abcdefghijklmnopqrstuvwxyz\";\n"
12562                "\t}\n"
12563                "};",
12564                Tab);
12565   Tab.AlignOperands = FormatStyle::OAS_Align;
12566   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb +\n"
12567                "                 cccccccccccccccccccc;",
12568                Tab);
12569   // no alignment
12570   verifyFormat("int aaaaaaaaaa =\n"
12571                "\tbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;",
12572                Tab);
12573   verifyFormat("return aaaaaaaaaaaaaaaa ? 111111111111111\n"
12574                "       : bbbbbbbbbbbbbb ? 222222222222222\n"
12575                "                        : 333333333333333;",
12576                Tab);
12577   Tab.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
12578   Tab.AlignOperands = FormatStyle::OAS_AlignAfterOperator;
12579   verifyFormat("int aaaaaaaaaa = bbbbbbbbbbbbbbbbbbbb\n"
12580                "               + cccccccccccccccccccc;",
12581                Tab);
12582 }
12583 
12584 TEST_F(FormatTest, ZeroTabWidth) {
12585   FormatStyle Tab = getLLVMStyleWithColumns(42);
12586   Tab.IndentWidth = 8;
12587   Tab.UseTab = FormatStyle::UT_Never;
12588   Tab.TabWidth = 0;
12589   EXPECT_EQ("void a(){\n"
12590             "    // line starts with '\t'\n"
12591             "};",
12592             format("void a(){\n"
12593                    "\t// line starts with '\t'\n"
12594                    "};",
12595                    Tab));
12596 
12597   EXPECT_EQ("void a(){\n"
12598             "    // line starts with '\t'\n"
12599             "};",
12600             format("void a(){\n"
12601                    "\t\t// line starts with '\t'\n"
12602                    "};",
12603                    Tab));
12604 
12605   Tab.UseTab = FormatStyle::UT_ForIndentation;
12606   EXPECT_EQ("void a(){\n"
12607             "    // line starts with '\t'\n"
12608             "};",
12609             format("void a(){\n"
12610                    "\t// line starts with '\t'\n"
12611                    "};",
12612                    Tab));
12613 
12614   EXPECT_EQ("void a(){\n"
12615             "    // line starts with '\t'\n"
12616             "};",
12617             format("void a(){\n"
12618                    "\t\t// line starts with '\t'\n"
12619                    "};",
12620                    Tab));
12621 
12622   Tab.UseTab = FormatStyle::UT_ForContinuationAndIndentation;
12623   EXPECT_EQ("void a(){\n"
12624             "    // line starts with '\t'\n"
12625             "};",
12626             format("void a(){\n"
12627                    "\t// line starts with '\t'\n"
12628                    "};",
12629                    Tab));
12630 
12631   EXPECT_EQ("void a(){\n"
12632             "    // line starts with '\t'\n"
12633             "};",
12634             format("void a(){\n"
12635                    "\t\t// line starts with '\t'\n"
12636                    "};",
12637                    Tab));
12638 
12639   Tab.UseTab = FormatStyle::UT_AlignWithSpaces;
12640   EXPECT_EQ("void a(){\n"
12641             "    // line starts with '\t'\n"
12642             "};",
12643             format("void a(){\n"
12644                    "\t// line starts with '\t'\n"
12645                    "};",
12646                    Tab));
12647 
12648   EXPECT_EQ("void a(){\n"
12649             "    // line starts with '\t'\n"
12650             "};",
12651             format("void a(){\n"
12652                    "\t\t// line starts with '\t'\n"
12653                    "};",
12654                    Tab));
12655 
12656   Tab.UseTab = FormatStyle::UT_Always;
12657   EXPECT_EQ("void a(){\n"
12658             "// line starts with '\t'\n"
12659             "};",
12660             format("void a(){\n"
12661                    "\t// line starts with '\t'\n"
12662                    "};",
12663                    Tab));
12664 
12665   EXPECT_EQ("void a(){\n"
12666             "// line starts with '\t'\n"
12667             "};",
12668             format("void a(){\n"
12669                    "\t\t// line starts with '\t'\n"
12670                    "};",
12671                    Tab));
12672 }
12673 
12674 TEST_F(FormatTest, CalculatesOriginalColumn) {
12675   EXPECT_EQ("\"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12676             "q\"; /* some\n"
12677             "       comment */",
12678             format("  \"qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12679                    "q\"; /* some\n"
12680                    "       comment */",
12681                    getLLVMStyle()));
12682   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
12683             "/* some\n"
12684             "   comment */",
12685             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\n"
12686                    " /* some\n"
12687                    "    comment */",
12688                    getLLVMStyle()));
12689   EXPECT_EQ("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12690             "qqq\n"
12691             "/* some\n"
12692             "   comment */",
12693             format("// qqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12694                    "qqq\n"
12695                    " /* some\n"
12696                    "    comment */",
12697                    getLLVMStyle()));
12698   EXPECT_EQ("inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12699             "wwww; /* some\n"
12700             "         comment */",
12701             format("  inttt qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq\\\n"
12702                    "wwww; /* some\n"
12703                    "         comment */",
12704                    getLLVMStyle()));
12705 }
12706 
12707 TEST_F(FormatTest, ConfigurableSpaceBeforeParens) {
12708   FormatStyle NoSpace = getLLVMStyle();
12709   NoSpace.SpaceBeforeParens = FormatStyle::SBPO_Never;
12710 
12711   verifyFormat("while(true)\n"
12712                "  continue;",
12713                NoSpace);
12714   verifyFormat("for(;;)\n"
12715                "  continue;",
12716                NoSpace);
12717   verifyFormat("if(true)\n"
12718                "  f();\n"
12719                "else if(true)\n"
12720                "  f();",
12721                NoSpace);
12722   verifyFormat("do {\n"
12723                "  do_something();\n"
12724                "} while(something());",
12725                NoSpace);
12726   verifyFormat("switch(x) {\n"
12727                "default:\n"
12728                "  break;\n"
12729                "}",
12730                NoSpace);
12731   verifyFormat("auto i = std::make_unique<int>(5);", NoSpace);
12732   verifyFormat("size_t x = sizeof(x);", NoSpace);
12733   verifyFormat("auto f(int x) -> decltype(x);", NoSpace);
12734   verifyFormat("auto f(int x) -> typeof(x);", NoSpace);
12735   verifyFormat("auto f(int x) -> _Atomic(x);", NoSpace);
12736   verifyFormat("auto f(int x) -> __underlying_type(x);", NoSpace);
12737   verifyFormat("int f(T x) noexcept(x.create());", NoSpace);
12738   verifyFormat("alignas(128) char a[128];", NoSpace);
12739   verifyFormat("size_t x = alignof(MyType);", NoSpace);
12740   verifyFormat("static_assert(sizeof(char) == 1, \"Impossible!\");", NoSpace);
12741   verifyFormat("int f() throw(Deprecated);", NoSpace);
12742   verifyFormat("typedef void (*cb)(int);", NoSpace);
12743   verifyFormat("T A::operator()();", NoSpace);
12744   verifyFormat("X A::operator++(T);", NoSpace);
12745   verifyFormat("auto lambda = []() { return 0; };", NoSpace);
12746 
12747   FormatStyle Space = getLLVMStyle();
12748   Space.SpaceBeforeParens = FormatStyle::SBPO_Always;
12749 
12750   verifyFormat("int f ();", Space);
12751   verifyFormat("void f (int a, T b) {\n"
12752                "  while (true)\n"
12753                "    continue;\n"
12754                "}",
12755                Space);
12756   verifyFormat("if (true)\n"
12757                "  f ();\n"
12758                "else if (true)\n"
12759                "  f ();",
12760                Space);
12761   verifyFormat("do {\n"
12762                "  do_something ();\n"
12763                "} while (something ());",
12764                Space);
12765   verifyFormat("switch (x) {\n"
12766                "default:\n"
12767                "  break;\n"
12768                "}",
12769                Space);
12770   verifyFormat("A::A () : a (1) {}", Space);
12771   verifyFormat("void f () __attribute__ ((asdf));", Space);
12772   verifyFormat("*(&a + 1);\n"
12773                "&((&a)[1]);\n"
12774                "a[(b + c) * d];\n"
12775                "(((a + 1) * 2) + 3) * 4;",
12776                Space);
12777   verifyFormat("#define A(x) x", Space);
12778   verifyFormat("#define A (x) x", Space);
12779   verifyFormat("#if defined(x)\n"
12780                "#endif",
12781                Space);
12782   verifyFormat("auto i = std::make_unique<int> (5);", Space);
12783   verifyFormat("size_t x = sizeof (x);", Space);
12784   verifyFormat("auto f (int x) -> decltype (x);", Space);
12785   verifyFormat("auto f (int x) -> typeof (x);", Space);
12786   verifyFormat("auto f (int x) -> _Atomic (x);", Space);
12787   verifyFormat("auto f (int x) -> __underlying_type (x);", Space);
12788   verifyFormat("int f (T x) noexcept (x.create ());", Space);
12789   verifyFormat("alignas (128) char a[128];", Space);
12790   verifyFormat("size_t x = alignof (MyType);", Space);
12791   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");", Space);
12792   verifyFormat("int f () throw (Deprecated);", Space);
12793   verifyFormat("typedef void (*cb) (int);", Space);
12794   verifyFormat("T A::operator() ();", Space);
12795   verifyFormat("X A::operator++ (T);", Space);
12796   verifyFormat("auto lambda = [] () { return 0; };", Space);
12797   verifyFormat("int x = int (y);", Space);
12798 
12799   FormatStyle SomeSpace = getLLVMStyle();
12800   SomeSpace.SpaceBeforeParens = FormatStyle::SBPO_NonEmptyParentheses;
12801 
12802   verifyFormat("[]() -> float {}", SomeSpace);
12803   verifyFormat("[] (auto foo) {}", SomeSpace);
12804   verifyFormat("[foo]() -> int {}", SomeSpace);
12805   verifyFormat("int f();", SomeSpace);
12806   verifyFormat("void f (int a, T b) {\n"
12807                "  while (true)\n"
12808                "    continue;\n"
12809                "}",
12810                SomeSpace);
12811   verifyFormat("if (true)\n"
12812                "  f();\n"
12813                "else if (true)\n"
12814                "  f();",
12815                SomeSpace);
12816   verifyFormat("do {\n"
12817                "  do_something();\n"
12818                "} while (something());",
12819                SomeSpace);
12820   verifyFormat("switch (x) {\n"
12821                "default:\n"
12822                "  break;\n"
12823                "}",
12824                SomeSpace);
12825   verifyFormat("A::A() : a (1) {}", SomeSpace);
12826   verifyFormat("void f() __attribute__ ((asdf));", SomeSpace);
12827   verifyFormat("*(&a + 1);\n"
12828                "&((&a)[1]);\n"
12829                "a[(b + c) * d];\n"
12830                "(((a + 1) * 2) + 3) * 4;",
12831                SomeSpace);
12832   verifyFormat("#define A(x) x", SomeSpace);
12833   verifyFormat("#define A (x) x", SomeSpace);
12834   verifyFormat("#if defined(x)\n"
12835                "#endif",
12836                SomeSpace);
12837   verifyFormat("auto i = std::make_unique<int> (5);", SomeSpace);
12838   verifyFormat("size_t x = sizeof (x);", SomeSpace);
12839   verifyFormat("auto f (int x) -> decltype (x);", SomeSpace);
12840   verifyFormat("auto f (int x) -> typeof (x);", SomeSpace);
12841   verifyFormat("auto f (int x) -> _Atomic (x);", SomeSpace);
12842   verifyFormat("auto f (int x) -> __underlying_type (x);", SomeSpace);
12843   verifyFormat("int f (T x) noexcept (x.create());", SomeSpace);
12844   verifyFormat("alignas (128) char a[128];", SomeSpace);
12845   verifyFormat("size_t x = alignof (MyType);", SomeSpace);
12846   verifyFormat("static_assert (sizeof (char) == 1, \"Impossible!\");",
12847                SomeSpace);
12848   verifyFormat("int f() throw (Deprecated);", SomeSpace);
12849   verifyFormat("typedef void (*cb) (int);", SomeSpace);
12850   verifyFormat("T A::operator()();", SomeSpace);
12851   verifyFormat("X A::operator++ (T);", SomeSpace);
12852   verifyFormat("int x = int (y);", SomeSpace);
12853   verifyFormat("auto lambda = []() { return 0; };", SomeSpace);
12854 }
12855 
12856 TEST_F(FormatTest, SpaceAfterLogicalNot) {
12857   FormatStyle Spaces = getLLVMStyle();
12858   Spaces.SpaceAfterLogicalNot = true;
12859 
12860   verifyFormat("bool x = ! y", Spaces);
12861   verifyFormat("if (! isFailure())", Spaces);
12862   verifyFormat("if (! (a && b))", Spaces);
12863   verifyFormat("\"Error!\"", Spaces);
12864   verifyFormat("! ! x", Spaces);
12865 }
12866 
12867 TEST_F(FormatTest, ConfigurableSpacesInParentheses) {
12868   FormatStyle Spaces = getLLVMStyle();
12869 
12870   Spaces.SpacesInParentheses = true;
12871   verifyFormat("do_something( ::globalVar );", Spaces);
12872   verifyFormat("call( x, y, z );", Spaces);
12873   verifyFormat("call();", Spaces);
12874   verifyFormat("std::function<void( int, int )> callback;", Spaces);
12875   verifyFormat("void inFunction() { std::function<void( int, int )> fct; }",
12876                Spaces);
12877   verifyFormat("while ( (bool)1 )\n"
12878                "  continue;",
12879                Spaces);
12880   verifyFormat("for ( ;; )\n"
12881                "  continue;",
12882                Spaces);
12883   verifyFormat("if ( true )\n"
12884                "  f();\n"
12885                "else if ( true )\n"
12886                "  f();",
12887                Spaces);
12888   verifyFormat("do {\n"
12889                "  do_something( (int)i );\n"
12890                "} while ( something() );",
12891                Spaces);
12892   verifyFormat("switch ( x ) {\n"
12893                "default:\n"
12894                "  break;\n"
12895                "}",
12896                Spaces);
12897 
12898   Spaces.SpacesInParentheses = false;
12899   Spaces.SpacesInCStyleCastParentheses = true;
12900   verifyFormat("Type *A = ( Type * )P;", Spaces);
12901   verifyFormat("Type *A = ( vector<Type *, int *> )P;", Spaces);
12902   verifyFormat("x = ( int32 )y;", Spaces);
12903   verifyFormat("int a = ( int )(2.0f);", Spaces);
12904   verifyFormat("#define AA(X) sizeof((( X * )NULL)->a)", Spaces);
12905   verifyFormat("my_int a = ( my_int )sizeof(int);", Spaces);
12906   verifyFormat("#define x (( int )-1)", Spaces);
12907 
12908   // Run the first set of tests again with:
12909   Spaces.SpacesInParentheses = false;
12910   Spaces.SpaceInEmptyParentheses = true;
12911   Spaces.SpacesInCStyleCastParentheses = true;
12912   verifyFormat("call(x, y, z);", Spaces);
12913   verifyFormat("call( );", Spaces);
12914   verifyFormat("std::function<void(int, int)> callback;", Spaces);
12915   verifyFormat("while (( bool )1)\n"
12916                "  continue;",
12917                Spaces);
12918   verifyFormat("for (;;)\n"
12919                "  continue;",
12920                Spaces);
12921   verifyFormat("if (true)\n"
12922                "  f( );\n"
12923                "else if (true)\n"
12924                "  f( );",
12925                Spaces);
12926   verifyFormat("do {\n"
12927                "  do_something(( int )i);\n"
12928                "} while (something( ));",
12929                Spaces);
12930   verifyFormat("switch (x) {\n"
12931                "default:\n"
12932                "  break;\n"
12933                "}",
12934                Spaces);
12935 
12936   // Run the first set of tests again with:
12937   Spaces.SpaceAfterCStyleCast = true;
12938   verifyFormat("call(x, y, z);", Spaces);
12939   verifyFormat("call( );", Spaces);
12940   verifyFormat("std::function<void(int, int)> callback;", Spaces);
12941   verifyFormat("while (( bool ) 1)\n"
12942                "  continue;",
12943                Spaces);
12944   verifyFormat("for (;;)\n"
12945                "  continue;",
12946                Spaces);
12947   verifyFormat("if (true)\n"
12948                "  f( );\n"
12949                "else if (true)\n"
12950                "  f( );",
12951                Spaces);
12952   verifyFormat("do {\n"
12953                "  do_something(( int ) i);\n"
12954                "} while (something( ));",
12955                Spaces);
12956   verifyFormat("switch (x) {\n"
12957                "default:\n"
12958                "  break;\n"
12959                "}",
12960                Spaces);
12961 
12962   // Run subset of tests again with:
12963   Spaces.SpacesInCStyleCastParentheses = false;
12964   Spaces.SpaceAfterCStyleCast = true;
12965   verifyFormat("while ((bool) 1)\n"
12966                "  continue;",
12967                Spaces);
12968   verifyFormat("do {\n"
12969                "  do_something((int) i);\n"
12970                "} while (something( ));",
12971                Spaces);
12972 
12973   verifyFormat("size_t idx = (size_t) (ptr - ((char *) file));", Spaces);
12974   verifyFormat("size_t idx = (size_t) a;", Spaces);
12975   verifyFormat("size_t idx = (size_t) (a - 1);", Spaces);
12976   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
12977   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
12978   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
12979   Spaces.SpaceAfterCStyleCast = false;
12980   verifyFormat("size_t idx = (size_t)(ptr - ((char *)file));", Spaces);
12981   verifyFormat("size_t idx = (size_t)a;", Spaces);
12982   verifyFormat("size_t idx = (size_t)(a - 1);", Spaces);
12983   verifyFormat("size_t idx = (a->*foo)(a - 1);", Spaces);
12984   verifyFormat("size_t idx = (a->foo)(a - 1);", Spaces);
12985   verifyFormat("size_t idx = (*foo)(a - 1);", Spaces);
12986 }
12987 
12988 TEST_F(FormatTest, ConfigurableSpacesInSquareBrackets) {
12989   verifyFormat("int a[5];");
12990   verifyFormat("a[3] += 42;");
12991 
12992   FormatStyle Spaces = getLLVMStyle();
12993   Spaces.SpacesInSquareBrackets = true;
12994   // Not lambdas.
12995   verifyFormat("int a[ 5 ];", Spaces);
12996   verifyFormat("a[ 3 ] += 42;", Spaces);
12997   verifyFormat("constexpr char hello[]{\"hello\"};", Spaces);
12998   verifyFormat("double &operator[](int i) { return 0; }\n"
12999                "int i;",
13000                Spaces);
13001   verifyFormat("std::unique_ptr<int[]> foo() {}", Spaces);
13002   verifyFormat("int i = a[ a ][ a ]->f();", Spaces);
13003   verifyFormat("int i = (*b)[ a ]->f();", Spaces);
13004   // Lambdas.
13005   verifyFormat("int c = []() -> int { return 2; }();\n", Spaces);
13006   verifyFormat("return [ i, args... ] {};", Spaces);
13007   verifyFormat("int foo = [ &bar ]() {};", Spaces);
13008   verifyFormat("int foo = [ = ]() {};", Spaces);
13009   verifyFormat("int foo = [ & ]() {};", Spaces);
13010   verifyFormat("int foo = [ =, &bar ]() {};", Spaces);
13011   verifyFormat("int foo = [ &bar, = ]() {};", Spaces);
13012 }
13013 
13014 TEST_F(FormatTest, ConfigurableSpaceBeforeBrackets) {
13015   FormatStyle NoSpaceStyle = getLLVMStyle();
13016   verifyFormat("int a[5];", NoSpaceStyle);
13017   verifyFormat("a[3] += 42;", NoSpaceStyle);
13018 
13019   verifyFormat("int a[1];", NoSpaceStyle);
13020   verifyFormat("int 1 [a];", NoSpaceStyle);
13021   verifyFormat("int a[1][2];", NoSpaceStyle);
13022   verifyFormat("a[7] = 5;", NoSpaceStyle);
13023   verifyFormat("int a = (f())[23];", NoSpaceStyle);
13024   verifyFormat("f([] {})", NoSpaceStyle);
13025 
13026   FormatStyle Space = getLLVMStyle();
13027   Space.SpaceBeforeSquareBrackets = true;
13028   verifyFormat("int c = []() -> int { return 2; }();\n", Space);
13029   verifyFormat("return [i, args...] {};", Space);
13030 
13031   verifyFormat("int a [5];", Space);
13032   verifyFormat("a [3] += 42;", Space);
13033   verifyFormat("constexpr char hello []{\"hello\"};", Space);
13034   verifyFormat("double &operator[](int i) { return 0; }\n"
13035                "int i;",
13036                Space);
13037   verifyFormat("std::unique_ptr<int []> foo() {}", Space);
13038   verifyFormat("int i = a [a][a]->f();", Space);
13039   verifyFormat("int i = (*b) [a]->f();", Space);
13040 
13041   verifyFormat("int a [1];", Space);
13042   verifyFormat("int 1 [a];", Space);
13043   verifyFormat("int a [1][2];", Space);
13044   verifyFormat("a [7] = 5;", Space);
13045   verifyFormat("int a = (f()) [23];", Space);
13046   verifyFormat("f([] {})", Space);
13047 }
13048 
13049 TEST_F(FormatTest, ConfigurableSpaceBeforeAssignmentOperators) {
13050   verifyFormat("int a = 5;");
13051   verifyFormat("a += 42;");
13052   verifyFormat("a or_eq 8;");
13053 
13054   FormatStyle Spaces = getLLVMStyle();
13055   Spaces.SpaceBeforeAssignmentOperators = false;
13056   verifyFormat("int a= 5;", Spaces);
13057   verifyFormat("a+= 42;", Spaces);
13058   verifyFormat("a or_eq 8;", Spaces);
13059 }
13060 
13061 TEST_F(FormatTest, ConfigurableSpaceBeforeColon) {
13062   verifyFormat("class Foo : public Bar {};");
13063   verifyFormat("Foo::Foo() : foo(1) {}");
13064   verifyFormat("for (auto a : b) {\n}");
13065   verifyFormat("int x = a ? b : c;");
13066   verifyFormat("{\n"
13067                "label0:\n"
13068                "  int x = 0;\n"
13069                "}");
13070   verifyFormat("switch (x) {\n"
13071                "case 1:\n"
13072                "default:\n"
13073                "}");
13074   verifyFormat("switch (allBraces) {\n"
13075                "case 1: {\n"
13076                "  break;\n"
13077                "}\n"
13078                "case 2: {\n"
13079                "  [[fallthrough]];\n"
13080                "}\n"
13081                "default: {\n"
13082                "  break;\n"
13083                "}\n"
13084                "}");
13085 
13086   FormatStyle CtorInitializerStyle = getLLVMStyleWithColumns(30);
13087   CtorInitializerStyle.SpaceBeforeCtorInitializerColon = false;
13088   verifyFormat("class Foo : public Bar {};", CtorInitializerStyle);
13089   verifyFormat("Foo::Foo(): foo(1) {}", CtorInitializerStyle);
13090   verifyFormat("for (auto a : b) {\n}", CtorInitializerStyle);
13091   verifyFormat("int x = a ? b : c;", CtorInitializerStyle);
13092   verifyFormat("{\n"
13093                "label1:\n"
13094                "  int x = 0;\n"
13095                "}",
13096                CtorInitializerStyle);
13097   verifyFormat("switch (x) {\n"
13098                "case 1:\n"
13099                "default:\n"
13100                "}",
13101                CtorInitializerStyle);
13102   verifyFormat("switch (allBraces) {\n"
13103                "case 1: {\n"
13104                "  break;\n"
13105                "}\n"
13106                "case 2: {\n"
13107                "  [[fallthrough]];\n"
13108                "}\n"
13109                "default: {\n"
13110                "  break;\n"
13111                "}\n"
13112                "}",
13113                CtorInitializerStyle);
13114   CtorInitializerStyle.BreakConstructorInitializers =
13115       FormatStyle::BCIS_AfterColon;
13116   verifyFormat("Fooooooooooo::Fooooooooooo():\n"
13117                "    aaaaaaaaaaaaaaaa(1),\n"
13118                "    bbbbbbbbbbbbbbbb(2) {}",
13119                CtorInitializerStyle);
13120   CtorInitializerStyle.BreakConstructorInitializers =
13121       FormatStyle::BCIS_BeforeComma;
13122   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
13123                "    : aaaaaaaaaaaaaaaa(1)\n"
13124                "    , bbbbbbbbbbbbbbbb(2) {}",
13125                CtorInitializerStyle);
13126   CtorInitializerStyle.BreakConstructorInitializers =
13127       FormatStyle::BCIS_BeforeColon;
13128   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
13129                "    : aaaaaaaaaaaaaaaa(1),\n"
13130                "      bbbbbbbbbbbbbbbb(2) {}",
13131                CtorInitializerStyle);
13132   CtorInitializerStyle.ConstructorInitializerIndentWidth = 0;
13133   verifyFormat("Fooooooooooo::Fooooooooooo()\n"
13134                ": aaaaaaaaaaaaaaaa(1),\n"
13135                "  bbbbbbbbbbbbbbbb(2) {}",
13136                CtorInitializerStyle);
13137 
13138   FormatStyle InheritanceStyle = getLLVMStyleWithColumns(30);
13139   InheritanceStyle.SpaceBeforeInheritanceColon = false;
13140   verifyFormat("class Foo: public Bar {};", InheritanceStyle);
13141   verifyFormat("Foo::Foo() : foo(1) {}", InheritanceStyle);
13142   verifyFormat("for (auto a : b) {\n}", InheritanceStyle);
13143   verifyFormat("int x = a ? b : c;", InheritanceStyle);
13144   verifyFormat("{\n"
13145                "label2:\n"
13146                "  int x = 0;\n"
13147                "}",
13148                InheritanceStyle);
13149   verifyFormat("switch (x) {\n"
13150                "case 1:\n"
13151                "default:\n"
13152                "}",
13153                InheritanceStyle);
13154   verifyFormat("switch (allBraces) {\n"
13155                "case 1: {\n"
13156                "  break;\n"
13157                "}\n"
13158                "case 2: {\n"
13159                "  [[fallthrough]];\n"
13160                "}\n"
13161                "default: {\n"
13162                "  break;\n"
13163                "}\n"
13164                "}",
13165                InheritanceStyle);
13166   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_AfterColon;
13167   verifyFormat("class Foooooooooooooooooooooo:\n"
13168                "    public aaaaaaaaaaaaaaaaaa,\n"
13169                "    public bbbbbbbbbbbbbbbbbb {\n"
13170                "}",
13171                InheritanceStyle);
13172   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeComma;
13173   verifyFormat("class Foooooooooooooooooooooo\n"
13174                "    : public aaaaaaaaaaaaaaaaaa\n"
13175                "    , public bbbbbbbbbbbbbbbbbb {\n"
13176                "}",
13177                InheritanceStyle);
13178   InheritanceStyle.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
13179   verifyFormat("class Foooooooooooooooooooooo\n"
13180                "    : public aaaaaaaaaaaaaaaaaa,\n"
13181                "      public bbbbbbbbbbbbbbbbbb {\n"
13182                "}",
13183                InheritanceStyle);
13184   InheritanceStyle.ConstructorInitializerIndentWidth = 0;
13185   verifyFormat("class Foooooooooooooooooooooo\n"
13186                ": public aaaaaaaaaaaaaaaaaa,\n"
13187                "  public bbbbbbbbbbbbbbbbbb {}",
13188                InheritanceStyle);
13189 
13190   FormatStyle ForLoopStyle = getLLVMStyle();
13191   ForLoopStyle.SpaceBeforeRangeBasedForLoopColon = false;
13192   verifyFormat("class Foo : public Bar {};", ForLoopStyle);
13193   verifyFormat("Foo::Foo() : foo(1) {}", ForLoopStyle);
13194   verifyFormat("for (auto a: b) {\n}", ForLoopStyle);
13195   verifyFormat("int x = a ? b : c;", ForLoopStyle);
13196   verifyFormat("{\n"
13197                "label2:\n"
13198                "  int x = 0;\n"
13199                "}",
13200                ForLoopStyle);
13201   verifyFormat("switch (x) {\n"
13202                "case 1:\n"
13203                "default:\n"
13204                "}",
13205                ForLoopStyle);
13206   verifyFormat("switch (allBraces) {\n"
13207                "case 1: {\n"
13208                "  break;\n"
13209                "}\n"
13210                "case 2: {\n"
13211                "  [[fallthrough]];\n"
13212                "}\n"
13213                "default: {\n"
13214                "  break;\n"
13215                "}\n"
13216                "}",
13217                ForLoopStyle);
13218 
13219   FormatStyle CaseStyle = getLLVMStyle();
13220   CaseStyle.SpaceBeforeCaseColon = true;
13221   verifyFormat("class Foo : public Bar {};", CaseStyle);
13222   verifyFormat("Foo::Foo() : foo(1) {}", CaseStyle);
13223   verifyFormat("for (auto a : b) {\n}", CaseStyle);
13224   verifyFormat("int x = a ? b : c;", CaseStyle);
13225   verifyFormat("switch (x) {\n"
13226                "case 1 :\n"
13227                "default :\n"
13228                "}",
13229                CaseStyle);
13230   verifyFormat("switch (allBraces) {\n"
13231                "case 1 : {\n"
13232                "  break;\n"
13233                "}\n"
13234                "case 2 : {\n"
13235                "  [[fallthrough]];\n"
13236                "}\n"
13237                "default : {\n"
13238                "  break;\n"
13239                "}\n"
13240                "}",
13241                CaseStyle);
13242 
13243   FormatStyle NoSpaceStyle = getLLVMStyle();
13244   EXPECT_EQ(NoSpaceStyle.SpaceBeforeCaseColon, false);
13245   NoSpaceStyle.SpaceBeforeCtorInitializerColon = false;
13246   NoSpaceStyle.SpaceBeforeInheritanceColon = false;
13247   NoSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
13248   verifyFormat("class Foo: public Bar {};", NoSpaceStyle);
13249   verifyFormat("Foo::Foo(): foo(1) {}", NoSpaceStyle);
13250   verifyFormat("for (auto a: b) {\n}", NoSpaceStyle);
13251   verifyFormat("int x = a ? b : c;", NoSpaceStyle);
13252   verifyFormat("{\n"
13253                "label3:\n"
13254                "  int x = 0;\n"
13255                "}",
13256                NoSpaceStyle);
13257   verifyFormat("switch (x) {\n"
13258                "case 1:\n"
13259                "default:\n"
13260                "}",
13261                NoSpaceStyle);
13262   verifyFormat("switch (allBraces) {\n"
13263                "case 1: {\n"
13264                "  break;\n"
13265                "}\n"
13266                "case 2: {\n"
13267                "  [[fallthrough]];\n"
13268                "}\n"
13269                "default: {\n"
13270                "  break;\n"
13271                "}\n"
13272                "}",
13273                NoSpaceStyle);
13274 
13275   FormatStyle InvertedSpaceStyle = getLLVMStyle();
13276   InvertedSpaceStyle.SpaceBeforeCaseColon = true;
13277   InvertedSpaceStyle.SpaceBeforeCtorInitializerColon = false;
13278   InvertedSpaceStyle.SpaceBeforeInheritanceColon = false;
13279   InvertedSpaceStyle.SpaceBeforeRangeBasedForLoopColon = false;
13280   verifyFormat("class Foo: public Bar {};", InvertedSpaceStyle);
13281   verifyFormat("Foo::Foo(): foo(1) {}", InvertedSpaceStyle);
13282   verifyFormat("for (auto a: b) {\n}", InvertedSpaceStyle);
13283   verifyFormat("int x = a ? b : c;", InvertedSpaceStyle);
13284   verifyFormat("{\n"
13285                "label3:\n"
13286                "  int x = 0;\n"
13287                "}",
13288                InvertedSpaceStyle);
13289   verifyFormat("switch (x) {\n"
13290                "case 1 :\n"
13291                "case 2 : {\n"
13292                "  break;\n"
13293                "}\n"
13294                "default :\n"
13295                "  break;\n"
13296                "}",
13297                InvertedSpaceStyle);
13298   verifyFormat("switch (allBraces) {\n"
13299                "case 1 : {\n"
13300                "  break;\n"
13301                "}\n"
13302                "case 2 : {\n"
13303                "  [[fallthrough]];\n"
13304                "}\n"
13305                "default : {\n"
13306                "  break;\n"
13307                "}\n"
13308                "}",
13309                InvertedSpaceStyle);
13310 }
13311 
13312 TEST_F(FormatTest, ConfigurableSpaceAroundPointerQualifiers) {
13313   FormatStyle Style = getLLVMStyle();
13314 
13315   Style.PointerAlignment = FormatStyle::PAS_Left;
13316   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
13317   verifyFormat("void* const* x = NULL;", Style);
13318 
13319 #define verifyQualifierSpaces(Code, Pointers, Qualifiers)                      \
13320   do {                                                                         \
13321     Style.PointerAlignment = FormatStyle::Pointers;                            \
13322     Style.SpaceAroundPointerQualifiers = FormatStyle::Qualifiers;              \
13323     verifyFormat(Code, Style);                                                 \
13324   } while (false)
13325 
13326   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Default);
13327   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_Default);
13328   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Default);
13329 
13330   verifyQualifierSpaces("void* const* x = NULL;", PAS_Left, SAPQ_Before);
13331   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Before);
13332   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Before);
13333 
13334   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_After);
13335   verifyQualifierSpaces("void *const *x = NULL;", PAS_Right, SAPQ_After);
13336   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_After);
13337 
13338   verifyQualifierSpaces("void* const * x = NULL;", PAS_Left, SAPQ_Both);
13339   verifyQualifierSpaces("void * const *x = NULL;", PAS_Right, SAPQ_Both);
13340   verifyQualifierSpaces("void * const * x = NULL;", PAS_Middle, SAPQ_Both);
13341 
13342   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Default);
13343   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
13344                         SAPQ_Default);
13345   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
13346                         SAPQ_Default);
13347 
13348   verifyQualifierSpaces("Foo::operator void const*();", PAS_Left, SAPQ_Before);
13349   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right,
13350                         SAPQ_Before);
13351   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
13352                         SAPQ_Before);
13353 
13354   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_After);
13355   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_After);
13356   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle,
13357                         SAPQ_After);
13358 
13359   verifyQualifierSpaces("Foo::operator void const *();", PAS_Left, SAPQ_Both);
13360   verifyQualifierSpaces("Foo::operator void const *();", PAS_Right, SAPQ_Both);
13361   verifyQualifierSpaces("Foo::operator void const *();", PAS_Middle, SAPQ_Both);
13362 
13363 #undef verifyQualifierSpaces
13364 
13365   FormatStyle Spaces = getLLVMStyle();
13366   Spaces.AttributeMacros.push_back("qualified");
13367   Spaces.PointerAlignment = FormatStyle::PAS_Right;
13368   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Default;
13369   verifyFormat("SomeType *volatile *a = NULL;", Spaces);
13370   verifyFormat("SomeType *__attribute__((attr)) *a = NULL;", Spaces);
13371   verifyFormat("std::vector<SomeType *const *> x;", Spaces);
13372   verifyFormat("std::vector<SomeType *qualified *> x;", Spaces);
13373   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13374   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
13375   verifyFormat("SomeType * volatile *a = NULL;", Spaces);
13376   verifyFormat("SomeType * __attribute__((attr)) *a = NULL;", Spaces);
13377   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
13378   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
13379   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13380 
13381   // Check that SAPQ_Before doesn't result in extra spaces for PAS_Left.
13382   Spaces.PointerAlignment = FormatStyle::PAS_Left;
13383   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Before;
13384   verifyFormat("SomeType* volatile* a = NULL;", Spaces);
13385   verifyFormat("SomeType* __attribute__((attr))* a = NULL;", Spaces);
13386   verifyFormat("std::vector<SomeType* const*> x;", Spaces);
13387   verifyFormat("std::vector<SomeType* qualified*> x;", Spaces);
13388   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13389   // However, setting it to SAPQ_After should add spaces after __attribute, etc.
13390   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
13391   verifyFormat("SomeType* volatile * a = NULL;", Spaces);
13392   verifyFormat("SomeType* __attribute__((attr)) * a = NULL;", Spaces);
13393   verifyFormat("std::vector<SomeType* const *> x;", Spaces);
13394   verifyFormat("std::vector<SomeType* qualified *> x;", Spaces);
13395   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13396 
13397   // PAS_Middle should not have any noticeable changes even for SAPQ_Both
13398   Spaces.PointerAlignment = FormatStyle::PAS_Middle;
13399   Spaces.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_After;
13400   verifyFormat("SomeType * volatile * a = NULL;", Spaces);
13401   verifyFormat("SomeType * __attribute__((attr)) * a = NULL;", Spaces);
13402   verifyFormat("std::vector<SomeType * const *> x;", Spaces);
13403   verifyFormat("std::vector<SomeType * qualified *> x;", Spaces);
13404   verifyFormat("std::vector<SomeVar * NotAQualifier> x;", Spaces);
13405 }
13406 
13407 TEST_F(FormatTest, AlignConsecutiveMacros) {
13408   FormatStyle Style = getLLVMStyle();
13409   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
13410   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
13411   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
13412 
13413   verifyFormat("#define a 3\n"
13414                "#define bbbb 4\n"
13415                "#define ccc (5)",
13416                Style);
13417 
13418   verifyFormat("#define f(x) (x * x)\n"
13419                "#define fff(x, y, z) (x * y + z)\n"
13420                "#define ffff(x, y) (x - y)",
13421                Style);
13422 
13423   verifyFormat("#define foo(x, y) (x + y)\n"
13424                "#define bar (5, 6)(2 + 2)",
13425                Style);
13426 
13427   verifyFormat("#define a 3\n"
13428                "#define bbbb 4\n"
13429                "#define ccc (5)\n"
13430                "#define f(x) (x * x)\n"
13431                "#define fff(x, y, z) (x * y + z)\n"
13432                "#define ffff(x, y) (x - y)",
13433                Style);
13434 
13435   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13436   verifyFormat("#define a    3\n"
13437                "#define bbbb 4\n"
13438                "#define ccc  (5)",
13439                Style);
13440 
13441   verifyFormat("#define f(x)         (x * x)\n"
13442                "#define fff(x, y, z) (x * y + z)\n"
13443                "#define ffff(x, y)   (x - y)",
13444                Style);
13445 
13446   verifyFormat("#define foo(x, y) (x + y)\n"
13447                "#define bar       (5, 6)(2 + 2)",
13448                Style);
13449 
13450   verifyFormat("#define a            3\n"
13451                "#define bbbb         4\n"
13452                "#define ccc          (5)\n"
13453                "#define f(x)         (x * x)\n"
13454                "#define fff(x, y, z) (x * y + z)\n"
13455                "#define ffff(x, y)   (x - y)",
13456                Style);
13457 
13458   verifyFormat("#define a         5\n"
13459                "#define foo(x, y) (x + y)\n"
13460                "#define CCC       (6)\n"
13461                "auto lambda = []() {\n"
13462                "  auto  ii = 0;\n"
13463                "  float j  = 0;\n"
13464                "  return 0;\n"
13465                "};\n"
13466                "int   i  = 0;\n"
13467                "float i2 = 0;\n"
13468                "auto  v  = type{\n"
13469                "    i = 1,   //\n"
13470                "    (i = 2), //\n"
13471                "    i = 3    //\n"
13472                "};",
13473                Style);
13474 
13475   Style.AlignConsecutiveMacros = FormatStyle::ACS_None;
13476   Style.ColumnLimit = 20;
13477 
13478   verifyFormat("#define a          \\\n"
13479                "  \"aabbbbbbbbbbbb\"\n"
13480                "#define D          \\\n"
13481                "  \"aabbbbbbbbbbbb\" \\\n"
13482                "  \"ccddeeeeeeeee\"\n"
13483                "#define B          \\\n"
13484                "  \"QQQQQQQQQQQQQ\"  \\\n"
13485                "  \"FFFFFFFFFFFFF\"  \\\n"
13486                "  \"LLLLLLLL\"\n",
13487                Style);
13488 
13489   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13490   verifyFormat("#define a          \\\n"
13491                "  \"aabbbbbbbbbbbb\"\n"
13492                "#define D          \\\n"
13493                "  \"aabbbbbbbbbbbb\" \\\n"
13494                "  \"ccddeeeeeeeee\"\n"
13495                "#define B          \\\n"
13496                "  \"QQQQQQQQQQQQQ\"  \\\n"
13497                "  \"FFFFFFFFFFFFF\"  \\\n"
13498                "  \"LLLLLLLL\"\n",
13499                Style);
13500 
13501   // Test across comments
13502   Style.MaxEmptyLinesToKeep = 10;
13503   Style.ReflowComments = false;
13504   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossComments;
13505   EXPECT_EQ("#define a    3\n"
13506             "// line comment\n"
13507             "#define bbbb 4\n"
13508             "#define ccc  (5)",
13509             format("#define a 3\n"
13510                    "// line comment\n"
13511                    "#define bbbb 4\n"
13512                    "#define ccc (5)",
13513                    Style));
13514 
13515   EXPECT_EQ("#define a    3\n"
13516             "/* block comment */\n"
13517             "#define bbbb 4\n"
13518             "#define ccc  (5)",
13519             format("#define a  3\n"
13520                    "/* block comment */\n"
13521                    "#define bbbb 4\n"
13522                    "#define ccc (5)",
13523                    Style));
13524 
13525   EXPECT_EQ("#define a    3\n"
13526             "/* multi-line *\n"
13527             " * block comment */\n"
13528             "#define bbbb 4\n"
13529             "#define ccc  (5)",
13530             format("#define a 3\n"
13531                    "/* multi-line *\n"
13532                    " * block comment */\n"
13533                    "#define bbbb 4\n"
13534                    "#define ccc (5)",
13535                    Style));
13536 
13537   EXPECT_EQ("#define a    3\n"
13538             "// multi-line line comment\n"
13539             "//\n"
13540             "#define bbbb 4\n"
13541             "#define ccc  (5)",
13542             format("#define a  3\n"
13543                    "// multi-line line comment\n"
13544                    "//\n"
13545                    "#define bbbb 4\n"
13546                    "#define ccc (5)",
13547                    Style));
13548 
13549   EXPECT_EQ("#define a 3\n"
13550             "// empty lines still break.\n"
13551             "\n"
13552             "#define bbbb 4\n"
13553             "#define ccc  (5)",
13554             format("#define a     3\n"
13555                    "// empty lines still break.\n"
13556                    "\n"
13557                    "#define bbbb     4\n"
13558                    "#define ccc  (5)",
13559                    Style));
13560 
13561   // Test across empty lines
13562   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLines;
13563   EXPECT_EQ("#define a    3\n"
13564             "\n"
13565             "#define bbbb 4\n"
13566             "#define ccc  (5)",
13567             format("#define a 3\n"
13568                    "\n"
13569                    "#define bbbb 4\n"
13570                    "#define ccc (5)",
13571                    Style));
13572 
13573   EXPECT_EQ("#define a    3\n"
13574             "\n"
13575             "\n"
13576             "\n"
13577             "#define bbbb 4\n"
13578             "#define ccc  (5)",
13579             format("#define a        3\n"
13580                    "\n"
13581                    "\n"
13582                    "\n"
13583                    "#define bbbb 4\n"
13584                    "#define ccc (5)",
13585                    Style));
13586 
13587   EXPECT_EQ("#define a 3\n"
13588             "// comments should break alignment\n"
13589             "//\n"
13590             "#define bbbb 4\n"
13591             "#define ccc  (5)",
13592             format("#define a        3\n"
13593                    "// comments should break alignment\n"
13594                    "//\n"
13595                    "#define bbbb 4\n"
13596                    "#define ccc (5)",
13597                    Style));
13598 
13599   // Test across empty lines and comments
13600   Style.AlignConsecutiveMacros = FormatStyle::ACS_AcrossEmptyLinesAndComments;
13601   verifyFormat("#define a    3\n"
13602                "\n"
13603                "// line comment\n"
13604                "#define bbbb 4\n"
13605                "#define ccc  (5)",
13606                Style);
13607 
13608   EXPECT_EQ("#define a    3\n"
13609             "\n"
13610             "\n"
13611             "/* multi-line *\n"
13612             " * block comment */\n"
13613             "\n"
13614             "\n"
13615             "#define bbbb 4\n"
13616             "#define ccc  (5)",
13617             format("#define a 3\n"
13618                    "\n"
13619                    "\n"
13620                    "/* multi-line *\n"
13621                    " * block comment */\n"
13622                    "\n"
13623                    "\n"
13624                    "#define bbbb 4\n"
13625                    "#define ccc (5)",
13626                    Style));
13627 
13628   EXPECT_EQ("#define a    3\n"
13629             "\n"
13630             "\n"
13631             "/* multi-line *\n"
13632             " * block comment */\n"
13633             "\n"
13634             "\n"
13635             "#define bbbb 4\n"
13636             "#define ccc  (5)",
13637             format("#define a 3\n"
13638                    "\n"
13639                    "\n"
13640                    "/* multi-line *\n"
13641                    " * block comment */\n"
13642                    "\n"
13643                    "\n"
13644                    "#define bbbb 4\n"
13645                    "#define ccc       (5)",
13646                    Style));
13647 }
13648 
13649 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLines) {
13650   FormatStyle Alignment = getLLVMStyle();
13651   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13652   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossEmptyLines;
13653 
13654   Alignment.MaxEmptyLinesToKeep = 10;
13655   /* Test alignment across empty lines */
13656   EXPECT_EQ("int a           = 5;\n"
13657             "\n"
13658             "int oneTwoThree = 123;",
13659             format("int a       = 5;\n"
13660                    "\n"
13661                    "int oneTwoThree= 123;",
13662                    Alignment));
13663   EXPECT_EQ("int a           = 5;\n"
13664             "int one         = 1;\n"
13665             "\n"
13666             "int oneTwoThree = 123;",
13667             format("int a = 5;\n"
13668                    "int one = 1;\n"
13669                    "\n"
13670                    "int oneTwoThree = 123;",
13671                    Alignment));
13672   EXPECT_EQ("int a           = 5;\n"
13673             "int one         = 1;\n"
13674             "\n"
13675             "int oneTwoThree = 123;\n"
13676             "int oneTwo      = 12;",
13677             format("int a = 5;\n"
13678                    "int one = 1;\n"
13679                    "\n"
13680                    "int oneTwoThree = 123;\n"
13681                    "int oneTwo = 12;",
13682                    Alignment));
13683 
13684   /* Test across comments */
13685   EXPECT_EQ("int a = 5;\n"
13686             "/* block comment */\n"
13687             "int oneTwoThree = 123;",
13688             format("int a = 5;\n"
13689                    "/* block comment */\n"
13690                    "int oneTwoThree=123;",
13691                    Alignment));
13692 
13693   EXPECT_EQ("int a = 5;\n"
13694             "// line comment\n"
13695             "int oneTwoThree = 123;",
13696             format("int a = 5;\n"
13697                    "// line comment\n"
13698                    "int oneTwoThree=123;",
13699                    Alignment));
13700 
13701   /* Test across comments and newlines */
13702   EXPECT_EQ("int a = 5;\n"
13703             "\n"
13704             "/* block comment */\n"
13705             "int oneTwoThree = 123;",
13706             format("int a = 5;\n"
13707                    "\n"
13708                    "/* block comment */\n"
13709                    "int oneTwoThree=123;",
13710                    Alignment));
13711 
13712   EXPECT_EQ("int a = 5;\n"
13713             "\n"
13714             "// line comment\n"
13715             "int oneTwoThree = 123;",
13716             format("int a = 5;\n"
13717                    "\n"
13718                    "// line comment\n"
13719                    "int oneTwoThree=123;",
13720                    Alignment));
13721 }
13722 
13723 TEST_F(FormatTest, AlignConsecutiveDeclarationsAcrossEmptyLinesAndComments) {
13724   FormatStyle Alignment = getLLVMStyle();
13725   Alignment.AlignConsecutiveDeclarations =
13726       FormatStyle::ACS_AcrossEmptyLinesAndComments;
13727   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
13728 
13729   Alignment.MaxEmptyLinesToKeep = 10;
13730   /* Test alignment across empty lines */
13731   EXPECT_EQ("int         a = 5;\n"
13732             "\n"
13733             "float const oneTwoThree = 123;",
13734             format("int a = 5;\n"
13735                    "\n"
13736                    "float const oneTwoThree = 123;",
13737                    Alignment));
13738   EXPECT_EQ("int         a = 5;\n"
13739             "float const one = 1;\n"
13740             "\n"
13741             "int         oneTwoThree = 123;",
13742             format("int a = 5;\n"
13743                    "float const one = 1;\n"
13744                    "\n"
13745                    "int oneTwoThree = 123;",
13746                    Alignment));
13747 
13748   /* Test across comments */
13749   EXPECT_EQ("float const a = 5;\n"
13750             "/* block comment */\n"
13751             "int         oneTwoThree = 123;",
13752             format("float const a = 5;\n"
13753                    "/* block comment */\n"
13754                    "int oneTwoThree=123;",
13755                    Alignment));
13756 
13757   EXPECT_EQ("float const a = 5;\n"
13758             "// line comment\n"
13759             "int         oneTwoThree = 123;",
13760             format("float const a = 5;\n"
13761                    "// line comment\n"
13762                    "int oneTwoThree=123;",
13763                    Alignment));
13764 
13765   /* Test across comments and newlines */
13766   EXPECT_EQ("float const a = 5;\n"
13767             "\n"
13768             "/* block comment */\n"
13769             "int         oneTwoThree = 123;",
13770             format("float const a = 5;\n"
13771                    "\n"
13772                    "/* block comment */\n"
13773                    "int         oneTwoThree=123;",
13774                    Alignment));
13775 
13776   EXPECT_EQ("float const a = 5;\n"
13777             "\n"
13778             "// line comment\n"
13779             "int         oneTwoThree = 123;",
13780             format("float const a = 5;\n"
13781                    "\n"
13782                    "// line comment\n"
13783                    "int oneTwoThree=123;",
13784                    Alignment));
13785 }
13786 
13787 TEST_F(FormatTest, AlignConsecutiveBitFieldsAcrossEmptyLinesAndComments) {
13788   FormatStyle Alignment = getLLVMStyle();
13789   Alignment.AlignConsecutiveBitFields =
13790       FormatStyle::ACS_AcrossEmptyLinesAndComments;
13791 
13792   Alignment.MaxEmptyLinesToKeep = 10;
13793   /* Test alignment across empty lines */
13794   EXPECT_EQ("int a            : 5;\n"
13795             "\n"
13796             "int longbitfield : 6;",
13797             format("int a : 5;\n"
13798                    "\n"
13799                    "int longbitfield : 6;",
13800                    Alignment));
13801   EXPECT_EQ("int a            : 5;\n"
13802             "int one          : 1;\n"
13803             "\n"
13804             "int longbitfield : 6;",
13805             format("int a : 5;\n"
13806                    "int one : 1;\n"
13807                    "\n"
13808                    "int longbitfield : 6;",
13809                    Alignment));
13810 
13811   /* Test across comments */
13812   EXPECT_EQ("int a            : 5;\n"
13813             "/* block comment */\n"
13814             "int longbitfield : 6;",
13815             format("int a : 5;\n"
13816                    "/* block comment */\n"
13817                    "int longbitfield : 6;",
13818                    Alignment));
13819   EXPECT_EQ("int a            : 5;\n"
13820             "int one          : 1;\n"
13821             "// line comment\n"
13822             "int longbitfield : 6;",
13823             format("int a : 5;\n"
13824                    "int one : 1;\n"
13825                    "// line comment\n"
13826                    "int longbitfield : 6;",
13827                    Alignment));
13828 
13829   /* Test across comments and newlines */
13830   EXPECT_EQ("int a            : 5;\n"
13831             "/* block comment */\n"
13832             "\n"
13833             "int longbitfield : 6;",
13834             format("int a : 5;\n"
13835                    "/* block comment */\n"
13836                    "\n"
13837                    "int longbitfield : 6;",
13838                    Alignment));
13839   EXPECT_EQ("int a            : 5;\n"
13840             "int one          : 1;\n"
13841             "\n"
13842             "// line comment\n"
13843             "\n"
13844             "int longbitfield : 6;",
13845             format("int a : 5;\n"
13846                    "int one : 1;\n"
13847                    "\n"
13848                    "// line comment \n"
13849                    "\n"
13850                    "int longbitfield : 6;",
13851                    Alignment));
13852 }
13853 
13854 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossComments) {
13855   FormatStyle Alignment = getLLVMStyle();
13856   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13857   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_AcrossComments;
13858 
13859   Alignment.MaxEmptyLinesToKeep = 10;
13860   /* Test alignment across empty lines */
13861   EXPECT_EQ("int a = 5;\n"
13862             "\n"
13863             "int oneTwoThree = 123;",
13864             format("int a       = 5;\n"
13865                    "\n"
13866                    "int oneTwoThree= 123;",
13867                    Alignment));
13868   EXPECT_EQ("int a   = 5;\n"
13869             "int one = 1;\n"
13870             "\n"
13871             "int oneTwoThree = 123;",
13872             format("int a = 5;\n"
13873                    "int one = 1;\n"
13874                    "\n"
13875                    "int oneTwoThree = 123;",
13876                    Alignment));
13877 
13878   /* Test across comments */
13879   EXPECT_EQ("int a           = 5;\n"
13880             "/* block comment */\n"
13881             "int oneTwoThree = 123;",
13882             format("int a = 5;\n"
13883                    "/* block comment */\n"
13884                    "int oneTwoThree=123;",
13885                    Alignment));
13886 
13887   EXPECT_EQ("int a           = 5;\n"
13888             "// line comment\n"
13889             "int oneTwoThree = 123;",
13890             format("int a = 5;\n"
13891                    "// line comment\n"
13892                    "int oneTwoThree=123;",
13893                    Alignment));
13894 
13895   EXPECT_EQ("int a           = 5;\n"
13896             "/*\n"
13897             " * multi-line block comment\n"
13898             " */\n"
13899             "int oneTwoThree = 123;",
13900             format("int a = 5;\n"
13901                    "/*\n"
13902                    " * multi-line block comment\n"
13903                    " */\n"
13904                    "int oneTwoThree=123;",
13905                    Alignment));
13906 
13907   EXPECT_EQ("int a           = 5;\n"
13908             "//\n"
13909             "// multi-line line comment\n"
13910             "//\n"
13911             "int oneTwoThree = 123;",
13912             format("int a = 5;\n"
13913                    "//\n"
13914                    "// multi-line line comment\n"
13915                    "//\n"
13916                    "int oneTwoThree=123;",
13917                    Alignment));
13918 
13919   /* Test across comments and newlines */
13920   EXPECT_EQ("int a = 5;\n"
13921             "\n"
13922             "/* block comment */\n"
13923             "int oneTwoThree = 123;",
13924             format("int a = 5;\n"
13925                    "\n"
13926                    "/* block comment */\n"
13927                    "int oneTwoThree=123;",
13928                    Alignment));
13929 
13930   EXPECT_EQ("int a = 5;\n"
13931             "\n"
13932             "// line comment\n"
13933             "int oneTwoThree = 123;",
13934             format("int a = 5;\n"
13935                    "\n"
13936                    "// line comment\n"
13937                    "int oneTwoThree=123;",
13938                    Alignment));
13939 }
13940 
13941 TEST_F(FormatTest, AlignConsecutiveAssignmentsAcrossEmptyLinesAndComments) {
13942   FormatStyle Alignment = getLLVMStyle();
13943   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
13944   Alignment.AlignConsecutiveAssignments =
13945       FormatStyle::ACS_AcrossEmptyLinesAndComments;
13946   verifyFormat("int a           = 5;\n"
13947                "int oneTwoThree = 123;",
13948                Alignment);
13949   verifyFormat("int a           = method();\n"
13950                "int oneTwoThree = 133;",
13951                Alignment);
13952   verifyFormat("a &= 5;\n"
13953                "bcd *= 5;\n"
13954                "ghtyf += 5;\n"
13955                "dvfvdb -= 5;\n"
13956                "a /= 5;\n"
13957                "vdsvsv %= 5;\n"
13958                "sfdbddfbdfbb ^= 5;\n"
13959                "dvsdsv |= 5;\n"
13960                "int dsvvdvsdvvv = 123;",
13961                Alignment);
13962   verifyFormat("int i = 1, j = 10;\n"
13963                "something = 2000;",
13964                Alignment);
13965   verifyFormat("something = 2000;\n"
13966                "int i = 1, j = 10;\n",
13967                Alignment);
13968   verifyFormat("something = 2000;\n"
13969                "another   = 911;\n"
13970                "int i = 1, j = 10;\n"
13971                "oneMore = 1;\n"
13972                "i       = 2;",
13973                Alignment);
13974   verifyFormat("int a   = 5;\n"
13975                "int one = 1;\n"
13976                "method();\n"
13977                "int oneTwoThree = 123;\n"
13978                "int oneTwo      = 12;",
13979                Alignment);
13980   verifyFormat("int oneTwoThree = 123;\n"
13981                "int oneTwo      = 12;\n"
13982                "method();\n",
13983                Alignment);
13984   verifyFormat("int oneTwoThree = 123; // comment\n"
13985                "int oneTwo      = 12;  // comment",
13986                Alignment);
13987 
13988   // Bug 25167
13989   /* Uncomment when fixed
13990     verifyFormat("#if A\n"
13991                  "#else\n"
13992                  "int aaaaaaaa = 12;\n"
13993                  "#endif\n"
13994                  "#if B\n"
13995                  "#else\n"
13996                  "int a = 12;\n"
13997                  "#endif\n",
13998                  Alignment);
13999     verifyFormat("enum foo {\n"
14000                  "#if A\n"
14001                  "#else\n"
14002                  "  aaaaaaaa = 12;\n"
14003                  "#endif\n"
14004                  "#if B\n"
14005                  "#else\n"
14006                  "  a = 12;\n"
14007                  "#endif\n"
14008                  "};\n",
14009                  Alignment);
14010   */
14011 
14012   Alignment.MaxEmptyLinesToKeep = 10;
14013   /* Test alignment across empty lines */
14014   EXPECT_EQ("int a           = 5;\n"
14015             "\n"
14016             "int oneTwoThree = 123;",
14017             format("int a       = 5;\n"
14018                    "\n"
14019                    "int oneTwoThree= 123;",
14020                    Alignment));
14021   EXPECT_EQ("int a           = 5;\n"
14022             "int one         = 1;\n"
14023             "\n"
14024             "int oneTwoThree = 123;",
14025             format("int a = 5;\n"
14026                    "int one = 1;\n"
14027                    "\n"
14028                    "int oneTwoThree = 123;",
14029                    Alignment));
14030   EXPECT_EQ("int a           = 5;\n"
14031             "int one         = 1;\n"
14032             "\n"
14033             "int oneTwoThree = 123;\n"
14034             "int oneTwo      = 12;",
14035             format("int a = 5;\n"
14036                    "int one = 1;\n"
14037                    "\n"
14038                    "int oneTwoThree = 123;\n"
14039                    "int oneTwo = 12;",
14040                    Alignment));
14041 
14042   /* Test across comments */
14043   EXPECT_EQ("int a           = 5;\n"
14044             "/* block comment */\n"
14045             "int oneTwoThree = 123;",
14046             format("int a = 5;\n"
14047                    "/* block comment */\n"
14048                    "int oneTwoThree=123;",
14049                    Alignment));
14050 
14051   EXPECT_EQ("int a           = 5;\n"
14052             "// line comment\n"
14053             "int oneTwoThree = 123;",
14054             format("int a = 5;\n"
14055                    "// line comment\n"
14056                    "int oneTwoThree=123;",
14057                    Alignment));
14058 
14059   /* Test across comments and newlines */
14060   EXPECT_EQ("int a           = 5;\n"
14061             "\n"
14062             "/* block comment */\n"
14063             "int oneTwoThree = 123;",
14064             format("int a = 5;\n"
14065                    "\n"
14066                    "/* block comment */\n"
14067                    "int oneTwoThree=123;",
14068                    Alignment));
14069 
14070   EXPECT_EQ("int a           = 5;\n"
14071             "\n"
14072             "// line comment\n"
14073             "int oneTwoThree = 123;",
14074             format("int a = 5;\n"
14075                    "\n"
14076                    "// line comment\n"
14077                    "int oneTwoThree=123;",
14078                    Alignment));
14079 
14080   EXPECT_EQ("int a           = 5;\n"
14081             "//\n"
14082             "// multi-line line comment\n"
14083             "//\n"
14084             "int oneTwoThree = 123;",
14085             format("int a = 5;\n"
14086                    "//\n"
14087                    "// multi-line line comment\n"
14088                    "//\n"
14089                    "int oneTwoThree=123;",
14090                    Alignment));
14091 
14092   EXPECT_EQ("int a           = 5;\n"
14093             "/*\n"
14094             " *  multi-line block comment\n"
14095             " */\n"
14096             "int oneTwoThree = 123;",
14097             format("int a = 5;\n"
14098                    "/*\n"
14099                    " *  multi-line block comment\n"
14100                    " */\n"
14101                    "int oneTwoThree=123;",
14102                    Alignment));
14103 
14104   EXPECT_EQ("int a           = 5;\n"
14105             "\n"
14106             "/* block comment */\n"
14107             "\n"
14108             "\n"
14109             "\n"
14110             "int oneTwoThree = 123;",
14111             format("int a = 5;\n"
14112                    "\n"
14113                    "/* block comment */\n"
14114                    "\n"
14115                    "\n"
14116                    "\n"
14117                    "int oneTwoThree=123;",
14118                    Alignment));
14119 
14120   EXPECT_EQ("int a           = 5;\n"
14121             "\n"
14122             "// line comment\n"
14123             "\n"
14124             "\n"
14125             "\n"
14126             "int oneTwoThree = 123;",
14127             format("int a = 5;\n"
14128                    "\n"
14129                    "// line comment\n"
14130                    "\n"
14131                    "\n"
14132                    "\n"
14133                    "int oneTwoThree=123;",
14134                    Alignment));
14135 
14136   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
14137   verifyFormat("#define A \\\n"
14138                "  int aaaa       = 12; \\\n"
14139                "  int b          = 23; \\\n"
14140                "  int ccc        = 234; \\\n"
14141                "  int dddddddddd = 2345;",
14142                Alignment);
14143   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14144   verifyFormat("#define A               \\\n"
14145                "  int aaaa       = 12;  \\\n"
14146                "  int b          = 23;  \\\n"
14147                "  int ccc        = 234; \\\n"
14148                "  int dddddddddd = 2345;",
14149                Alignment);
14150   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
14151   verifyFormat("#define A                                                      "
14152                "                \\\n"
14153                "  int aaaa       = 12;                                         "
14154                "                \\\n"
14155                "  int b          = 23;                                         "
14156                "                \\\n"
14157                "  int ccc        = 234;                                        "
14158                "                \\\n"
14159                "  int dddddddddd = 2345;",
14160                Alignment);
14161   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
14162                "k = 4, int l = 5,\n"
14163                "                  int m = 6) {\n"
14164                "  int j      = 10;\n"
14165                "  otherThing = 1;\n"
14166                "}",
14167                Alignment);
14168   verifyFormat("void SomeFunction(int parameter = 0) {\n"
14169                "  int i   = 1;\n"
14170                "  int j   = 2;\n"
14171                "  int big = 10000;\n"
14172                "}",
14173                Alignment);
14174   verifyFormat("class C {\n"
14175                "public:\n"
14176                "  int i            = 1;\n"
14177                "  virtual void f() = 0;\n"
14178                "};",
14179                Alignment);
14180   verifyFormat("int i = 1;\n"
14181                "if (SomeType t = getSomething()) {\n"
14182                "}\n"
14183                "int j   = 2;\n"
14184                "int big = 10000;",
14185                Alignment);
14186   verifyFormat("int j = 7;\n"
14187                "for (int k = 0; k < N; ++k) {\n"
14188                "}\n"
14189                "int j   = 2;\n"
14190                "int big = 10000;\n"
14191                "}",
14192                Alignment);
14193   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14194   verifyFormat("int i = 1;\n"
14195                "LooooooooooongType loooooooooooooooooooooongVariable\n"
14196                "    = someLooooooooooooooooongFunction();\n"
14197                "int j = 2;",
14198                Alignment);
14199   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
14200   verifyFormat("int i = 1;\n"
14201                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
14202                "    someLooooooooooooooooongFunction();\n"
14203                "int j = 2;",
14204                Alignment);
14205 
14206   verifyFormat("auto lambda = []() {\n"
14207                "  auto i = 0;\n"
14208                "  return 0;\n"
14209                "};\n"
14210                "int i  = 0;\n"
14211                "auto v = type{\n"
14212                "    i = 1,   //\n"
14213                "    (i = 2), //\n"
14214                "    i = 3    //\n"
14215                "};",
14216                Alignment);
14217 
14218   verifyFormat(
14219       "int i      = 1;\n"
14220       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
14221       "                          loooooooooooooooooooooongParameterB);\n"
14222       "int j      = 2;",
14223       Alignment);
14224 
14225   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
14226                "          typename B   = very_long_type_name_1,\n"
14227                "          typename T_2 = very_long_type_name_2>\n"
14228                "auto foo() {}\n",
14229                Alignment);
14230   verifyFormat("int a, b = 1;\n"
14231                "int c  = 2;\n"
14232                "int dd = 3;\n",
14233                Alignment);
14234   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
14235                "float b[1][] = {{3.f}};\n",
14236                Alignment);
14237   verifyFormat("for (int i = 0; i < 1; i++)\n"
14238                "  int x = 1;\n",
14239                Alignment);
14240   verifyFormat("for (i = 0; i < 1; i++)\n"
14241                "  x = 1;\n"
14242                "y = 1;\n",
14243                Alignment);
14244 
14245   Alignment.ReflowComments = true;
14246   Alignment.ColumnLimit = 50;
14247   EXPECT_EQ("int x   = 0;\n"
14248             "int yy  = 1; /// specificlennospace\n"
14249             "int zzz = 2;\n",
14250             format("int x   = 0;\n"
14251                    "int yy  = 1; ///specificlennospace\n"
14252                    "int zzz = 2;\n",
14253                    Alignment));
14254 }
14255 
14256 TEST_F(FormatTest, AlignConsecutiveAssignments) {
14257   FormatStyle Alignment = getLLVMStyle();
14258   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14259   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14260   verifyFormat("int a = 5;\n"
14261                "int oneTwoThree = 123;",
14262                Alignment);
14263   verifyFormat("int a = 5;\n"
14264                "int oneTwoThree = 123;",
14265                Alignment);
14266 
14267   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14268   verifyFormat("int a           = 5;\n"
14269                "int oneTwoThree = 123;",
14270                Alignment);
14271   verifyFormat("int a           = method();\n"
14272                "int oneTwoThree = 133;",
14273                Alignment);
14274   verifyFormat("a &= 5;\n"
14275                "bcd *= 5;\n"
14276                "ghtyf += 5;\n"
14277                "dvfvdb -= 5;\n"
14278                "a /= 5;\n"
14279                "vdsvsv %= 5;\n"
14280                "sfdbddfbdfbb ^= 5;\n"
14281                "dvsdsv |= 5;\n"
14282                "int dsvvdvsdvvv = 123;",
14283                Alignment);
14284   verifyFormat("int i = 1, j = 10;\n"
14285                "something = 2000;",
14286                Alignment);
14287   verifyFormat("something = 2000;\n"
14288                "int i = 1, j = 10;\n",
14289                Alignment);
14290   verifyFormat("something = 2000;\n"
14291                "another   = 911;\n"
14292                "int i = 1, j = 10;\n"
14293                "oneMore = 1;\n"
14294                "i       = 2;",
14295                Alignment);
14296   verifyFormat("int a   = 5;\n"
14297                "int one = 1;\n"
14298                "method();\n"
14299                "int oneTwoThree = 123;\n"
14300                "int oneTwo      = 12;",
14301                Alignment);
14302   verifyFormat("int oneTwoThree = 123;\n"
14303                "int oneTwo      = 12;\n"
14304                "method();\n",
14305                Alignment);
14306   verifyFormat("int oneTwoThree = 123; // comment\n"
14307                "int oneTwo      = 12;  // comment",
14308                Alignment);
14309 
14310   // Bug 25167
14311   /* Uncomment when fixed
14312     verifyFormat("#if A\n"
14313                  "#else\n"
14314                  "int aaaaaaaa = 12;\n"
14315                  "#endif\n"
14316                  "#if B\n"
14317                  "#else\n"
14318                  "int a = 12;\n"
14319                  "#endif\n",
14320                  Alignment);
14321     verifyFormat("enum foo {\n"
14322                  "#if A\n"
14323                  "#else\n"
14324                  "  aaaaaaaa = 12;\n"
14325                  "#endif\n"
14326                  "#if B\n"
14327                  "#else\n"
14328                  "  a = 12;\n"
14329                  "#endif\n"
14330                  "};\n",
14331                  Alignment);
14332   */
14333 
14334   EXPECT_EQ("int a = 5;\n"
14335             "\n"
14336             "int oneTwoThree = 123;",
14337             format("int a       = 5;\n"
14338                    "\n"
14339                    "int oneTwoThree= 123;",
14340                    Alignment));
14341   EXPECT_EQ("int a   = 5;\n"
14342             "int one = 1;\n"
14343             "\n"
14344             "int oneTwoThree = 123;",
14345             format("int a = 5;\n"
14346                    "int one = 1;\n"
14347                    "\n"
14348                    "int oneTwoThree = 123;",
14349                    Alignment));
14350   EXPECT_EQ("int a   = 5;\n"
14351             "int one = 1;\n"
14352             "\n"
14353             "int oneTwoThree = 123;\n"
14354             "int oneTwo      = 12;",
14355             format("int a = 5;\n"
14356                    "int one = 1;\n"
14357                    "\n"
14358                    "int oneTwoThree = 123;\n"
14359                    "int oneTwo = 12;",
14360                    Alignment));
14361   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
14362   verifyFormat("#define A \\\n"
14363                "  int aaaa       = 12; \\\n"
14364                "  int b          = 23; \\\n"
14365                "  int ccc        = 234; \\\n"
14366                "  int dddddddddd = 2345;",
14367                Alignment);
14368   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14369   verifyFormat("#define A               \\\n"
14370                "  int aaaa       = 12;  \\\n"
14371                "  int b          = 23;  \\\n"
14372                "  int ccc        = 234; \\\n"
14373                "  int dddddddddd = 2345;",
14374                Alignment);
14375   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
14376   verifyFormat("#define A                                                      "
14377                "                \\\n"
14378                "  int aaaa       = 12;                                         "
14379                "                \\\n"
14380                "  int b          = 23;                                         "
14381                "                \\\n"
14382                "  int ccc        = 234;                                        "
14383                "                \\\n"
14384                "  int dddddddddd = 2345;",
14385                Alignment);
14386   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
14387                "k = 4, int l = 5,\n"
14388                "                  int m = 6) {\n"
14389                "  int j      = 10;\n"
14390                "  otherThing = 1;\n"
14391                "}",
14392                Alignment);
14393   verifyFormat("void SomeFunction(int parameter = 0) {\n"
14394                "  int i   = 1;\n"
14395                "  int j   = 2;\n"
14396                "  int big = 10000;\n"
14397                "}",
14398                Alignment);
14399   verifyFormat("class C {\n"
14400                "public:\n"
14401                "  int i            = 1;\n"
14402                "  virtual void f() = 0;\n"
14403                "};",
14404                Alignment);
14405   verifyFormat("int i = 1;\n"
14406                "if (SomeType t = getSomething()) {\n"
14407                "}\n"
14408                "int j   = 2;\n"
14409                "int big = 10000;",
14410                Alignment);
14411   verifyFormat("int j = 7;\n"
14412                "for (int k = 0; k < N; ++k) {\n"
14413                "}\n"
14414                "int j   = 2;\n"
14415                "int big = 10000;\n"
14416                "}",
14417                Alignment);
14418   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14419   verifyFormat("int i = 1;\n"
14420                "LooooooooooongType loooooooooooooooooooooongVariable\n"
14421                "    = someLooooooooooooooooongFunction();\n"
14422                "int j = 2;",
14423                Alignment);
14424   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
14425   verifyFormat("int i = 1;\n"
14426                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
14427                "    someLooooooooooooooooongFunction();\n"
14428                "int j = 2;",
14429                Alignment);
14430 
14431   verifyFormat("auto lambda = []() {\n"
14432                "  auto i = 0;\n"
14433                "  return 0;\n"
14434                "};\n"
14435                "int i  = 0;\n"
14436                "auto v = type{\n"
14437                "    i = 1,   //\n"
14438                "    (i = 2), //\n"
14439                "    i = 3    //\n"
14440                "};",
14441                Alignment);
14442 
14443   verifyFormat(
14444       "int i      = 1;\n"
14445       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
14446       "                          loooooooooooooooooooooongParameterB);\n"
14447       "int j      = 2;",
14448       Alignment);
14449 
14450   verifyFormat("template <typename T, typename T_0 = very_long_type_name_0,\n"
14451                "          typename B   = very_long_type_name_1,\n"
14452                "          typename T_2 = very_long_type_name_2>\n"
14453                "auto foo() {}\n",
14454                Alignment);
14455   verifyFormat("int a, b = 1;\n"
14456                "int c  = 2;\n"
14457                "int dd = 3;\n",
14458                Alignment);
14459   verifyFormat("int aa       = ((1 > 2) ? 3 : 4);\n"
14460                "float b[1][] = {{3.f}};\n",
14461                Alignment);
14462   verifyFormat("for (int i = 0; i < 1; i++)\n"
14463                "  int x = 1;\n",
14464                Alignment);
14465   verifyFormat("for (i = 0; i < 1; i++)\n"
14466                "  x = 1;\n"
14467                "y = 1;\n",
14468                Alignment);
14469 
14470   Alignment.ReflowComments = true;
14471   Alignment.ColumnLimit = 50;
14472   EXPECT_EQ("int x   = 0;\n"
14473             "int yy  = 1; /// specificlennospace\n"
14474             "int zzz = 2;\n",
14475             format("int x   = 0;\n"
14476                    "int yy  = 1; ///specificlennospace\n"
14477                    "int zzz = 2;\n",
14478                    Alignment));
14479 }
14480 
14481 TEST_F(FormatTest, AlignConsecutiveBitFields) {
14482   FormatStyle Alignment = getLLVMStyle();
14483   Alignment.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
14484   verifyFormat("int const a     : 5;\n"
14485                "int oneTwoThree : 23;",
14486                Alignment);
14487 
14488   // Initializers are allowed starting with c++2a
14489   verifyFormat("int const a     : 5 = 1;\n"
14490                "int oneTwoThree : 23 = 0;",
14491                Alignment);
14492 
14493   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14494   verifyFormat("int const a           : 5;\n"
14495                "int       oneTwoThree : 23;",
14496                Alignment);
14497 
14498   verifyFormat("int const a           : 5;  // comment\n"
14499                "int       oneTwoThree : 23; // comment",
14500                Alignment);
14501 
14502   verifyFormat("int const a           : 5 = 1;\n"
14503                "int       oneTwoThree : 23 = 0;",
14504                Alignment);
14505 
14506   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14507   verifyFormat("int const a           : 5  = 1;\n"
14508                "int       oneTwoThree : 23 = 0;",
14509                Alignment);
14510   verifyFormat("int const a           : 5  = {1};\n"
14511                "int       oneTwoThree : 23 = 0;",
14512                Alignment);
14513 
14514   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_None;
14515   verifyFormat("int const a          :5;\n"
14516                "int       oneTwoThree:23;",
14517                Alignment);
14518 
14519   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_Before;
14520   verifyFormat("int const a           :5;\n"
14521                "int       oneTwoThree :23;",
14522                Alignment);
14523 
14524   Alignment.BitFieldColonSpacing = FormatStyle::BFCS_After;
14525   verifyFormat("int const a          : 5;\n"
14526                "int       oneTwoThree: 23;",
14527                Alignment);
14528 
14529   // Known limitations: ':' is only recognized as a bitfield colon when
14530   // followed by a number.
14531   /*
14532   verifyFormat("int oneTwoThree : SOME_CONSTANT;\n"
14533                "int a           : 5;",
14534                Alignment);
14535   */
14536 }
14537 
14538 TEST_F(FormatTest, AlignConsecutiveDeclarations) {
14539   FormatStyle Alignment = getLLVMStyle();
14540   Alignment.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
14541   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_None;
14542   verifyFormat("float const a = 5;\n"
14543                "int oneTwoThree = 123;",
14544                Alignment);
14545   verifyFormat("int a = 5;\n"
14546                "float const oneTwoThree = 123;",
14547                Alignment);
14548 
14549   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14550   verifyFormat("float const a = 5;\n"
14551                "int         oneTwoThree = 123;",
14552                Alignment);
14553   verifyFormat("int         a = method();\n"
14554                "float const oneTwoThree = 133;",
14555                Alignment);
14556   verifyFormat("int i = 1, j = 10;\n"
14557                "something = 2000;",
14558                Alignment);
14559   verifyFormat("something = 2000;\n"
14560                "int i = 1, j = 10;\n",
14561                Alignment);
14562   verifyFormat("float      something = 2000;\n"
14563                "double     another = 911;\n"
14564                "int        i = 1, j = 10;\n"
14565                "const int *oneMore = 1;\n"
14566                "unsigned   i = 2;",
14567                Alignment);
14568   verifyFormat("float a = 5;\n"
14569                "int   one = 1;\n"
14570                "method();\n"
14571                "const double       oneTwoThree = 123;\n"
14572                "const unsigned int oneTwo = 12;",
14573                Alignment);
14574   verifyFormat("int      oneTwoThree{0}; // comment\n"
14575                "unsigned oneTwo;         // comment",
14576                Alignment);
14577   verifyFormat("unsigned int *      a;\n"
14578                "int *               b;\n"
14579                "unsigned int Const *c;\n"
14580                "unsigned int const *d;\n"
14581                "unsigned int Const &e;\n"
14582                "unsigned int const &f;",
14583                Alignment);
14584   verifyFormat("Const unsigned int *c;\n"
14585                "const unsigned int *d;\n"
14586                "Const unsigned int &e;\n"
14587                "const unsigned int &f;\n"
14588                "const unsigned      g;\n"
14589                "Const unsigned      h;",
14590                Alignment);
14591   EXPECT_EQ("float const a = 5;\n"
14592             "\n"
14593             "int oneTwoThree = 123;",
14594             format("float const   a = 5;\n"
14595                    "\n"
14596                    "int           oneTwoThree= 123;",
14597                    Alignment));
14598   EXPECT_EQ("float a = 5;\n"
14599             "int   one = 1;\n"
14600             "\n"
14601             "unsigned oneTwoThree = 123;",
14602             format("float    a = 5;\n"
14603                    "int      one = 1;\n"
14604                    "\n"
14605                    "unsigned oneTwoThree = 123;",
14606                    Alignment));
14607   EXPECT_EQ("float a = 5;\n"
14608             "int   one = 1;\n"
14609             "\n"
14610             "unsigned oneTwoThree = 123;\n"
14611             "int      oneTwo = 12;",
14612             format("float    a = 5;\n"
14613                    "int one = 1;\n"
14614                    "\n"
14615                    "unsigned oneTwoThree = 123;\n"
14616                    "int oneTwo = 12;",
14617                    Alignment));
14618   // Function prototype alignment
14619   verifyFormat("int    a();\n"
14620                "double b();",
14621                Alignment);
14622   verifyFormat("int    a(int x);\n"
14623                "double b();",
14624                Alignment);
14625   unsigned OldColumnLimit = Alignment.ColumnLimit;
14626   // We need to set ColumnLimit to zero, in order to stress nested alignments,
14627   // otherwise the function parameters will be re-flowed onto a single line.
14628   Alignment.ColumnLimit = 0;
14629   EXPECT_EQ("int    a(int   x,\n"
14630             "         float y);\n"
14631             "double b(int    x,\n"
14632             "         double y);",
14633             format("int a(int x,\n"
14634                    " float y);\n"
14635                    "double b(int x,\n"
14636                    " double y);",
14637                    Alignment));
14638   // This ensures that function parameters of function declarations are
14639   // correctly indented when their owning functions are indented.
14640   // The failure case here is for 'double y' to not be indented enough.
14641   EXPECT_EQ("double a(int x);\n"
14642             "int    b(int    y,\n"
14643             "         double z);",
14644             format("double a(int x);\n"
14645                    "int b(int y,\n"
14646                    " double z);",
14647                    Alignment));
14648   // Set ColumnLimit low so that we induce wrapping immediately after
14649   // the function name and opening paren.
14650   Alignment.ColumnLimit = 13;
14651   verifyFormat("int function(\n"
14652                "    int  x,\n"
14653                "    bool y);",
14654                Alignment);
14655   Alignment.ColumnLimit = OldColumnLimit;
14656   // Ensure function pointers don't screw up recursive alignment
14657   verifyFormat("int    a(int x, void (*fp)(int y));\n"
14658                "double b();",
14659                Alignment);
14660   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14661   // Ensure recursive alignment is broken by function braces, so that the
14662   // "a = 1" does not align with subsequent assignments inside the function
14663   // body.
14664   verifyFormat("int func(int a = 1) {\n"
14665                "  int b  = 2;\n"
14666                "  int cc = 3;\n"
14667                "}",
14668                Alignment);
14669   verifyFormat("float      something = 2000;\n"
14670                "double     another   = 911;\n"
14671                "int        i = 1, j = 10;\n"
14672                "const int *oneMore = 1;\n"
14673                "unsigned   i       = 2;",
14674                Alignment);
14675   verifyFormat("int      oneTwoThree = {0}; // comment\n"
14676                "unsigned oneTwo      = 0;   // comment",
14677                Alignment);
14678   // Make sure that scope is correctly tracked, in the absence of braces
14679   verifyFormat("for (int i = 0; i < n; i++)\n"
14680                "  j = i;\n"
14681                "double x = 1;\n",
14682                Alignment);
14683   verifyFormat("if (int i = 0)\n"
14684                "  j = i;\n"
14685                "double x = 1;\n",
14686                Alignment);
14687   // Ensure operator[] and operator() are comprehended
14688   verifyFormat("struct test {\n"
14689                "  long long int foo();\n"
14690                "  int           operator[](int a);\n"
14691                "  double        bar();\n"
14692                "};\n",
14693                Alignment);
14694   verifyFormat("struct test {\n"
14695                "  long long int foo();\n"
14696                "  int           operator()(int a);\n"
14697                "  double        bar();\n"
14698                "};\n",
14699                Alignment);
14700   EXPECT_EQ("void SomeFunction(int parameter = 0) {\n"
14701             "  int const i   = 1;\n"
14702             "  int *     j   = 2;\n"
14703             "  int       big = 10000;\n"
14704             "\n"
14705             "  unsigned oneTwoThree = 123;\n"
14706             "  int      oneTwo      = 12;\n"
14707             "  method();\n"
14708             "  float k  = 2;\n"
14709             "  int   ll = 10000;\n"
14710             "}",
14711             format("void SomeFunction(int parameter= 0) {\n"
14712                    " int const  i= 1;\n"
14713                    "  int *j=2;\n"
14714                    " int big  =  10000;\n"
14715                    "\n"
14716                    "unsigned oneTwoThree  =123;\n"
14717                    "int oneTwo = 12;\n"
14718                    "  method();\n"
14719                    "float k= 2;\n"
14720                    "int ll=10000;\n"
14721                    "}",
14722                    Alignment));
14723   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14724   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_DontAlign;
14725   verifyFormat("#define A \\\n"
14726                "  int       aaaa = 12; \\\n"
14727                "  float     b = 23; \\\n"
14728                "  const int ccc = 234; \\\n"
14729                "  unsigned  dddddddddd = 2345;",
14730                Alignment);
14731   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Left;
14732   verifyFormat("#define A              \\\n"
14733                "  int       aaaa = 12; \\\n"
14734                "  float     b = 23;    \\\n"
14735                "  const int ccc = 234; \\\n"
14736                "  unsigned  dddddddddd = 2345;",
14737                Alignment);
14738   Alignment.AlignEscapedNewlines = FormatStyle::ENAS_Right;
14739   Alignment.ColumnLimit = 30;
14740   verifyFormat("#define A                    \\\n"
14741                "  int       aaaa = 12;       \\\n"
14742                "  float     b = 23;          \\\n"
14743                "  const int ccc = 234;       \\\n"
14744                "  int       dddddddddd = 2345;",
14745                Alignment);
14746   Alignment.ColumnLimit = 80;
14747   verifyFormat("void SomeFunction(int parameter = 1, int i = 2, int j = 3, int "
14748                "k = 4, int l = 5,\n"
14749                "                  int m = 6) {\n"
14750                "  const int j = 10;\n"
14751                "  otherThing = 1;\n"
14752                "}",
14753                Alignment);
14754   verifyFormat("void SomeFunction(int parameter = 0) {\n"
14755                "  int const i = 1;\n"
14756                "  int *     j = 2;\n"
14757                "  int       big = 10000;\n"
14758                "}",
14759                Alignment);
14760   verifyFormat("class C {\n"
14761                "public:\n"
14762                "  int          i = 1;\n"
14763                "  virtual void f() = 0;\n"
14764                "};",
14765                Alignment);
14766   verifyFormat("float i = 1;\n"
14767                "if (SomeType t = getSomething()) {\n"
14768                "}\n"
14769                "const unsigned j = 2;\n"
14770                "int            big = 10000;",
14771                Alignment);
14772   verifyFormat("float j = 7;\n"
14773                "for (int k = 0; k < N; ++k) {\n"
14774                "}\n"
14775                "unsigned j = 2;\n"
14776                "int      big = 10000;\n"
14777                "}",
14778                Alignment);
14779   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
14780   verifyFormat("float              i = 1;\n"
14781                "LooooooooooongType loooooooooooooooooooooongVariable\n"
14782                "    = someLooooooooooooooooongFunction();\n"
14783                "int j = 2;",
14784                Alignment);
14785   Alignment.BreakBeforeBinaryOperators = FormatStyle::BOS_None;
14786   verifyFormat("int                i = 1;\n"
14787                "LooooooooooongType loooooooooooooooooooooongVariable =\n"
14788                "    someLooooooooooooooooongFunction();\n"
14789                "int j = 2;",
14790                Alignment);
14791 
14792   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14793   verifyFormat("auto lambda = []() {\n"
14794                "  auto  ii = 0;\n"
14795                "  float j  = 0;\n"
14796                "  return 0;\n"
14797                "};\n"
14798                "int   i  = 0;\n"
14799                "float i2 = 0;\n"
14800                "auto  v  = type{\n"
14801                "    i = 1,   //\n"
14802                "    (i = 2), //\n"
14803                "    i = 3    //\n"
14804                "};",
14805                Alignment);
14806   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14807 
14808   verifyFormat(
14809       "int      i = 1;\n"
14810       "SomeType a = SomeFunction(looooooooooooooooooooooongParameterA,\n"
14811       "                          loooooooooooooooooooooongParameterB);\n"
14812       "int      j = 2;",
14813       Alignment);
14814 
14815   // Test interactions with ColumnLimit and AlignConsecutiveAssignments:
14816   // We expect declarations and assignments to align, as long as it doesn't
14817   // exceed the column limit, starting a new alignment sequence whenever it
14818   // happens.
14819   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14820   Alignment.ColumnLimit = 30;
14821   verifyFormat("float    ii              = 1;\n"
14822                "unsigned j               = 2;\n"
14823                "int someVerylongVariable = 1;\n"
14824                "AnotherLongType  ll = 123456;\n"
14825                "VeryVeryLongType k  = 2;\n"
14826                "int              myvar = 1;",
14827                Alignment);
14828   Alignment.ColumnLimit = 80;
14829   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14830 
14831   verifyFormat(
14832       "template <typename LongTemplate, typename VeryLongTemplateTypeName,\n"
14833       "          typename LongType, typename B>\n"
14834       "auto foo() {}\n",
14835       Alignment);
14836   verifyFormat("float a, b = 1;\n"
14837                "int   c = 2;\n"
14838                "int   dd = 3;\n",
14839                Alignment);
14840   verifyFormat("int   aa = ((1 > 2) ? 3 : 4);\n"
14841                "float b[1][] = {{3.f}};\n",
14842                Alignment);
14843   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14844   verifyFormat("float a, b = 1;\n"
14845                "int   c  = 2;\n"
14846                "int   dd = 3;\n",
14847                Alignment);
14848   verifyFormat("int   aa     = ((1 > 2) ? 3 : 4);\n"
14849                "float b[1][] = {{3.f}};\n",
14850                Alignment);
14851   Alignment.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14852 
14853   Alignment.ColumnLimit = 30;
14854   Alignment.BinPackParameters = false;
14855   verifyFormat("void foo(float     a,\n"
14856                "         float     b,\n"
14857                "         int       c,\n"
14858                "         uint32_t *d) {\n"
14859                "  int *  e = 0;\n"
14860                "  float  f = 0;\n"
14861                "  double g = 0;\n"
14862                "}\n"
14863                "void bar(ino_t     a,\n"
14864                "         int       b,\n"
14865                "         uint32_t *c,\n"
14866                "         bool      d) {}\n",
14867                Alignment);
14868   Alignment.BinPackParameters = true;
14869   Alignment.ColumnLimit = 80;
14870 
14871   // Bug 33507
14872   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
14873   verifyFormat(
14874       "auto found = range::find_if(vsProducts, [&](auto * aProduct) {\n"
14875       "  static const Version verVs2017;\n"
14876       "  return true;\n"
14877       "});\n",
14878       Alignment);
14879   Alignment.PointerAlignment = FormatStyle::PAS_Right;
14880 
14881   // See llvm.org/PR35641
14882   Alignment.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14883   verifyFormat("int func() { //\n"
14884                "  int      b;\n"
14885                "  unsigned c;\n"
14886                "}",
14887                Alignment);
14888 
14889   // See PR37175
14890   FormatStyle Style = getMozillaStyle();
14891   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14892   EXPECT_EQ("DECOR1 /**/ int8_t /**/ DECOR2 /**/\n"
14893             "foo(int a);",
14894             format("DECOR1 /**/ int8_t /**/ DECOR2 /**/ foo (int a);", Style));
14895 
14896   Alignment.PointerAlignment = FormatStyle::PAS_Left;
14897   verifyFormat("unsigned int*       a;\n"
14898                "int*                b;\n"
14899                "unsigned int Const* c;\n"
14900                "unsigned int const* d;\n"
14901                "unsigned int Const& e;\n"
14902                "unsigned int const& f;",
14903                Alignment);
14904   verifyFormat("Const unsigned int* c;\n"
14905                "const unsigned int* d;\n"
14906                "Const unsigned int& e;\n"
14907                "const unsigned int& f;\n"
14908                "const unsigned      g;\n"
14909                "Const unsigned      h;",
14910                Alignment);
14911 
14912   Alignment.PointerAlignment = FormatStyle::PAS_Middle;
14913   verifyFormat("unsigned int *       a;\n"
14914                "int *                b;\n"
14915                "unsigned int Const * c;\n"
14916                "unsigned int const * d;\n"
14917                "unsigned int Const & e;\n"
14918                "unsigned int const & f;",
14919                Alignment);
14920   verifyFormat("Const unsigned int * c;\n"
14921                "const unsigned int * d;\n"
14922                "Const unsigned int & e;\n"
14923                "const unsigned int & f;\n"
14924                "const unsigned       g;\n"
14925                "Const unsigned       h;",
14926                Alignment);
14927 }
14928 
14929 TEST_F(FormatTest, AlignWithLineBreaks) {
14930   auto Style = getLLVMStyleWithColumns(120);
14931 
14932   EXPECT_EQ(Style.AlignConsecutiveAssignments, FormatStyle::ACS_None);
14933   EXPECT_EQ(Style.AlignConsecutiveDeclarations, FormatStyle::ACS_None);
14934   verifyFormat("void foo() {\n"
14935                "  int myVar = 5;\n"
14936                "  double x = 3.14;\n"
14937                "  auto str = \"Hello \"\n"
14938                "             \"World\";\n"
14939                "  auto s = \"Hello \"\n"
14940                "           \"Again\";\n"
14941                "}",
14942                Style);
14943 
14944   // clang-format off
14945   verifyFormat("void foo() {\n"
14946                "  const int capacityBefore = Entries.capacity();\n"
14947                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14948                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14949                "  const X newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14950                "                                          std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14951                "}",
14952                Style);
14953   // clang-format on
14954 
14955   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
14956   verifyFormat("void foo() {\n"
14957                "  int myVar = 5;\n"
14958                "  double x  = 3.14;\n"
14959                "  auto str  = \"Hello \"\n"
14960                "              \"World\";\n"
14961                "  auto s    = \"Hello \"\n"
14962                "              \"Again\";\n"
14963                "}",
14964                Style);
14965 
14966   // clang-format off
14967   verifyFormat("void foo() {\n"
14968                "  const int capacityBefore = Entries.capacity();\n"
14969                "  const auto newEntry      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14970                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14971                "  const X newEntry2        = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14972                "                                                 std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14973                "}",
14974                Style);
14975   // clang-format on
14976 
14977   Style.AlignConsecutiveAssignments = FormatStyle::ACS_None;
14978   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
14979   verifyFormat("void foo() {\n"
14980                "  int    myVar = 5;\n"
14981                "  double x = 3.14;\n"
14982                "  auto   str = \"Hello \"\n"
14983                "               \"World\";\n"
14984                "  auto   s = \"Hello \"\n"
14985                "             \"Again\";\n"
14986                "}",
14987                Style);
14988 
14989   // clang-format off
14990   verifyFormat("void foo() {\n"
14991                "  const int  capacityBefore = Entries.capacity();\n"
14992                "  const auto newEntry = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14993                "                                            std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14994                "  const X    newEntry2 = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
14995                "                                             std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
14996                "}",
14997                Style);
14998   // clang-format on
14999 
15000   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
15001   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
15002 
15003   verifyFormat("void foo() {\n"
15004                "  int    myVar = 5;\n"
15005                "  double x     = 3.14;\n"
15006                "  auto   str   = \"Hello \"\n"
15007                "                 \"World\";\n"
15008                "  auto   s     = \"Hello \"\n"
15009                "                 \"Again\";\n"
15010                "}",
15011                Style);
15012 
15013   // clang-format off
15014   verifyFormat("void foo() {\n"
15015                "  const int  capacityBefore = Entries.capacity();\n"
15016                "  const auto newEntry       = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
15017                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
15018                "  const X    newEntry2      = Entries.emplaceHint(std::piecewise_construct, std::forward_as_tuple(uniqueId),\n"
15019                "                                                  std::forward_as_tuple(id, uniqueId, name, threadCreation));\n"
15020                "}",
15021                Style);
15022   // clang-format on
15023 }
15024 
15025 TEST_F(FormatTest, LinuxBraceBreaking) {
15026   FormatStyle LinuxBraceStyle = getLLVMStyle();
15027   LinuxBraceStyle.BreakBeforeBraces = FormatStyle::BS_Linux;
15028   verifyFormat("namespace a\n"
15029                "{\n"
15030                "class A\n"
15031                "{\n"
15032                "  void f()\n"
15033                "  {\n"
15034                "    if (true) {\n"
15035                "      a();\n"
15036                "      b();\n"
15037                "    } else {\n"
15038                "      a();\n"
15039                "    }\n"
15040                "  }\n"
15041                "  void g() { return; }\n"
15042                "};\n"
15043                "struct B {\n"
15044                "  int x;\n"
15045                "};\n"
15046                "} // namespace a\n",
15047                LinuxBraceStyle);
15048   verifyFormat("enum X {\n"
15049                "  Y = 0,\n"
15050                "}\n",
15051                LinuxBraceStyle);
15052   verifyFormat("struct S {\n"
15053                "  int Type;\n"
15054                "  union {\n"
15055                "    int x;\n"
15056                "    double y;\n"
15057                "  } Value;\n"
15058                "  class C\n"
15059                "  {\n"
15060                "    MyFavoriteType Value;\n"
15061                "  } Class;\n"
15062                "}\n",
15063                LinuxBraceStyle);
15064 }
15065 
15066 TEST_F(FormatTest, MozillaBraceBreaking) {
15067   FormatStyle MozillaBraceStyle = getLLVMStyle();
15068   MozillaBraceStyle.BreakBeforeBraces = FormatStyle::BS_Mozilla;
15069   MozillaBraceStyle.FixNamespaceComments = false;
15070   verifyFormat("namespace a {\n"
15071                "class A\n"
15072                "{\n"
15073                "  void f()\n"
15074                "  {\n"
15075                "    if (true) {\n"
15076                "      a();\n"
15077                "      b();\n"
15078                "    }\n"
15079                "  }\n"
15080                "  void g() { return; }\n"
15081                "};\n"
15082                "enum E\n"
15083                "{\n"
15084                "  A,\n"
15085                "  // foo\n"
15086                "  B,\n"
15087                "  C\n"
15088                "};\n"
15089                "struct B\n"
15090                "{\n"
15091                "  int x;\n"
15092                "};\n"
15093                "}\n",
15094                MozillaBraceStyle);
15095   verifyFormat("struct S\n"
15096                "{\n"
15097                "  int Type;\n"
15098                "  union\n"
15099                "  {\n"
15100                "    int x;\n"
15101                "    double y;\n"
15102                "  } Value;\n"
15103                "  class C\n"
15104                "  {\n"
15105                "    MyFavoriteType Value;\n"
15106                "  } Class;\n"
15107                "}\n",
15108                MozillaBraceStyle);
15109 }
15110 
15111 TEST_F(FormatTest, StroustrupBraceBreaking) {
15112   FormatStyle StroustrupBraceStyle = getLLVMStyle();
15113   StroustrupBraceStyle.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
15114   verifyFormat("namespace a {\n"
15115                "class A {\n"
15116                "  void f()\n"
15117                "  {\n"
15118                "    if (true) {\n"
15119                "      a();\n"
15120                "      b();\n"
15121                "    }\n"
15122                "  }\n"
15123                "  void g() { return; }\n"
15124                "};\n"
15125                "struct B {\n"
15126                "  int x;\n"
15127                "};\n"
15128                "} // namespace a\n",
15129                StroustrupBraceStyle);
15130 
15131   verifyFormat("void foo()\n"
15132                "{\n"
15133                "  if (a) {\n"
15134                "    a();\n"
15135                "  }\n"
15136                "  else {\n"
15137                "    b();\n"
15138                "  }\n"
15139                "}\n",
15140                StroustrupBraceStyle);
15141 
15142   verifyFormat("#ifdef _DEBUG\n"
15143                "int foo(int i = 0)\n"
15144                "#else\n"
15145                "int foo(int i = 5)\n"
15146                "#endif\n"
15147                "{\n"
15148                "  return i;\n"
15149                "}",
15150                StroustrupBraceStyle);
15151 
15152   verifyFormat("void foo() {}\n"
15153                "void bar()\n"
15154                "#ifdef _DEBUG\n"
15155                "{\n"
15156                "  foo();\n"
15157                "}\n"
15158                "#else\n"
15159                "{\n"
15160                "}\n"
15161                "#endif",
15162                StroustrupBraceStyle);
15163 
15164   verifyFormat("void foobar() { int i = 5; }\n"
15165                "#ifdef _DEBUG\n"
15166                "void bar() {}\n"
15167                "#else\n"
15168                "void bar() { foobar(); }\n"
15169                "#endif",
15170                StroustrupBraceStyle);
15171 }
15172 
15173 TEST_F(FormatTest, AllmanBraceBreaking) {
15174   FormatStyle AllmanBraceStyle = getLLVMStyle();
15175   AllmanBraceStyle.BreakBeforeBraces = FormatStyle::BS_Allman;
15176 
15177   EXPECT_EQ("namespace a\n"
15178             "{\n"
15179             "void f();\n"
15180             "void g();\n"
15181             "} // namespace a\n",
15182             format("namespace a\n"
15183                    "{\n"
15184                    "void f();\n"
15185                    "void g();\n"
15186                    "}\n",
15187                    AllmanBraceStyle));
15188 
15189   verifyFormat("namespace a\n"
15190                "{\n"
15191                "class A\n"
15192                "{\n"
15193                "  void f()\n"
15194                "  {\n"
15195                "    if (true)\n"
15196                "    {\n"
15197                "      a();\n"
15198                "      b();\n"
15199                "    }\n"
15200                "  }\n"
15201                "  void g() { return; }\n"
15202                "};\n"
15203                "struct B\n"
15204                "{\n"
15205                "  int x;\n"
15206                "};\n"
15207                "union C\n"
15208                "{\n"
15209                "};\n"
15210                "} // namespace a",
15211                AllmanBraceStyle);
15212 
15213   verifyFormat("void f()\n"
15214                "{\n"
15215                "  if (true)\n"
15216                "  {\n"
15217                "    a();\n"
15218                "  }\n"
15219                "  else if (false)\n"
15220                "  {\n"
15221                "    b();\n"
15222                "  }\n"
15223                "  else\n"
15224                "  {\n"
15225                "    c();\n"
15226                "  }\n"
15227                "}\n",
15228                AllmanBraceStyle);
15229 
15230   verifyFormat("void f()\n"
15231                "{\n"
15232                "  for (int i = 0; i < 10; ++i)\n"
15233                "  {\n"
15234                "    a();\n"
15235                "  }\n"
15236                "  while (false)\n"
15237                "  {\n"
15238                "    b();\n"
15239                "  }\n"
15240                "  do\n"
15241                "  {\n"
15242                "    c();\n"
15243                "  } while (false)\n"
15244                "}\n",
15245                AllmanBraceStyle);
15246 
15247   verifyFormat("void f(int a)\n"
15248                "{\n"
15249                "  switch (a)\n"
15250                "  {\n"
15251                "  case 0:\n"
15252                "    break;\n"
15253                "  case 1:\n"
15254                "  {\n"
15255                "    break;\n"
15256                "  }\n"
15257                "  case 2:\n"
15258                "  {\n"
15259                "  }\n"
15260                "  break;\n"
15261                "  default:\n"
15262                "    break;\n"
15263                "  }\n"
15264                "}\n",
15265                AllmanBraceStyle);
15266 
15267   verifyFormat("enum X\n"
15268                "{\n"
15269                "  Y = 0,\n"
15270                "}\n",
15271                AllmanBraceStyle);
15272   verifyFormat("enum X\n"
15273                "{\n"
15274                "  Y = 0\n"
15275                "}\n",
15276                AllmanBraceStyle);
15277 
15278   verifyFormat("@interface BSApplicationController ()\n"
15279                "{\n"
15280                "@private\n"
15281                "  id _extraIvar;\n"
15282                "}\n"
15283                "@end\n",
15284                AllmanBraceStyle);
15285 
15286   verifyFormat("#ifdef _DEBUG\n"
15287                "int foo(int i = 0)\n"
15288                "#else\n"
15289                "int foo(int i = 5)\n"
15290                "#endif\n"
15291                "{\n"
15292                "  return i;\n"
15293                "}",
15294                AllmanBraceStyle);
15295 
15296   verifyFormat("void foo() {}\n"
15297                "void bar()\n"
15298                "#ifdef _DEBUG\n"
15299                "{\n"
15300                "  foo();\n"
15301                "}\n"
15302                "#else\n"
15303                "{\n"
15304                "}\n"
15305                "#endif",
15306                AllmanBraceStyle);
15307 
15308   verifyFormat("void foobar() { int i = 5; }\n"
15309                "#ifdef _DEBUG\n"
15310                "void bar() {}\n"
15311                "#else\n"
15312                "void bar() { foobar(); }\n"
15313                "#endif",
15314                AllmanBraceStyle);
15315 
15316   EXPECT_EQ(AllmanBraceStyle.AllowShortLambdasOnASingleLine,
15317             FormatStyle::SLS_All);
15318 
15319   verifyFormat("[](int i) { return i + 2; };\n"
15320                "[](int i, int j)\n"
15321                "{\n"
15322                "  auto x = i + j;\n"
15323                "  auto y = i * j;\n"
15324                "  return x ^ y;\n"
15325                "};\n"
15326                "void foo()\n"
15327                "{\n"
15328                "  auto shortLambda = [](int i) { return i + 2; };\n"
15329                "  auto longLambda = [](int i, int j)\n"
15330                "  {\n"
15331                "    auto x = i + j;\n"
15332                "    auto y = i * j;\n"
15333                "    return x ^ y;\n"
15334                "  };\n"
15335                "}",
15336                AllmanBraceStyle);
15337 
15338   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
15339 
15340   verifyFormat("[](int i)\n"
15341                "{\n"
15342                "  return i + 2;\n"
15343                "};\n"
15344                "[](int i, int j)\n"
15345                "{\n"
15346                "  auto x = i + j;\n"
15347                "  auto y = i * j;\n"
15348                "  return x ^ y;\n"
15349                "};\n"
15350                "void foo()\n"
15351                "{\n"
15352                "  auto shortLambda = [](int i)\n"
15353                "  {\n"
15354                "    return i + 2;\n"
15355                "  };\n"
15356                "  auto longLambda = [](int i, int j)\n"
15357                "  {\n"
15358                "    auto x = i + j;\n"
15359                "    auto y = i * j;\n"
15360                "    return x ^ y;\n"
15361                "  };\n"
15362                "}",
15363                AllmanBraceStyle);
15364 
15365   // Reset
15366   AllmanBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_All;
15367 
15368   // This shouldn't affect ObjC blocks..
15369   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
15370                "  // ...\n"
15371                "  int i;\n"
15372                "}];",
15373                AllmanBraceStyle);
15374   verifyFormat("void (^block)(void) = ^{\n"
15375                "  // ...\n"
15376                "  int i;\n"
15377                "};",
15378                AllmanBraceStyle);
15379   // .. or dict literals.
15380   verifyFormat("void f()\n"
15381                "{\n"
15382                "  // ...\n"
15383                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
15384                "}",
15385                AllmanBraceStyle);
15386   verifyFormat("void f()\n"
15387                "{\n"
15388                "  // ...\n"
15389                "  [object someMethod:@{a : @\"b\"}];\n"
15390                "}",
15391                AllmanBraceStyle);
15392   verifyFormat("int f()\n"
15393                "{ // comment\n"
15394                "  return 42;\n"
15395                "}",
15396                AllmanBraceStyle);
15397 
15398   AllmanBraceStyle.ColumnLimit = 19;
15399   verifyFormat("void f() { int i; }", AllmanBraceStyle);
15400   AllmanBraceStyle.ColumnLimit = 18;
15401   verifyFormat("void f()\n"
15402                "{\n"
15403                "  int i;\n"
15404                "}",
15405                AllmanBraceStyle);
15406   AllmanBraceStyle.ColumnLimit = 80;
15407 
15408   FormatStyle BreakBeforeBraceShortIfs = AllmanBraceStyle;
15409   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
15410       FormatStyle::SIS_WithoutElse;
15411   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
15412   verifyFormat("void f(bool b)\n"
15413                "{\n"
15414                "  if (b)\n"
15415                "  {\n"
15416                "    return;\n"
15417                "  }\n"
15418                "}\n",
15419                BreakBeforeBraceShortIfs);
15420   verifyFormat("void f(bool b)\n"
15421                "{\n"
15422                "  if constexpr (b)\n"
15423                "  {\n"
15424                "    return;\n"
15425                "  }\n"
15426                "}\n",
15427                BreakBeforeBraceShortIfs);
15428   verifyFormat("void f(bool b)\n"
15429                "{\n"
15430                "  if CONSTEXPR (b)\n"
15431                "  {\n"
15432                "    return;\n"
15433                "  }\n"
15434                "}\n",
15435                BreakBeforeBraceShortIfs);
15436   verifyFormat("void f(bool b)\n"
15437                "{\n"
15438                "  if (b) return;\n"
15439                "}\n",
15440                BreakBeforeBraceShortIfs);
15441   verifyFormat("void f(bool b)\n"
15442                "{\n"
15443                "  if constexpr (b) return;\n"
15444                "}\n",
15445                BreakBeforeBraceShortIfs);
15446   verifyFormat("void f(bool b)\n"
15447                "{\n"
15448                "  if CONSTEXPR (b) return;\n"
15449                "}\n",
15450                BreakBeforeBraceShortIfs);
15451   verifyFormat("void f(bool b)\n"
15452                "{\n"
15453                "  while (b)\n"
15454                "  {\n"
15455                "    return;\n"
15456                "  }\n"
15457                "}\n",
15458                BreakBeforeBraceShortIfs);
15459 }
15460 
15461 TEST_F(FormatTest, WhitesmithsBraceBreaking) {
15462   FormatStyle WhitesmithsBraceStyle = getLLVMStyle();
15463   WhitesmithsBraceStyle.BreakBeforeBraces = FormatStyle::BS_Whitesmiths;
15464 
15465   // Make a few changes to the style for testing purposes
15466   WhitesmithsBraceStyle.AllowShortFunctionsOnASingleLine =
15467       FormatStyle::SFS_Empty;
15468   WhitesmithsBraceStyle.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
15469   WhitesmithsBraceStyle.ColumnLimit = 0;
15470 
15471   // FIXME: this test case can't decide whether there should be a blank line
15472   // after the ~D() line or not. It adds one if one doesn't exist in the test
15473   // and it removes the line if one exists.
15474   /*
15475   verifyFormat("class A;\n"
15476                "namespace B\n"
15477                "  {\n"
15478                "class C;\n"
15479                "// Comment\n"
15480                "class D\n"
15481                "  {\n"
15482                "public:\n"
15483                "  D();\n"
15484                "  ~D() {}\n"
15485                "private:\n"
15486                "  enum E\n"
15487                "    {\n"
15488                "    F\n"
15489                "    }\n"
15490                "  };\n"
15491                "  } // namespace B\n",
15492                WhitesmithsBraceStyle);
15493   */
15494 
15495   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_None;
15496   verifyFormat("namespace a\n"
15497                "  {\n"
15498                "class A\n"
15499                "  {\n"
15500                "  void f()\n"
15501                "    {\n"
15502                "    if (true)\n"
15503                "      {\n"
15504                "      a();\n"
15505                "      b();\n"
15506                "      }\n"
15507                "    }\n"
15508                "  void g()\n"
15509                "    {\n"
15510                "    return;\n"
15511                "    }\n"
15512                "  };\n"
15513                "struct B\n"
15514                "  {\n"
15515                "  int x;\n"
15516                "  };\n"
15517                "  } // namespace a",
15518                WhitesmithsBraceStyle);
15519 
15520   verifyFormat("namespace a\n"
15521                "  {\n"
15522                "namespace b\n"
15523                "  {\n"
15524                "class A\n"
15525                "  {\n"
15526                "  void f()\n"
15527                "    {\n"
15528                "    if (true)\n"
15529                "      {\n"
15530                "      a();\n"
15531                "      b();\n"
15532                "      }\n"
15533                "    }\n"
15534                "  void g()\n"
15535                "    {\n"
15536                "    return;\n"
15537                "    }\n"
15538                "  };\n"
15539                "struct B\n"
15540                "  {\n"
15541                "  int x;\n"
15542                "  };\n"
15543                "  } // namespace b\n"
15544                "  } // namespace a",
15545                WhitesmithsBraceStyle);
15546 
15547   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_Inner;
15548   verifyFormat("namespace a\n"
15549                "  {\n"
15550                "namespace b\n"
15551                "  {\n"
15552                "  class A\n"
15553                "    {\n"
15554                "    void f()\n"
15555                "      {\n"
15556                "      if (true)\n"
15557                "        {\n"
15558                "        a();\n"
15559                "        b();\n"
15560                "        }\n"
15561                "      }\n"
15562                "    void g()\n"
15563                "      {\n"
15564                "      return;\n"
15565                "      }\n"
15566                "    };\n"
15567                "  struct B\n"
15568                "    {\n"
15569                "    int x;\n"
15570                "    };\n"
15571                "  } // namespace b\n"
15572                "  } // namespace a",
15573                WhitesmithsBraceStyle);
15574 
15575   WhitesmithsBraceStyle.NamespaceIndentation = FormatStyle::NI_All;
15576   verifyFormat("namespace a\n"
15577                "  {\n"
15578                "  namespace b\n"
15579                "    {\n"
15580                "    class A\n"
15581                "      {\n"
15582                "      void f()\n"
15583                "        {\n"
15584                "        if (true)\n"
15585                "          {\n"
15586                "          a();\n"
15587                "          b();\n"
15588                "          }\n"
15589                "        }\n"
15590                "      void g()\n"
15591                "        {\n"
15592                "        return;\n"
15593                "        }\n"
15594                "      };\n"
15595                "    struct B\n"
15596                "      {\n"
15597                "      int x;\n"
15598                "      };\n"
15599                "    } // namespace b\n"
15600                "  }   // namespace a",
15601                WhitesmithsBraceStyle);
15602 
15603   verifyFormat("void f()\n"
15604                "  {\n"
15605                "  if (true)\n"
15606                "    {\n"
15607                "    a();\n"
15608                "    }\n"
15609                "  else if (false)\n"
15610                "    {\n"
15611                "    b();\n"
15612                "    }\n"
15613                "  else\n"
15614                "    {\n"
15615                "    c();\n"
15616                "    }\n"
15617                "  }\n",
15618                WhitesmithsBraceStyle);
15619 
15620   verifyFormat("void f()\n"
15621                "  {\n"
15622                "  for (int i = 0; i < 10; ++i)\n"
15623                "    {\n"
15624                "    a();\n"
15625                "    }\n"
15626                "  while (false)\n"
15627                "    {\n"
15628                "    b();\n"
15629                "    }\n"
15630                "  do\n"
15631                "    {\n"
15632                "    c();\n"
15633                "    } while (false)\n"
15634                "  }\n",
15635                WhitesmithsBraceStyle);
15636 
15637   WhitesmithsBraceStyle.IndentCaseLabels = true;
15638   verifyFormat("void switchTest1(int a)\n"
15639                "  {\n"
15640                "  switch (a)\n"
15641                "    {\n"
15642                "    case 2:\n"
15643                "      {\n"
15644                "      }\n"
15645                "      break;\n"
15646                "    }\n"
15647                "  }\n",
15648                WhitesmithsBraceStyle);
15649 
15650   verifyFormat("void switchTest2(int a)\n"
15651                "  {\n"
15652                "  switch (a)\n"
15653                "    {\n"
15654                "    case 0:\n"
15655                "      break;\n"
15656                "    case 1:\n"
15657                "      {\n"
15658                "      break;\n"
15659                "      }\n"
15660                "    case 2:\n"
15661                "      {\n"
15662                "      }\n"
15663                "      break;\n"
15664                "    default:\n"
15665                "      break;\n"
15666                "    }\n"
15667                "  }\n",
15668                WhitesmithsBraceStyle);
15669 
15670   verifyFormat("void switchTest3(int a)\n"
15671                "  {\n"
15672                "  switch (a)\n"
15673                "    {\n"
15674                "    case 0:\n"
15675                "      {\n"
15676                "      foo(x);\n"
15677                "      }\n"
15678                "      break;\n"
15679                "    default:\n"
15680                "      {\n"
15681                "      foo(1);\n"
15682                "      }\n"
15683                "      break;\n"
15684                "    }\n"
15685                "  }\n",
15686                WhitesmithsBraceStyle);
15687 
15688   WhitesmithsBraceStyle.IndentCaseLabels = false;
15689 
15690   verifyFormat("void switchTest4(int a)\n"
15691                "  {\n"
15692                "  switch (a)\n"
15693                "    {\n"
15694                "  case 2:\n"
15695                "    {\n"
15696                "    }\n"
15697                "    break;\n"
15698                "    }\n"
15699                "  }\n",
15700                WhitesmithsBraceStyle);
15701 
15702   verifyFormat("void switchTest5(int a)\n"
15703                "  {\n"
15704                "  switch (a)\n"
15705                "    {\n"
15706                "  case 0:\n"
15707                "    break;\n"
15708                "  case 1:\n"
15709                "    {\n"
15710                "    foo();\n"
15711                "    break;\n"
15712                "    }\n"
15713                "  case 2:\n"
15714                "    {\n"
15715                "    }\n"
15716                "    break;\n"
15717                "  default:\n"
15718                "    break;\n"
15719                "    }\n"
15720                "  }\n",
15721                WhitesmithsBraceStyle);
15722 
15723   verifyFormat("void switchTest6(int a)\n"
15724                "  {\n"
15725                "  switch (a)\n"
15726                "    {\n"
15727                "  case 0:\n"
15728                "    {\n"
15729                "    foo(x);\n"
15730                "    }\n"
15731                "    break;\n"
15732                "  default:\n"
15733                "    {\n"
15734                "    foo(1);\n"
15735                "    }\n"
15736                "    break;\n"
15737                "    }\n"
15738                "  }\n",
15739                WhitesmithsBraceStyle);
15740 
15741   verifyFormat("enum X\n"
15742                "  {\n"
15743                "  Y = 0, // testing\n"
15744                "  }\n",
15745                WhitesmithsBraceStyle);
15746 
15747   verifyFormat("enum X\n"
15748                "  {\n"
15749                "  Y = 0\n"
15750                "  }\n",
15751                WhitesmithsBraceStyle);
15752   verifyFormat("enum X\n"
15753                "  {\n"
15754                "  Y = 0,\n"
15755                "  Z = 1\n"
15756                "  };\n",
15757                WhitesmithsBraceStyle);
15758 
15759   verifyFormat("@interface BSApplicationController ()\n"
15760                "  {\n"
15761                "@private\n"
15762                "  id _extraIvar;\n"
15763                "  }\n"
15764                "@end\n",
15765                WhitesmithsBraceStyle);
15766 
15767   verifyFormat("#ifdef _DEBUG\n"
15768                "int foo(int i = 0)\n"
15769                "#else\n"
15770                "int foo(int i = 5)\n"
15771                "#endif\n"
15772                "  {\n"
15773                "  return i;\n"
15774                "  }",
15775                WhitesmithsBraceStyle);
15776 
15777   verifyFormat("void foo() {}\n"
15778                "void bar()\n"
15779                "#ifdef _DEBUG\n"
15780                "  {\n"
15781                "  foo();\n"
15782                "  }\n"
15783                "#else\n"
15784                "  {\n"
15785                "  }\n"
15786                "#endif",
15787                WhitesmithsBraceStyle);
15788 
15789   verifyFormat("void foobar()\n"
15790                "  {\n"
15791                "  int i = 5;\n"
15792                "  }\n"
15793                "#ifdef _DEBUG\n"
15794                "void bar()\n"
15795                "  {\n"
15796                "  }\n"
15797                "#else\n"
15798                "void bar()\n"
15799                "  {\n"
15800                "  foobar();\n"
15801                "  }\n"
15802                "#endif",
15803                WhitesmithsBraceStyle);
15804 
15805   // This shouldn't affect ObjC blocks..
15806   verifyFormat("[self doSomeThingWithACompletionHandler:^{\n"
15807                "  // ...\n"
15808                "  int i;\n"
15809                "}];",
15810                WhitesmithsBraceStyle);
15811   verifyFormat("void (^block)(void) = ^{\n"
15812                "  // ...\n"
15813                "  int i;\n"
15814                "};",
15815                WhitesmithsBraceStyle);
15816   // .. or dict literals.
15817   verifyFormat("void f()\n"
15818                "  {\n"
15819                "  [object someMethod:@{@\"a\" : @\"b\"}];\n"
15820                "  }",
15821                WhitesmithsBraceStyle);
15822 
15823   verifyFormat("int f()\n"
15824                "  { // comment\n"
15825                "  return 42;\n"
15826                "  }",
15827                WhitesmithsBraceStyle);
15828 
15829   FormatStyle BreakBeforeBraceShortIfs = WhitesmithsBraceStyle;
15830   BreakBeforeBraceShortIfs.AllowShortIfStatementsOnASingleLine =
15831       FormatStyle::SIS_Always;
15832   BreakBeforeBraceShortIfs.AllowShortLoopsOnASingleLine = true;
15833   verifyFormat("void f(bool b)\n"
15834                "  {\n"
15835                "  if (b)\n"
15836                "    {\n"
15837                "    return;\n"
15838                "    }\n"
15839                "  }\n",
15840                BreakBeforeBraceShortIfs);
15841   verifyFormat("void f(bool b)\n"
15842                "  {\n"
15843                "  if (b) return;\n"
15844                "  }\n",
15845                BreakBeforeBraceShortIfs);
15846   verifyFormat("void f(bool b)\n"
15847                "  {\n"
15848                "  while (b)\n"
15849                "    {\n"
15850                "    return;\n"
15851                "    }\n"
15852                "  }\n",
15853                BreakBeforeBraceShortIfs);
15854 }
15855 
15856 TEST_F(FormatTest, GNUBraceBreaking) {
15857   FormatStyle GNUBraceStyle = getLLVMStyle();
15858   GNUBraceStyle.BreakBeforeBraces = FormatStyle::BS_GNU;
15859   verifyFormat("namespace a\n"
15860                "{\n"
15861                "class A\n"
15862                "{\n"
15863                "  void f()\n"
15864                "  {\n"
15865                "    int a;\n"
15866                "    {\n"
15867                "      int b;\n"
15868                "    }\n"
15869                "    if (true)\n"
15870                "      {\n"
15871                "        a();\n"
15872                "        b();\n"
15873                "      }\n"
15874                "  }\n"
15875                "  void g() { return; }\n"
15876                "}\n"
15877                "} // namespace a",
15878                GNUBraceStyle);
15879 
15880   verifyFormat("void f()\n"
15881                "{\n"
15882                "  if (true)\n"
15883                "    {\n"
15884                "      a();\n"
15885                "    }\n"
15886                "  else if (false)\n"
15887                "    {\n"
15888                "      b();\n"
15889                "    }\n"
15890                "  else\n"
15891                "    {\n"
15892                "      c();\n"
15893                "    }\n"
15894                "}\n",
15895                GNUBraceStyle);
15896 
15897   verifyFormat("void f()\n"
15898                "{\n"
15899                "  for (int i = 0; i < 10; ++i)\n"
15900                "    {\n"
15901                "      a();\n"
15902                "    }\n"
15903                "  while (false)\n"
15904                "    {\n"
15905                "      b();\n"
15906                "    }\n"
15907                "  do\n"
15908                "    {\n"
15909                "      c();\n"
15910                "    }\n"
15911                "  while (false);\n"
15912                "}\n",
15913                GNUBraceStyle);
15914 
15915   verifyFormat("void f(int a)\n"
15916                "{\n"
15917                "  switch (a)\n"
15918                "    {\n"
15919                "    case 0:\n"
15920                "      break;\n"
15921                "    case 1:\n"
15922                "      {\n"
15923                "        break;\n"
15924                "      }\n"
15925                "    case 2:\n"
15926                "      {\n"
15927                "      }\n"
15928                "      break;\n"
15929                "    default:\n"
15930                "      break;\n"
15931                "    }\n"
15932                "}\n",
15933                GNUBraceStyle);
15934 
15935   verifyFormat("enum X\n"
15936                "{\n"
15937                "  Y = 0,\n"
15938                "}\n",
15939                GNUBraceStyle);
15940 
15941   verifyFormat("@interface BSApplicationController ()\n"
15942                "{\n"
15943                "@private\n"
15944                "  id _extraIvar;\n"
15945                "}\n"
15946                "@end\n",
15947                GNUBraceStyle);
15948 
15949   verifyFormat("#ifdef _DEBUG\n"
15950                "int foo(int i = 0)\n"
15951                "#else\n"
15952                "int foo(int i = 5)\n"
15953                "#endif\n"
15954                "{\n"
15955                "  return i;\n"
15956                "}",
15957                GNUBraceStyle);
15958 
15959   verifyFormat("void foo() {}\n"
15960                "void bar()\n"
15961                "#ifdef _DEBUG\n"
15962                "{\n"
15963                "  foo();\n"
15964                "}\n"
15965                "#else\n"
15966                "{\n"
15967                "}\n"
15968                "#endif",
15969                GNUBraceStyle);
15970 
15971   verifyFormat("void foobar() { int i = 5; }\n"
15972                "#ifdef _DEBUG\n"
15973                "void bar() {}\n"
15974                "#else\n"
15975                "void bar() { foobar(); }\n"
15976                "#endif",
15977                GNUBraceStyle);
15978 }
15979 
15980 TEST_F(FormatTest, WebKitBraceBreaking) {
15981   FormatStyle WebKitBraceStyle = getLLVMStyle();
15982   WebKitBraceStyle.BreakBeforeBraces = FormatStyle::BS_WebKit;
15983   WebKitBraceStyle.FixNamespaceComments = false;
15984   verifyFormat("namespace a {\n"
15985                "class A {\n"
15986                "  void f()\n"
15987                "  {\n"
15988                "    if (true) {\n"
15989                "      a();\n"
15990                "      b();\n"
15991                "    }\n"
15992                "  }\n"
15993                "  void g() { return; }\n"
15994                "};\n"
15995                "enum E {\n"
15996                "  A,\n"
15997                "  // foo\n"
15998                "  B,\n"
15999                "  C\n"
16000                "};\n"
16001                "struct B {\n"
16002                "  int x;\n"
16003                "};\n"
16004                "}\n",
16005                WebKitBraceStyle);
16006   verifyFormat("struct S {\n"
16007                "  int Type;\n"
16008                "  union {\n"
16009                "    int x;\n"
16010                "    double y;\n"
16011                "  } Value;\n"
16012                "  class C {\n"
16013                "    MyFavoriteType Value;\n"
16014                "  } Class;\n"
16015                "};\n",
16016                WebKitBraceStyle);
16017 }
16018 
16019 TEST_F(FormatTest, CatchExceptionReferenceBinding) {
16020   verifyFormat("void f() {\n"
16021                "  try {\n"
16022                "  } catch (const Exception &e) {\n"
16023                "  }\n"
16024                "}\n",
16025                getLLVMStyle());
16026 }
16027 
16028 TEST_F(FormatTest, UnderstandsPragmas) {
16029   verifyFormat("#pragma omp reduction(| : var)");
16030   verifyFormat("#pragma omp reduction(+ : var)");
16031 
16032   EXPECT_EQ("#pragma mark Any non-hyphenated or hyphenated string "
16033             "(including parentheses).",
16034             format("#pragma    mark   Any non-hyphenated or hyphenated string "
16035                    "(including parentheses)."));
16036 }
16037 
16038 TEST_F(FormatTest, UnderstandPragmaOption) {
16039   verifyFormat("#pragma option -C -A");
16040 
16041   EXPECT_EQ("#pragma option -C -A", format("#pragma    option   -C   -A"));
16042 }
16043 
16044 TEST_F(FormatTest, OptimizeBreakPenaltyVsExcess) {
16045   FormatStyle Style = getLLVMStyle();
16046   Style.ColumnLimit = 20;
16047 
16048   // See PR41213
16049   EXPECT_EQ("/*\n"
16050             " *\t9012345\n"
16051             " * /8901\n"
16052             " */",
16053             format("/*\n"
16054                    " *\t9012345 /8901\n"
16055                    " */",
16056                    Style));
16057   EXPECT_EQ("/*\n"
16058             " *345678\n"
16059             " *\t/8901\n"
16060             " */",
16061             format("/*\n"
16062                    " *345678\t/8901\n"
16063                    " */",
16064                    Style));
16065 
16066   verifyFormat("int a; // the\n"
16067                "       // comment",
16068                Style);
16069   EXPECT_EQ("int a; /* first line\n"
16070             "        * second\n"
16071             "        * line third\n"
16072             "        * line\n"
16073             "        */",
16074             format("int a; /* first line\n"
16075                    "        * second\n"
16076                    "        * line third\n"
16077                    "        * line\n"
16078                    "        */",
16079                    Style));
16080   EXPECT_EQ("int a; // first line\n"
16081             "       // second\n"
16082             "       // line third\n"
16083             "       // line",
16084             format("int a; // first line\n"
16085                    "       // second line\n"
16086                    "       // third line",
16087                    Style));
16088 
16089   Style.PenaltyExcessCharacter = 90;
16090   verifyFormat("int a; // the comment", Style);
16091   EXPECT_EQ("int a; // the comment\n"
16092             "       // aaa",
16093             format("int a; // the comment aaa", Style));
16094   EXPECT_EQ("int a; /* first line\n"
16095             "        * second line\n"
16096             "        * third line\n"
16097             "        */",
16098             format("int a; /* first line\n"
16099                    "        * second line\n"
16100                    "        * third line\n"
16101                    "        */",
16102                    Style));
16103   EXPECT_EQ("int a; // first line\n"
16104             "       // second line\n"
16105             "       // third line",
16106             format("int a; // first line\n"
16107                    "       // second line\n"
16108                    "       // third line",
16109                    Style));
16110   // FIXME: Investigate why this is not getting the same layout as the test
16111   // above.
16112   EXPECT_EQ("int a; /* first line\n"
16113             "        * second line\n"
16114             "        * third line\n"
16115             "        */",
16116             format("int a; /* first line second line third line"
16117                    "\n*/",
16118                    Style));
16119 
16120   EXPECT_EQ("// foo bar baz bazfoo\n"
16121             "// foo bar foo bar\n",
16122             format("// foo bar baz bazfoo\n"
16123                    "// foo bar foo           bar\n",
16124                    Style));
16125   EXPECT_EQ("// foo bar baz bazfoo\n"
16126             "// foo bar foo bar\n",
16127             format("// foo bar baz      bazfoo\n"
16128                    "// foo            bar foo bar\n",
16129                    Style));
16130 
16131   // FIXME: Optimally, we'd keep bazfoo on the first line and reflow bar to the
16132   // next one.
16133   EXPECT_EQ("// foo bar baz bazfoo\n"
16134             "// bar foo bar\n",
16135             format("// foo bar baz      bazfoo bar\n"
16136                    "// foo            bar\n",
16137                    Style));
16138 
16139   EXPECT_EQ("// foo bar baz bazfoo\n"
16140             "// foo bar baz bazfoo\n"
16141             "// bar foo bar\n",
16142             format("// foo bar baz      bazfoo\n"
16143                    "// foo bar baz      bazfoo bar\n"
16144                    "// foo bar\n",
16145                    Style));
16146 
16147   EXPECT_EQ("// foo bar baz bazfoo\n"
16148             "// foo bar baz bazfoo\n"
16149             "// bar foo bar\n",
16150             format("// foo bar baz      bazfoo\n"
16151                    "// foo bar baz      bazfoo bar\n"
16152                    "// foo           bar\n",
16153                    Style));
16154 
16155   // Make sure we do not keep protruding characters if strict mode reflow is
16156   // cheaper than keeping protruding characters.
16157   Style.ColumnLimit = 21;
16158   EXPECT_EQ(
16159       "// foo foo foo foo\n"
16160       "// foo foo foo foo\n"
16161       "// foo foo foo foo\n",
16162       format("// foo foo foo foo foo foo foo foo foo foo foo foo\n", Style));
16163 
16164   EXPECT_EQ("int a = /* long block\n"
16165             "           comment */\n"
16166             "    42;",
16167             format("int a = /* long block comment */ 42;", Style));
16168 }
16169 
16170 #define EXPECT_ALL_STYLES_EQUAL(Styles)                                        \
16171   for (size_t i = 1; i < Styles.size(); ++i)                                   \
16172   EXPECT_EQ(Styles[0], Styles[i])                                              \
16173       << "Style #" << i << " of " << Styles.size() << " differs from Style #0"
16174 
16175 TEST_F(FormatTest, GetsPredefinedStyleByName) {
16176   SmallVector<FormatStyle, 3> Styles;
16177   Styles.resize(3);
16178 
16179   Styles[0] = getLLVMStyle();
16180   EXPECT_TRUE(getPredefinedStyle("LLVM", FormatStyle::LK_Cpp, &Styles[1]));
16181   EXPECT_TRUE(getPredefinedStyle("lLvM", FormatStyle::LK_Cpp, &Styles[2]));
16182   EXPECT_ALL_STYLES_EQUAL(Styles);
16183 
16184   Styles[0] = getGoogleStyle();
16185   EXPECT_TRUE(getPredefinedStyle("Google", FormatStyle::LK_Cpp, &Styles[1]));
16186   EXPECT_TRUE(getPredefinedStyle("gOOgle", FormatStyle::LK_Cpp, &Styles[2]));
16187   EXPECT_ALL_STYLES_EQUAL(Styles);
16188 
16189   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
16190   EXPECT_TRUE(
16191       getPredefinedStyle("Google", FormatStyle::LK_JavaScript, &Styles[1]));
16192   EXPECT_TRUE(
16193       getPredefinedStyle("gOOgle", FormatStyle::LK_JavaScript, &Styles[2]));
16194   EXPECT_ALL_STYLES_EQUAL(Styles);
16195 
16196   Styles[0] = getChromiumStyle(FormatStyle::LK_Cpp);
16197   EXPECT_TRUE(getPredefinedStyle("Chromium", FormatStyle::LK_Cpp, &Styles[1]));
16198   EXPECT_TRUE(getPredefinedStyle("cHRoMiUM", FormatStyle::LK_Cpp, &Styles[2]));
16199   EXPECT_ALL_STYLES_EQUAL(Styles);
16200 
16201   Styles[0] = getMozillaStyle();
16202   EXPECT_TRUE(getPredefinedStyle("Mozilla", FormatStyle::LK_Cpp, &Styles[1]));
16203   EXPECT_TRUE(getPredefinedStyle("moZILla", FormatStyle::LK_Cpp, &Styles[2]));
16204   EXPECT_ALL_STYLES_EQUAL(Styles);
16205 
16206   Styles[0] = getWebKitStyle();
16207   EXPECT_TRUE(getPredefinedStyle("WebKit", FormatStyle::LK_Cpp, &Styles[1]));
16208   EXPECT_TRUE(getPredefinedStyle("wEbKit", FormatStyle::LK_Cpp, &Styles[2]));
16209   EXPECT_ALL_STYLES_EQUAL(Styles);
16210 
16211   Styles[0] = getGNUStyle();
16212   EXPECT_TRUE(getPredefinedStyle("GNU", FormatStyle::LK_Cpp, &Styles[1]));
16213   EXPECT_TRUE(getPredefinedStyle("gnU", FormatStyle::LK_Cpp, &Styles[2]));
16214   EXPECT_ALL_STYLES_EQUAL(Styles);
16215 
16216   EXPECT_FALSE(getPredefinedStyle("qwerty", FormatStyle::LK_Cpp, &Styles[0]));
16217 }
16218 
16219 TEST_F(FormatTest, GetsCorrectBasedOnStyle) {
16220   SmallVector<FormatStyle, 8> Styles;
16221   Styles.resize(2);
16222 
16223   Styles[0] = getGoogleStyle();
16224   Styles[1] = getLLVMStyle();
16225   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
16226   EXPECT_ALL_STYLES_EQUAL(Styles);
16227 
16228   Styles.resize(5);
16229   Styles[0] = getGoogleStyle(FormatStyle::LK_JavaScript);
16230   Styles[1] = getLLVMStyle();
16231   Styles[1].Language = FormatStyle::LK_JavaScript;
16232   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Styles[1]).value());
16233 
16234   Styles[2] = getLLVMStyle();
16235   Styles[2].Language = FormatStyle::LK_JavaScript;
16236   EXPECT_EQ(0, parseConfiguration("Language: JavaScript\n"
16237                                   "BasedOnStyle: Google",
16238                                   &Styles[2])
16239                    .value());
16240 
16241   Styles[3] = getLLVMStyle();
16242   Styles[3].Language = FormatStyle::LK_JavaScript;
16243   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google\n"
16244                                   "Language: JavaScript",
16245                                   &Styles[3])
16246                    .value());
16247 
16248   Styles[4] = getLLVMStyle();
16249   Styles[4].Language = FormatStyle::LK_JavaScript;
16250   EXPECT_EQ(0, parseConfiguration("---\n"
16251                                   "BasedOnStyle: LLVM\n"
16252                                   "IndentWidth: 123\n"
16253                                   "---\n"
16254                                   "BasedOnStyle: Google\n"
16255                                   "Language: JavaScript",
16256                                   &Styles[4])
16257                    .value());
16258   EXPECT_ALL_STYLES_EQUAL(Styles);
16259 }
16260 
16261 #define CHECK_PARSE_BOOL_FIELD(FIELD, CONFIG_NAME)                             \
16262   Style.FIELD = false;                                                         \
16263   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": true", &Style).value());      \
16264   EXPECT_TRUE(Style.FIELD);                                                    \
16265   EXPECT_EQ(0, parseConfiguration(CONFIG_NAME ": false", &Style).value());     \
16266   EXPECT_FALSE(Style.FIELD);
16267 
16268 #define CHECK_PARSE_BOOL(FIELD) CHECK_PARSE_BOOL_FIELD(FIELD, #FIELD)
16269 
16270 #define CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, CONFIG_NAME)              \
16271   Style.STRUCT.FIELD = false;                                                  \
16272   EXPECT_EQ(0,                                                                 \
16273             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": true", &Style)   \
16274                 .value());                                                     \
16275   EXPECT_TRUE(Style.STRUCT.FIELD);                                             \
16276   EXPECT_EQ(0,                                                                 \
16277             parseConfiguration(#STRUCT ":\n  " CONFIG_NAME ": false", &Style)  \
16278                 .value());                                                     \
16279   EXPECT_FALSE(Style.STRUCT.FIELD);
16280 
16281 #define CHECK_PARSE_NESTED_BOOL(STRUCT, FIELD)                                 \
16282   CHECK_PARSE_NESTED_BOOL_FIELD(STRUCT, FIELD, #FIELD)
16283 
16284 #define CHECK_PARSE(TEXT, FIELD, VALUE)                                        \
16285   EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";          \
16286   EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());                      \
16287   EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
16288 
16289 TEST_F(FormatTest, ParsesConfigurationBools) {
16290   FormatStyle Style = {};
16291   Style.Language = FormatStyle::LK_Cpp;
16292   CHECK_PARSE_BOOL(AlignTrailingComments);
16293   CHECK_PARSE_BOOL(AllowAllArgumentsOnNextLine);
16294   CHECK_PARSE_BOOL(AllowAllConstructorInitializersOnNextLine);
16295   CHECK_PARSE_BOOL(AllowAllParametersOfDeclarationOnNextLine);
16296   CHECK_PARSE_BOOL(AllowShortCaseLabelsOnASingleLine);
16297   CHECK_PARSE_BOOL(AllowShortEnumsOnASingleLine);
16298   CHECK_PARSE_BOOL(AllowShortLoopsOnASingleLine);
16299   CHECK_PARSE_BOOL(BinPackArguments);
16300   CHECK_PARSE_BOOL(BinPackParameters);
16301   CHECK_PARSE_BOOL(BreakAfterJavaFieldAnnotations);
16302   CHECK_PARSE_BOOL(BreakBeforeConceptDeclarations);
16303   CHECK_PARSE_BOOL(BreakBeforeTernaryOperators);
16304   CHECK_PARSE_BOOL(BreakStringLiterals);
16305   CHECK_PARSE_BOOL(CompactNamespaces);
16306   CHECK_PARSE_BOOL(ConstructorInitializerAllOnOneLineOrOnePerLine);
16307   CHECK_PARSE_BOOL(DeriveLineEnding);
16308   CHECK_PARSE_BOOL(DerivePointerAlignment);
16309   CHECK_PARSE_BOOL_FIELD(DerivePointerAlignment, "DerivePointerBinding");
16310   CHECK_PARSE_BOOL(DisableFormat);
16311   CHECK_PARSE_BOOL(IndentAccessModifiers);
16312   CHECK_PARSE_BOOL(IndentCaseLabels);
16313   CHECK_PARSE_BOOL(IndentCaseBlocks);
16314   CHECK_PARSE_BOOL(IndentGotoLabels);
16315   CHECK_PARSE_BOOL(IndentRequires);
16316   CHECK_PARSE_BOOL(IndentWrappedFunctionNames);
16317   CHECK_PARSE_BOOL(KeepEmptyLinesAtTheStartOfBlocks);
16318   CHECK_PARSE_BOOL(ObjCSpaceAfterProperty);
16319   CHECK_PARSE_BOOL(ObjCSpaceBeforeProtocolList);
16320   CHECK_PARSE_BOOL(Cpp11BracedListStyle);
16321   CHECK_PARSE_BOOL(ReflowComments);
16322   CHECK_PARSE_BOOL(SortUsingDeclarations);
16323   CHECK_PARSE_BOOL(SpacesInParentheses);
16324   CHECK_PARSE_BOOL(SpacesInSquareBrackets);
16325   CHECK_PARSE_BOOL(SpacesInAngles);
16326   CHECK_PARSE_BOOL(SpacesInConditionalStatement);
16327   CHECK_PARSE_BOOL(SpaceInEmptyBlock);
16328   CHECK_PARSE_BOOL(SpaceInEmptyParentheses);
16329   CHECK_PARSE_BOOL(SpacesInContainerLiterals);
16330   CHECK_PARSE_BOOL(SpacesInCStyleCastParentheses);
16331   CHECK_PARSE_BOOL(SpaceAfterCStyleCast);
16332   CHECK_PARSE_BOOL(SpaceAfterTemplateKeyword);
16333   CHECK_PARSE_BOOL(SpaceAfterLogicalNot);
16334   CHECK_PARSE_BOOL(SpaceBeforeAssignmentOperators);
16335   CHECK_PARSE_BOOL(SpaceBeforeCaseColon);
16336   CHECK_PARSE_BOOL(SpaceBeforeCpp11BracedList);
16337   CHECK_PARSE_BOOL(SpaceBeforeCtorInitializerColon);
16338   CHECK_PARSE_BOOL(SpaceBeforeInheritanceColon);
16339   CHECK_PARSE_BOOL(SpaceBeforeRangeBasedForLoopColon);
16340   CHECK_PARSE_BOOL(SpaceBeforeSquareBrackets);
16341   CHECK_PARSE_BOOL(UseCRLF);
16342 
16343   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterCaseLabel);
16344   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterClass);
16345   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterEnum);
16346   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterFunction);
16347   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterNamespace);
16348   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterObjCDeclaration);
16349   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterStruct);
16350   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterUnion);
16351   CHECK_PARSE_NESTED_BOOL(BraceWrapping, AfterExternBlock);
16352   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeCatch);
16353   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeElse);
16354   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeLambdaBody);
16355   CHECK_PARSE_NESTED_BOOL(BraceWrapping, BeforeWhile);
16356   CHECK_PARSE_NESTED_BOOL(BraceWrapping, IndentBraces);
16357   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyFunction);
16358   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyRecord);
16359   CHECK_PARSE_NESTED_BOOL(BraceWrapping, SplitEmptyNamespace);
16360 }
16361 
16362 #undef CHECK_PARSE_BOOL
16363 
16364 TEST_F(FormatTest, ParsesConfiguration) {
16365   FormatStyle Style = {};
16366   Style.Language = FormatStyle::LK_Cpp;
16367   CHECK_PARSE("AccessModifierOffset: -1234", AccessModifierOffset, -1234);
16368   CHECK_PARSE("ConstructorInitializerIndentWidth: 1234",
16369               ConstructorInitializerIndentWidth, 1234u);
16370   CHECK_PARSE("ObjCBlockIndentWidth: 1234", ObjCBlockIndentWidth, 1234u);
16371   CHECK_PARSE("ColumnLimit: 1234", ColumnLimit, 1234u);
16372   CHECK_PARSE("MaxEmptyLinesToKeep: 1234", MaxEmptyLinesToKeep, 1234u);
16373   CHECK_PARSE("PenaltyBreakAssignment: 1234", PenaltyBreakAssignment, 1234u);
16374   CHECK_PARSE("PenaltyBreakBeforeFirstCallParameter: 1234",
16375               PenaltyBreakBeforeFirstCallParameter, 1234u);
16376   CHECK_PARSE("PenaltyBreakTemplateDeclaration: 1234",
16377               PenaltyBreakTemplateDeclaration, 1234u);
16378   CHECK_PARSE("PenaltyExcessCharacter: 1234", PenaltyExcessCharacter, 1234u);
16379   CHECK_PARSE("PenaltyReturnTypeOnItsOwnLine: 1234",
16380               PenaltyReturnTypeOnItsOwnLine, 1234u);
16381   CHECK_PARSE("SpacesBeforeTrailingComments: 1234",
16382               SpacesBeforeTrailingComments, 1234u);
16383   CHECK_PARSE("IndentWidth: 32", IndentWidth, 32u);
16384   CHECK_PARSE("ContinuationIndentWidth: 11", ContinuationIndentWidth, 11u);
16385   CHECK_PARSE("CommentPragmas: '// abc$'", CommentPragmas, "// abc$");
16386 
16387   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
16388   CHECK_PARSE("AlignConsecutiveAssignments: None", AlignConsecutiveAssignments,
16389               FormatStyle::ACS_None);
16390   CHECK_PARSE("AlignConsecutiveAssignments: Consecutive",
16391               AlignConsecutiveAssignments, FormatStyle::ACS_Consecutive);
16392   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLines",
16393               AlignConsecutiveAssignments, FormatStyle::ACS_AcrossEmptyLines);
16394   CHECK_PARSE("AlignConsecutiveAssignments: AcrossEmptyLinesAndComments",
16395               AlignConsecutiveAssignments,
16396               FormatStyle::ACS_AcrossEmptyLinesAndComments);
16397   // For backwards compability, false / true should still parse
16398   CHECK_PARSE("AlignConsecutiveAssignments: false", AlignConsecutiveAssignments,
16399               FormatStyle::ACS_None);
16400   CHECK_PARSE("AlignConsecutiveAssignments: true", AlignConsecutiveAssignments,
16401               FormatStyle::ACS_Consecutive);
16402 
16403   Style.AlignConsecutiveBitFields = FormatStyle::ACS_Consecutive;
16404   CHECK_PARSE("AlignConsecutiveBitFields: None", AlignConsecutiveBitFields,
16405               FormatStyle::ACS_None);
16406   CHECK_PARSE("AlignConsecutiveBitFields: Consecutive",
16407               AlignConsecutiveBitFields, FormatStyle::ACS_Consecutive);
16408   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLines",
16409               AlignConsecutiveBitFields, FormatStyle::ACS_AcrossEmptyLines);
16410   CHECK_PARSE("AlignConsecutiveBitFields: AcrossEmptyLinesAndComments",
16411               AlignConsecutiveBitFields,
16412               FormatStyle::ACS_AcrossEmptyLinesAndComments);
16413   // For backwards compability, false / true should still parse
16414   CHECK_PARSE("AlignConsecutiveBitFields: false", AlignConsecutiveBitFields,
16415               FormatStyle::ACS_None);
16416   CHECK_PARSE("AlignConsecutiveBitFields: true", AlignConsecutiveBitFields,
16417               FormatStyle::ACS_Consecutive);
16418 
16419   Style.AlignConsecutiveMacros = FormatStyle::ACS_Consecutive;
16420   CHECK_PARSE("AlignConsecutiveMacros: None", AlignConsecutiveMacros,
16421               FormatStyle::ACS_None);
16422   CHECK_PARSE("AlignConsecutiveMacros: Consecutive", AlignConsecutiveMacros,
16423               FormatStyle::ACS_Consecutive);
16424   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLines",
16425               AlignConsecutiveMacros, FormatStyle::ACS_AcrossEmptyLines);
16426   CHECK_PARSE("AlignConsecutiveMacros: AcrossEmptyLinesAndComments",
16427               AlignConsecutiveMacros,
16428               FormatStyle::ACS_AcrossEmptyLinesAndComments);
16429   // For backwards compability, false / true should still parse
16430   CHECK_PARSE("AlignConsecutiveMacros: false", AlignConsecutiveMacros,
16431               FormatStyle::ACS_None);
16432   CHECK_PARSE("AlignConsecutiveMacros: true", AlignConsecutiveMacros,
16433               FormatStyle::ACS_Consecutive);
16434 
16435   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
16436   CHECK_PARSE("AlignConsecutiveDeclarations: None",
16437               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
16438   CHECK_PARSE("AlignConsecutiveDeclarations: Consecutive",
16439               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
16440   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLines",
16441               AlignConsecutiveDeclarations, FormatStyle::ACS_AcrossEmptyLines);
16442   CHECK_PARSE("AlignConsecutiveDeclarations: AcrossEmptyLinesAndComments",
16443               AlignConsecutiveDeclarations,
16444               FormatStyle::ACS_AcrossEmptyLinesAndComments);
16445   // For backwards compability, false / true should still parse
16446   CHECK_PARSE("AlignConsecutiveDeclarations: false",
16447               AlignConsecutiveDeclarations, FormatStyle::ACS_None);
16448   CHECK_PARSE("AlignConsecutiveDeclarations: true",
16449               AlignConsecutiveDeclarations, FormatStyle::ACS_Consecutive);
16450 
16451   Style.PointerAlignment = FormatStyle::PAS_Middle;
16452   CHECK_PARSE("PointerAlignment: Left", PointerAlignment,
16453               FormatStyle::PAS_Left);
16454   CHECK_PARSE("PointerAlignment: Right", PointerAlignment,
16455               FormatStyle::PAS_Right);
16456   CHECK_PARSE("PointerAlignment: Middle", PointerAlignment,
16457               FormatStyle::PAS_Middle);
16458   // For backward compatibility:
16459   CHECK_PARSE("PointerBindsToType: Left", PointerAlignment,
16460               FormatStyle::PAS_Left);
16461   CHECK_PARSE("PointerBindsToType: Right", PointerAlignment,
16462               FormatStyle::PAS_Right);
16463   CHECK_PARSE("PointerBindsToType: Middle", PointerAlignment,
16464               FormatStyle::PAS_Middle);
16465 
16466   Style.Standard = FormatStyle::LS_Auto;
16467   CHECK_PARSE("Standard: c++03", Standard, FormatStyle::LS_Cpp03);
16468   CHECK_PARSE("Standard: c++11", Standard, FormatStyle::LS_Cpp11);
16469   CHECK_PARSE("Standard: c++14", Standard, FormatStyle::LS_Cpp14);
16470   CHECK_PARSE("Standard: c++17", Standard, FormatStyle::LS_Cpp17);
16471   CHECK_PARSE("Standard: c++20", Standard, FormatStyle::LS_Cpp20);
16472   CHECK_PARSE("Standard: Auto", Standard, FormatStyle::LS_Auto);
16473   CHECK_PARSE("Standard: Latest", Standard, FormatStyle::LS_Latest);
16474   // Legacy aliases:
16475   CHECK_PARSE("Standard: Cpp03", Standard, FormatStyle::LS_Cpp03);
16476   CHECK_PARSE("Standard: Cpp11", Standard, FormatStyle::LS_Latest);
16477   CHECK_PARSE("Standard: C++03", Standard, FormatStyle::LS_Cpp03);
16478   CHECK_PARSE("Standard: C++11", Standard, FormatStyle::LS_Cpp11);
16479 
16480   Style.BreakBeforeBinaryOperators = FormatStyle::BOS_All;
16481   CHECK_PARSE("BreakBeforeBinaryOperators: NonAssignment",
16482               BreakBeforeBinaryOperators, FormatStyle::BOS_NonAssignment);
16483   CHECK_PARSE("BreakBeforeBinaryOperators: None", BreakBeforeBinaryOperators,
16484               FormatStyle::BOS_None);
16485   CHECK_PARSE("BreakBeforeBinaryOperators: All", BreakBeforeBinaryOperators,
16486               FormatStyle::BOS_All);
16487   // For backward compatibility:
16488   CHECK_PARSE("BreakBeforeBinaryOperators: false", BreakBeforeBinaryOperators,
16489               FormatStyle::BOS_None);
16490   CHECK_PARSE("BreakBeforeBinaryOperators: true", BreakBeforeBinaryOperators,
16491               FormatStyle::BOS_All);
16492 
16493   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
16494   CHECK_PARSE("BreakConstructorInitializers: BeforeComma",
16495               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
16496   CHECK_PARSE("BreakConstructorInitializers: AfterColon",
16497               BreakConstructorInitializers, FormatStyle::BCIS_AfterColon);
16498   CHECK_PARSE("BreakConstructorInitializers: BeforeColon",
16499               BreakConstructorInitializers, FormatStyle::BCIS_BeforeColon);
16500   // For backward compatibility:
16501   CHECK_PARSE("BreakConstructorInitializersBeforeComma: true",
16502               BreakConstructorInitializers, FormatStyle::BCIS_BeforeComma);
16503 
16504   Style.BreakInheritanceList = FormatStyle::BILS_BeforeColon;
16505   CHECK_PARSE("BreakInheritanceList: BeforeComma", BreakInheritanceList,
16506               FormatStyle::BILS_BeforeComma);
16507   CHECK_PARSE("BreakInheritanceList: AfterColon", BreakInheritanceList,
16508               FormatStyle::BILS_AfterColon);
16509   CHECK_PARSE("BreakInheritanceList: BeforeColon", BreakInheritanceList,
16510               FormatStyle::BILS_BeforeColon);
16511   // For backward compatibility:
16512   CHECK_PARSE("BreakBeforeInheritanceComma: true", BreakInheritanceList,
16513               FormatStyle::BILS_BeforeComma);
16514 
16515   Style.EmptyLineBeforeAccessModifier = FormatStyle::ELBAMS_LogicalBlock;
16516   CHECK_PARSE("EmptyLineBeforeAccessModifier: Never",
16517               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Never);
16518   CHECK_PARSE("EmptyLineBeforeAccessModifier: Leave",
16519               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Leave);
16520   CHECK_PARSE("EmptyLineBeforeAccessModifier: LogicalBlock",
16521               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_LogicalBlock);
16522   CHECK_PARSE("EmptyLineBeforeAccessModifier: Always",
16523               EmptyLineBeforeAccessModifier, FormatStyle::ELBAMS_Always);
16524 
16525   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
16526   CHECK_PARSE("AlignAfterOpenBracket: Align", AlignAfterOpenBracket,
16527               FormatStyle::BAS_Align);
16528   CHECK_PARSE("AlignAfterOpenBracket: DontAlign", AlignAfterOpenBracket,
16529               FormatStyle::BAS_DontAlign);
16530   CHECK_PARSE("AlignAfterOpenBracket: AlwaysBreak", AlignAfterOpenBracket,
16531               FormatStyle::BAS_AlwaysBreak);
16532   // For backward compatibility:
16533   CHECK_PARSE("AlignAfterOpenBracket: false", AlignAfterOpenBracket,
16534               FormatStyle::BAS_DontAlign);
16535   CHECK_PARSE("AlignAfterOpenBracket: true", AlignAfterOpenBracket,
16536               FormatStyle::BAS_Align);
16537 
16538   Style.AlignEscapedNewlines = FormatStyle::ENAS_Left;
16539   CHECK_PARSE("AlignEscapedNewlines: DontAlign", AlignEscapedNewlines,
16540               FormatStyle::ENAS_DontAlign);
16541   CHECK_PARSE("AlignEscapedNewlines: Left", AlignEscapedNewlines,
16542               FormatStyle::ENAS_Left);
16543   CHECK_PARSE("AlignEscapedNewlines: Right", AlignEscapedNewlines,
16544               FormatStyle::ENAS_Right);
16545   // For backward compatibility:
16546   CHECK_PARSE("AlignEscapedNewlinesLeft: true", AlignEscapedNewlines,
16547               FormatStyle::ENAS_Left);
16548   CHECK_PARSE("AlignEscapedNewlinesLeft: false", AlignEscapedNewlines,
16549               FormatStyle::ENAS_Right);
16550 
16551   Style.AlignOperands = FormatStyle::OAS_Align;
16552   CHECK_PARSE("AlignOperands: DontAlign", AlignOperands,
16553               FormatStyle::OAS_DontAlign);
16554   CHECK_PARSE("AlignOperands: Align", AlignOperands, FormatStyle::OAS_Align);
16555   CHECK_PARSE("AlignOperands: AlignAfterOperator", AlignOperands,
16556               FormatStyle::OAS_AlignAfterOperator);
16557   // For backward compatibility:
16558   CHECK_PARSE("AlignOperands: false", AlignOperands,
16559               FormatStyle::OAS_DontAlign);
16560   CHECK_PARSE("AlignOperands: true", AlignOperands, FormatStyle::OAS_Align);
16561 
16562   Style.UseTab = FormatStyle::UT_ForIndentation;
16563   CHECK_PARSE("UseTab: Never", UseTab, FormatStyle::UT_Never);
16564   CHECK_PARSE("UseTab: ForIndentation", UseTab, FormatStyle::UT_ForIndentation);
16565   CHECK_PARSE("UseTab: Always", UseTab, FormatStyle::UT_Always);
16566   CHECK_PARSE("UseTab: ForContinuationAndIndentation", UseTab,
16567               FormatStyle::UT_ForContinuationAndIndentation);
16568   CHECK_PARSE("UseTab: AlignWithSpaces", UseTab,
16569               FormatStyle::UT_AlignWithSpaces);
16570   // For backward compatibility:
16571   CHECK_PARSE("UseTab: false", UseTab, FormatStyle::UT_Never);
16572   CHECK_PARSE("UseTab: true", UseTab, FormatStyle::UT_Always);
16573 
16574   Style.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Empty;
16575   CHECK_PARSE("AllowShortBlocksOnASingleLine: Never",
16576               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
16577   CHECK_PARSE("AllowShortBlocksOnASingleLine: Empty",
16578               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Empty);
16579   CHECK_PARSE("AllowShortBlocksOnASingleLine: Always",
16580               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
16581   // For backward compatibility:
16582   CHECK_PARSE("AllowShortBlocksOnASingleLine: false",
16583               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Never);
16584   CHECK_PARSE("AllowShortBlocksOnASingleLine: true",
16585               AllowShortBlocksOnASingleLine, FormatStyle::SBS_Always);
16586 
16587   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_Inline;
16588   CHECK_PARSE("AllowShortFunctionsOnASingleLine: None",
16589               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
16590   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Inline",
16591               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Inline);
16592   CHECK_PARSE("AllowShortFunctionsOnASingleLine: Empty",
16593               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_Empty);
16594   CHECK_PARSE("AllowShortFunctionsOnASingleLine: All",
16595               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
16596   // For backward compatibility:
16597   CHECK_PARSE("AllowShortFunctionsOnASingleLine: false",
16598               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_None);
16599   CHECK_PARSE("AllowShortFunctionsOnASingleLine: true",
16600               AllowShortFunctionsOnASingleLine, FormatStyle::SFS_All);
16601 
16602   Style.SpaceAroundPointerQualifiers = FormatStyle::SAPQ_Both;
16603   CHECK_PARSE("SpaceAroundPointerQualifiers: Default",
16604               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Default);
16605   CHECK_PARSE("SpaceAroundPointerQualifiers: Before",
16606               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Before);
16607   CHECK_PARSE("SpaceAroundPointerQualifiers: After",
16608               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_After);
16609   CHECK_PARSE("SpaceAroundPointerQualifiers: Both",
16610               SpaceAroundPointerQualifiers, FormatStyle::SAPQ_Both);
16611 
16612   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
16613   CHECK_PARSE("SpaceBeforeParens: Never", SpaceBeforeParens,
16614               FormatStyle::SBPO_Never);
16615   CHECK_PARSE("SpaceBeforeParens: Always", SpaceBeforeParens,
16616               FormatStyle::SBPO_Always);
16617   CHECK_PARSE("SpaceBeforeParens: ControlStatements", SpaceBeforeParens,
16618               FormatStyle::SBPO_ControlStatements);
16619   CHECK_PARSE("SpaceBeforeParens: NonEmptyParentheses", SpaceBeforeParens,
16620               FormatStyle::SBPO_NonEmptyParentheses);
16621   // For backward compatibility:
16622   CHECK_PARSE("SpaceAfterControlStatementKeyword: false", SpaceBeforeParens,
16623               FormatStyle::SBPO_Never);
16624   CHECK_PARSE("SpaceAfterControlStatementKeyword: true", SpaceBeforeParens,
16625               FormatStyle::SBPO_ControlStatements);
16626 
16627   Style.ColumnLimit = 123;
16628   FormatStyle BaseStyle = getLLVMStyle();
16629   CHECK_PARSE("BasedOnStyle: LLVM", ColumnLimit, BaseStyle.ColumnLimit);
16630   CHECK_PARSE("BasedOnStyle: LLVM\nColumnLimit: 1234", ColumnLimit, 1234u);
16631 
16632   Style.BreakBeforeBraces = FormatStyle::BS_Stroustrup;
16633   CHECK_PARSE("BreakBeforeBraces: Attach", BreakBeforeBraces,
16634               FormatStyle::BS_Attach);
16635   CHECK_PARSE("BreakBeforeBraces: Linux", BreakBeforeBraces,
16636               FormatStyle::BS_Linux);
16637   CHECK_PARSE("BreakBeforeBraces: Mozilla", BreakBeforeBraces,
16638               FormatStyle::BS_Mozilla);
16639   CHECK_PARSE("BreakBeforeBraces: Stroustrup", BreakBeforeBraces,
16640               FormatStyle::BS_Stroustrup);
16641   CHECK_PARSE("BreakBeforeBraces: Allman", BreakBeforeBraces,
16642               FormatStyle::BS_Allman);
16643   CHECK_PARSE("BreakBeforeBraces: Whitesmiths", BreakBeforeBraces,
16644               FormatStyle::BS_Whitesmiths);
16645   CHECK_PARSE("BreakBeforeBraces: GNU", BreakBeforeBraces, FormatStyle::BS_GNU);
16646   CHECK_PARSE("BreakBeforeBraces: WebKit", BreakBeforeBraces,
16647               FormatStyle::BS_WebKit);
16648   CHECK_PARSE("BreakBeforeBraces: Custom", BreakBeforeBraces,
16649               FormatStyle::BS_Custom);
16650 
16651   Style.BraceWrapping.AfterControlStatement = FormatStyle::BWACS_Never;
16652   CHECK_PARSE("BraceWrapping:\n"
16653               "  AfterControlStatement: MultiLine",
16654               BraceWrapping.AfterControlStatement,
16655               FormatStyle::BWACS_MultiLine);
16656   CHECK_PARSE("BraceWrapping:\n"
16657               "  AfterControlStatement: Always",
16658               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
16659   CHECK_PARSE("BraceWrapping:\n"
16660               "  AfterControlStatement: Never",
16661               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
16662   // For backward compatibility:
16663   CHECK_PARSE("BraceWrapping:\n"
16664               "  AfterControlStatement: true",
16665               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Always);
16666   CHECK_PARSE("BraceWrapping:\n"
16667               "  AfterControlStatement: false",
16668               BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
16669 
16670   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
16671   CHECK_PARSE("AlwaysBreakAfterReturnType: None", AlwaysBreakAfterReturnType,
16672               FormatStyle::RTBS_None);
16673   CHECK_PARSE("AlwaysBreakAfterReturnType: All", AlwaysBreakAfterReturnType,
16674               FormatStyle::RTBS_All);
16675   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevel",
16676               AlwaysBreakAfterReturnType, FormatStyle::RTBS_TopLevel);
16677   CHECK_PARSE("AlwaysBreakAfterReturnType: AllDefinitions",
16678               AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
16679   CHECK_PARSE("AlwaysBreakAfterReturnType: TopLevelDefinitions",
16680               AlwaysBreakAfterReturnType,
16681               FormatStyle::RTBS_TopLevelDefinitions);
16682 
16683   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
16684   CHECK_PARSE("AlwaysBreakTemplateDeclarations: No",
16685               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_No);
16686   CHECK_PARSE("AlwaysBreakTemplateDeclarations: MultiLine",
16687               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
16688   CHECK_PARSE("AlwaysBreakTemplateDeclarations: Yes",
16689               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
16690   CHECK_PARSE("AlwaysBreakTemplateDeclarations: false",
16691               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_MultiLine);
16692   CHECK_PARSE("AlwaysBreakTemplateDeclarations: true",
16693               AlwaysBreakTemplateDeclarations, FormatStyle::BTDS_Yes);
16694 
16695   Style.AlwaysBreakAfterDefinitionReturnType = FormatStyle::DRTBS_All;
16696   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: None",
16697               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_None);
16698   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: All",
16699               AlwaysBreakAfterDefinitionReturnType, FormatStyle::DRTBS_All);
16700   CHECK_PARSE("AlwaysBreakAfterDefinitionReturnType: TopLevel",
16701               AlwaysBreakAfterDefinitionReturnType,
16702               FormatStyle::DRTBS_TopLevel);
16703 
16704   Style.NamespaceIndentation = FormatStyle::NI_All;
16705   CHECK_PARSE("NamespaceIndentation: None", NamespaceIndentation,
16706               FormatStyle::NI_None);
16707   CHECK_PARSE("NamespaceIndentation: Inner", NamespaceIndentation,
16708               FormatStyle::NI_Inner);
16709   CHECK_PARSE("NamespaceIndentation: All", NamespaceIndentation,
16710               FormatStyle::NI_All);
16711 
16712   Style.AllowShortIfStatementsOnASingleLine = FormatStyle::SIS_Always;
16713   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Never",
16714               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
16715   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: WithoutElse",
16716               AllowShortIfStatementsOnASingleLine,
16717               FormatStyle::SIS_WithoutElse);
16718   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: Always",
16719               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Always);
16720   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: false",
16721               AllowShortIfStatementsOnASingleLine, FormatStyle::SIS_Never);
16722   CHECK_PARSE("AllowShortIfStatementsOnASingleLine: true",
16723               AllowShortIfStatementsOnASingleLine,
16724               FormatStyle::SIS_WithoutElse);
16725 
16726   Style.IndentExternBlock = FormatStyle::IEBS_NoIndent;
16727   CHECK_PARSE("IndentExternBlock: AfterExternBlock", IndentExternBlock,
16728               FormatStyle::IEBS_AfterExternBlock);
16729   CHECK_PARSE("IndentExternBlock: Indent", IndentExternBlock,
16730               FormatStyle::IEBS_Indent);
16731   CHECK_PARSE("IndentExternBlock: NoIndent", IndentExternBlock,
16732               FormatStyle::IEBS_NoIndent);
16733   CHECK_PARSE("IndentExternBlock: true", IndentExternBlock,
16734               FormatStyle::IEBS_Indent);
16735   CHECK_PARSE("IndentExternBlock: false", IndentExternBlock,
16736               FormatStyle::IEBS_NoIndent);
16737 
16738   Style.BitFieldColonSpacing = FormatStyle::BFCS_None;
16739   CHECK_PARSE("BitFieldColonSpacing: Both", BitFieldColonSpacing,
16740               FormatStyle::BFCS_Both);
16741   CHECK_PARSE("BitFieldColonSpacing: None", BitFieldColonSpacing,
16742               FormatStyle::BFCS_None);
16743   CHECK_PARSE("BitFieldColonSpacing: Before", BitFieldColonSpacing,
16744               FormatStyle::BFCS_Before);
16745   CHECK_PARSE("BitFieldColonSpacing: After", BitFieldColonSpacing,
16746               FormatStyle::BFCS_After);
16747 
16748   Style.SortJavaStaticImport = FormatStyle::SJSIO_Before;
16749   CHECK_PARSE("SortJavaStaticImport: After", SortJavaStaticImport,
16750               FormatStyle::SJSIO_After);
16751   CHECK_PARSE("SortJavaStaticImport: Before", SortJavaStaticImport,
16752               FormatStyle::SJSIO_Before);
16753 
16754   // FIXME: This is required because parsing a configuration simply overwrites
16755   // the first N elements of the list instead of resetting it.
16756   Style.ForEachMacros.clear();
16757   std::vector<std::string> BoostForeach;
16758   BoostForeach.push_back("BOOST_FOREACH");
16759   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH]", ForEachMacros, BoostForeach);
16760   std::vector<std::string> BoostAndQForeach;
16761   BoostAndQForeach.push_back("BOOST_FOREACH");
16762   BoostAndQForeach.push_back("Q_FOREACH");
16763   CHECK_PARSE("ForEachMacros: [BOOST_FOREACH, Q_FOREACH]", ForEachMacros,
16764               BoostAndQForeach);
16765 
16766   Style.AttributeMacros.clear();
16767   CHECK_PARSE("BasedOnStyle: LLVM", AttributeMacros,
16768               std::vector<std::string>{"__capability"});
16769   CHECK_PARSE("AttributeMacros: [attr1, attr2]", AttributeMacros,
16770               std::vector<std::string>({"attr1", "attr2"}));
16771 
16772   Style.StatementAttributeLikeMacros.clear();
16773   CHECK_PARSE("StatementAttributeLikeMacros: [emit,Q_EMIT]",
16774               StatementAttributeLikeMacros,
16775               std::vector<std::string>({"emit", "Q_EMIT"}));
16776 
16777   Style.StatementMacros.clear();
16778   CHECK_PARSE("StatementMacros: [QUNUSED]", StatementMacros,
16779               std::vector<std::string>{"QUNUSED"});
16780   CHECK_PARSE("StatementMacros: [QUNUSED, QT_REQUIRE_VERSION]", StatementMacros,
16781               std::vector<std::string>({"QUNUSED", "QT_REQUIRE_VERSION"}));
16782 
16783   Style.NamespaceMacros.clear();
16784   CHECK_PARSE("NamespaceMacros: [TESTSUITE]", NamespaceMacros,
16785               std::vector<std::string>{"TESTSUITE"});
16786   CHECK_PARSE("NamespaceMacros: [TESTSUITE, SUITE]", NamespaceMacros,
16787               std::vector<std::string>({"TESTSUITE", "SUITE"}));
16788 
16789   Style.WhitespaceSensitiveMacros.clear();
16790   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE]",
16791               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
16792   CHECK_PARSE("WhitespaceSensitiveMacros: [STRINGIZE, ASSERT]",
16793               WhitespaceSensitiveMacros,
16794               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
16795   Style.WhitespaceSensitiveMacros.clear();
16796   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE']",
16797               WhitespaceSensitiveMacros, std::vector<std::string>{"STRINGIZE"});
16798   CHECK_PARSE("WhitespaceSensitiveMacros: ['STRINGIZE', 'ASSERT']",
16799               WhitespaceSensitiveMacros,
16800               std::vector<std::string>({"STRINGIZE", "ASSERT"}));
16801 
16802   Style.IncludeStyle.IncludeCategories.clear();
16803   std::vector<tooling::IncludeStyle::IncludeCategory> ExpectedCategories = {
16804       {"abc/.*", 2, 0, false}, {".*", 1, 0, true}};
16805   CHECK_PARSE("IncludeCategories:\n"
16806               "  - Regex: abc/.*\n"
16807               "    Priority: 2\n"
16808               "  - Regex: .*\n"
16809               "    Priority: 1\n"
16810               "    CaseSensitive: true\n",
16811               IncludeStyle.IncludeCategories, ExpectedCategories);
16812   CHECK_PARSE("IncludeIsMainRegex: 'abc$'", IncludeStyle.IncludeIsMainRegex,
16813               "abc$");
16814   CHECK_PARSE("IncludeIsMainSourceRegex: 'abc$'",
16815               IncludeStyle.IncludeIsMainSourceRegex, "abc$");
16816 
16817   Style.SortIncludes = FormatStyle::SI_Never;
16818   CHECK_PARSE("SortIncludes: true", SortIncludes,
16819               FormatStyle::SI_CaseSensitive);
16820   CHECK_PARSE("SortIncludes: false", SortIncludes, FormatStyle::SI_Never);
16821   CHECK_PARSE("SortIncludes: CaseInsensitive", SortIncludes,
16822               FormatStyle::SI_CaseInsensitive);
16823   CHECK_PARSE("SortIncludes: CaseSensitive", SortIncludes,
16824               FormatStyle::SI_CaseSensitive);
16825   CHECK_PARSE("SortIncludes: Never", SortIncludes, FormatStyle::SI_Never);
16826 
16827   Style.RawStringFormats.clear();
16828   std::vector<FormatStyle::RawStringFormat> ExpectedRawStringFormats = {
16829       {
16830           FormatStyle::LK_TextProto,
16831           {"pb", "proto"},
16832           {"PARSE_TEXT_PROTO"},
16833           /*CanonicalDelimiter=*/"",
16834           "llvm",
16835       },
16836       {
16837           FormatStyle::LK_Cpp,
16838           {"cc", "cpp"},
16839           {"C_CODEBLOCK", "CPPEVAL"},
16840           /*CanonicalDelimiter=*/"cc",
16841           /*BasedOnStyle=*/"",
16842       },
16843   };
16844 
16845   CHECK_PARSE("RawStringFormats:\n"
16846               "  - Language: TextProto\n"
16847               "    Delimiters:\n"
16848               "      - 'pb'\n"
16849               "      - 'proto'\n"
16850               "    EnclosingFunctions:\n"
16851               "      - 'PARSE_TEXT_PROTO'\n"
16852               "    BasedOnStyle: llvm\n"
16853               "  - Language: Cpp\n"
16854               "    Delimiters:\n"
16855               "      - 'cc'\n"
16856               "      - 'cpp'\n"
16857               "    EnclosingFunctions:\n"
16858               "      - 'C_CODEBLOCK'\n"
16859               "      - 'CPPEVAL'\n"
16860               "    CanonicalDelimiter: 'cc'",
16861               RawStringFormats, ExpectedRawStringFormats);
16862 
16863   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16864               "  Minimum: 0\n"
16865               "  Maximum: 0",
16866               SpacesInLineCommentPrefix.Minimum, 0u);
16867   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Maximum, 0u);
16868   Style.SpacesInLineCommentPrefix.Minimum = 1;
16869   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16870               "  Minimum: 2",
16871               SpacesInLineCommentPrefix.Minimum, 0u);
16872   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16873               "  Maximum: -1",
16874               SpacesInLineCommentPrefix.Maximum, -1u);
16875   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16876               "  Minimum: 2",
16877               SpacesInLineCommentPrefix.Minimum, 2u);
16878   CHECK_PARSE("SpacesInLineCommentPrefix:\n"
16879               "  Maximum: 1",
16880               SpacesInLineCommentPrefix.Maximum, 1u);
16881   EXPECT_EQ(Style.SpacesInLineCommentPrefix.Minimum, 1u);
16882 }
16883 
16884 TEST_F(FormatTest, ParsesConfigurationWithLanguages) {
16885   FormatStyle Style = {};
16886   Style.Language = FormatStyle::LK_Cpp;
16887   CHECK_PARSE("Language: Cpp\n"
16888               "IndentWidth: 12",
16889               IndentWidth, 12u);
16890   EXPECT_EQ(parseConfiguration("Language: JavaScript\n"
16891                                "IndentWidth: 34",
16892                                &Style),
16893             ParseError::Unsuitable);
16894   FormatStyle BinPackedTCS = {};
16895   BinPackedTCS.Language = FormatStyle::LK_JavaScript;
16896   EXPECT_EQ(parseConfiguration("BinPackArguments: true\n"
16897                                "InsertTrailingCommas: Wrapped",
16898                                &BinPackedTCS),
16899             ParseError::BinPackTrailingCommaConflict);
16900   EXPECT_EQ(12u, Style.IndentWidth);
16901   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
16902   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
16903 
16904   Style.Language = FormatStyle::LK_JavaScript;
16905   CHECK_PARSE("Language: JavaScript\n"
16906               "IndentWidth: 12",
16907               IndentWidth, 12u);
16908   CHECK_PARSE("IndentWidth: 23", IndentWidth, 23u);
16909   EXPECT_EQ(parseConfiguration("Language: Cpp\n"
16910                                "IndentWidth: 34",
16911                                &Style),
16912             ParseError::Unsuitable);
16913   EXPECT_EQ(23u, Style.IndentWidth);
16914   CHECK_PARSE("IndentWidth: 56", IndentWidth, 56u);
16915   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
16916 
16917   CHECK_PARSE("BasedOnStyle: LLVM\n"
16918               "IndentWidth: 67",
16919               IndentWidth, 67u);
16920 
16921   CHECK_PARSE("---\n"
16922               "Language: JavaScript\n"
16923               "IndentWidth: 12\n"
16924               "---\n"
16925               "Language: Cpp\n"
16926               "IndentWidth: 34\n"
16927               "...\n",
16928               IndentWidth, 12u);
16929 
16930   Style.Language = FormatStyle::LK_Cpp;
16931   CHECK_PARSE("---\n"
16932               "Language: JavaScript\n"
16933               "IndentWidth: 12\n"
16934               "---\n"
16935               "Language: Cpp\n"
16936               "IndentWidth: 34\n"
16937               "...\n",
16938               IndentWidth, 34u);
16939   CHECK_PARSE("---\n"
16940               "IndentWidth: 78\n"
16941               "---\n"
16942               "Language: JavaScript\n"
16943               "IndentWidth: 56\n"
16944               "...\n",
16945               IndentWidth, 78u);
16946 
16947   Style.ColumnLimit = 123;
16948   Style.IndentWidth = 234;
16949   Style.BreakBeforeBraces = FormatStyle::BS_Linux;
16950   Style.TabWidth = 345;
16951   EXPECT_FALSE(parseConfiguration("---\n"
16952                                   "IndentWidth: 456\n"
16953                                   "BreakBeforeBraces: Allman\n"
16954                                   "---\n"
16955                                   "Language: JavaScript\n"
16956                                   "IndentWidth: 111\n"
16957                                   "TabWidth: 111\n"
16958                                   "---\n"
16959                                   "Language: Cpp\n"
16960                                   "BreakBeforeBraces: Stroustrup\n"
16961                                   "TabWidth: 789\n"
16962                                   "...\n",
16963                                   &Style));
16964   EXPECT_EQ(123u, Style.ColumnLimit);
16965   EXPECT_EQ(456u, Style.IndentWidth);
16966   EXPECT_EQ(FormatStyle::BS_Stroustrup, Style.BreakBeforeBraces);
16967   EXPECT_EQ(789u, Style.TabWidth);
16968 
16969   EXPECT_EQ(parseConfiguration("---\n"
16970                                "Language: JavaScript\n"
16971                                "IndentWidth: 56\n"
16972                                "---\n"
16973                                "IndentWidth: 78\n"
16974                                "...\n",
16975                                &Style),
16976             ParseError::Error);
16977   EXPECT_EQ(parseConfiguration("---\n"
16978                                "Language: JavaScript\n"
16979                                "IndentWidth: 56\n"
16980                                "---\n"
16981                                "Language: JavaScript\n"
16982                                "IndentWidth: 78\n"
16983                                "...\n",
16984                                &Style),
16985             ParseError::Error);
16986 
16987   EXPECT_EQ(FormatStyle::LK_Cpp, Style.Language);
16988 }
16989 
16990 #undef CHECK_PARSE
16991 
16992 TEST_F(FormatTest, UsesLanguageForBasedOnStyle) {
16993   FormatStyle Style = {};
16994   Style.Language = FormatStyle::LK_JavaScript;
16995   Style.BreakBeforeTernaryOperators = true;
16996   EXPECT_EQ(0, parseConfiguration("BasedOnStyle: Google", &Style).value());
16997   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
16998 
16999   Style.BreakBeforeTernaryOperators = true;
17000   EXPECT_EQ(0, parseConfiguration("---\n"
17001                                   "BasedOnStyle: Google\n"
17002                                   "---\n"
17003                                   "Language: JavaScript\n"
17004                                   "IndentWidth: 76\n"
17005                                   "...\n",
17006                                   &Style)
17007                    .value());
17008   EXPECT_FALSE(Style.BreakBeforeTernaryOperators);
17009   EXPECT_EQ(76u, Style.IndentWidth);
17010   EXPECT_EQ(FormatStyle::LK_JavaScript, Style.Language);
17011 }
17012 
17013 TEST_F(FormatTest, ConfigurationRoundTripTest) {
17014   FormatStyle Style = getLLVMStyle();
17015   std::string YAML = configurationAsText(Style);
17016   FormatStyle ParsedStyle = {};
17017   ParsedStyle.Language = FormatStyle::LK_Cpp;
17018   EXPECT_EQ(0, parseConfiguration(YAML, &ParsedStyle).value());
17019   EXPECT_EQ(Style, ParsedStyle);
17020 }
17021 
17022 TEST_F(FormatTest, WorksFor8bitEncodings) {
17023   EXPECT_EQ("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 \"\n"
17024             "\"\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \"\n"
17025             "\"\xe7\xe8\xec\xed\xfe\xfe \"\n"
17026             "\"\xef\xee\xf0\xf3...\"",
17027             format("\"\xce\xe4\xed\xe0\xe6\xe4\xfb \xe2 "
17028                    "\xf1\xf2\xf3\xe4\xb8\xed\xf3\xfe \xe7\xe8\xec\xed\xfe\xfe "
17029                    "\xef\xee\xf0\xf3...\"",
17030                    getLLVMStyleWithColumns(12)));
17031 }
17032 
17033 TEST_F(FormatTest, HandlesUTF8BOM) {
17034   EXPECT_EQ("\xef\xbb\xbf", format("\xef\xbb\xbf"));
17035   EXPECT_EQ("\xef\xbb\xbf#include <iostream>",
17036             format("\xef\xbb\xbf#include <iostream>"));
17037   EXPECT_EQ("\xef\xbb\xbf\n#include <iostream>",
17038             format("\xef\xbb\xbf\n#include <iostream>"));
17039 }
17040 
17041 // FIXME: Encode Cyrillic and CJK characters below to appease MS compilers.
17042 #if !defined(_MSC_VER)
17043 
17044 TEST_F(FormatTest, CountsUTF8CharactersProperly) {
17045   verifyFormat("\"Однажды в студёную зимнюю пору...\"",
17046                getLLVMStyleWithColumns(35));
17047   verifyFormat("\"一 二 三 四 五 六 七 八 九 十\"",
17048                getLLVMStyleWithColumns(31));
17049   verifyFormat("// Однажды в студёную зимнюю пору...",
17050                getLLVMStyleWithColumns(36));
17051   verifyFormat("// 一 二 三 四 五 六 七 八 九 十", getLLVMStyleWithColumns(32));
17052   verifyFormat("/* Однажды в студёную зимнюю пору... */",
17053                getLLVMStyleWithColumns(39));
17054   verifyFormat("/* 一 二 三 四 五 六 七 八 九 十 */",
17055                getLLVMStyleWithColumns(35));
17056 }
17057 
17058 TEST_F(FormatTest, SplitsUTF8Strings) {
17059   // Non-printable characters' width is currently considered to be the length in
17060   // bytes in UTF8. The characters can be displayed in very different manner
17061   // (zero-width, single width with a substitution glyph, expanded to their code
17062   // (e.g. "<8d>"), so there's no single correct way to handle them.
17063   EXPECT_EQ("\"aaaaÄ\"\n"
17064             "\"\xc2\x8d\";",
17065             format("\"aaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
17066   EXPECT_EQ("\"aaaaaaaÄ\"\n"
17067             "\"\xc2\x8d\";",
17068             format("\"aaaaaaaÄ\xc2\x8d\";", getLLVMStyleWithColumns(10)));
17069   EXPECT_EQ("\"Однажды, в \"\n"
17070             "\"студёную \"\n"
17071             "\"зимнюю \"\n"
17072             "\"пору,\"",
17073             format("\"Однажды, в студёную зимнюю пору,\"",
17074                    getLLVMStyleWithColumns(13)));
17075   EXPECT_EQ(
17076       "\"一 二 三 \"\n"
17077       "\"四 五六 \"\n"
17078       "\"七 八 九 \"\n"
17079       "\"十\"",
17080       format("\"一 二 三 四 五六 七 八 九 十\"", getLLVMStyleWithColumns(11)));
17081   EXPECT_EQ("\"一\t\"\n"
17082             "\"二 \t\"\n"
17083             "\"三 四 \"\n"
17084             "\"五\t\"\n"
17085             "\"六 \t\"\n"
17086             "\"七 \"\n"
17087             "\"八九十\tqq\"",
17088             format("\"一\t二 \t三 四 五\t六 \t七 八九十\tqq\"",
17089                    getLLVMStyleWithColumns(11)));
17090 
17091   // UTF8 character in an escape sequence.
17092   EXPECT_EQ("\"aaaaaa\"\n"
17093             "\"\\\xC2\x8D\"",
17094             format("\"aaaaaa\\\xC2\x8D\"", getLLVMStyleWithColumns(10)));
17095 }
17096 
17097 TEST_F(FormatTest, HandlesDoubleWidthCharsInMultiLineStrings) {
17098   EXPECT_EQ("const char *sssss =\n"
17099             "    \"一二三四五六七八\\\n"
17100             " 九 十\";",
17101             format("const char *sssss = \"一二三四五六七八\\\n"
17102                    " 九 十\";",
17103                    getLLVMStyleWithColumns(30)));
17104 }
17105 
17106 TEST_F(FormatTest, SplitsUTF8LineComments) {
17107   EXPECT_EQ("// aaaaÄ\xc2\x8d",
17108             format("// aaaaÄ\xc2\x8d", getLLVMStyleWithColumns(10)));
17109   EXPECT_EQ("// Я из лесу\n"
17110             "// вышел; был\n"
17111             "// сильный\n"
17112             "// мороз.",
17113             format("// Я из лесу вышел; был сильный мороз.",
17114                    getLLVMStyleWithColumns(13)));
17115   EXPECT_EQ("// 一二三\n"
17116             "// 四五六七\n"
17117             "// 八  九\n"
17118             "// 十",
17119             format("// 一二三 四五六七 八  九 十", getLLVMStyleWithColumns(9)));
17120 }
17121 
17122 TEST_F(FormatTest, SplitsUTF8BlockComments) {
17123   EXPECT_EQ("/* Гляжу,\n"
17124             " * поднимается\n"
17125             " * медленно в\n"
17126             " * гору\n"
17127             " * Лошадка,\n"
17128             " * везущая\n"
17129             " * хворосту\n"
17130             " * воз. */",
17131             format("/* Гляжу, поднимается медленно в гору\n"
17132                    " * Лошадка, везущая хворосту воз. */",
17133                    getLLVMStyleWithColumns(13)));
17134   EXPECT_EQ(
17135       "/* 一二三\n"
17136       " * 四五六七\n"
17137       " * 八  九\n"
17138       " * 十  */",
17139       format("/* 一二三 四五六七 八  九 十  */", getLLVMStyleWithColumns(9)));
17140   EXPECT_EQ("/* �������� ��������\n"
17141             " * ��������\n"
17142             " * ������-�� */",
17143             format("/* �������� �������� �������� ������-�� */", getLLVMStyleWithColumns(12)));
17144 }
17145 
17146 #endif // _MSC_VER
17147 
17148 TEST_F(FormatTest, ConstructorInitializerIndentWidth) {
17149   FormatStyle Style = getLLVMStyle();
17150 
17151   Style.ConstructorInitializerIndentWidth = 4;
17152   verifyFormat(
17153       "SomeClass::Constructor()\n"
17154       "    : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
17155       "      aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
17156       Style);
17157 
17158   Style.ConstructorInitializerIndentWidth = 2;
17159   verifyFormat(
17160       "SomeClass::Constructor()\n"
17161       "  : aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
17162       "    aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
17163       Style);
17164 
17165   Style.ConstructorInitializerIndentWidth = 0;
17166   verifyFormat(
17167       "SomeClass::Constructor()\n"
17168       ": aaaaaaaaaaaaa(aaaaaaaaaaaaaa), aaaaaaaaaaaaa(aaaaaaaaaaaaaa),\n"
17169       "  aaaaaaaaaaaaa(aaaaaaaaaaaaaa) {}",
17170       Style);
17171   Style.AlignAfterOpenBracket = FormatStyle::BAS_AlwaysBreak;
17172   verifyFormat(
17173       "SomeLongTemplateVariableName<\n"
17174       "    aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa>",
17175       Style);
17176   verifyFormat("bool smaller = 1 < "
17177                "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb(\n"
17178                "                       "
17179                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa);",
17180                Style);
17181 
17182   Style.BreakConstructorInitializers = FormatStyle::BCIS_AfterColon;
17183   verifyFormat("SomeClass::Constructor() :\n"
17184                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa),\n"
17185                "aaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaa) {}",
17186                Style);
17187 }
17188 
17189 TEST_F(FormatTest, BreakConstructorInitializersBeforeComma) {
17190   FormatStyle Style = getLLVMStyle();
17191   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeComma;
17192   Style.ConstructorInitializerIndentWidth = 4;
17193   verifyFormat("SomeClass::Constructor()\n"
17194                "    : a(a)\n"
17195                "    , b(b)\n"
17196                "    , c(c) {}",
17197                Style);
17198   verifyFormat("SomeClass::Constructor()\n"
17199                "    : a(a) {}",
17200                Style);
17201 
17202   Style.ColumnLimit = 0;
17203   verifyFormat("SomeClass::Constructor()\n"
17204                "    : a(a) {}",
17205                Style);
17206   verifyFormat("SomeClass::Constructor() noexcept\n"
17207                "    : a(a) {}",
17208                Style);
17209   verifyFormat("SomeClass::Constructor()\n"
17210                "    : a(a)\n"
17211                "    , b(b)\n"
17212                "    , c(c) {}",
17213                Style);
17214   verifyFormat("SomeClass::Constructor()\n"
17215                "    : a(a) {\n"
17216                "  foo();\n"
17217                "  bar();\n"
17218                "}",
17219                Style);
17220 
17221   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
17222   verifyFormat("SomeClass::Constructor()\n"
17223                "    : a(a)\n"
17224                "    , b(b)\n"
17225                "    , c(c) {\n}",
17226                Style);
17227   verifyFormat("SomeClass::Constructor()\n"
17228                "    : a(a) {\n}",
17229                Style);
17230 
17231   Style.ColumnLimit = 80;
17232   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_All;
17233   Style.ConstructorInitializerIndentWidth = 2;
17234   verifyFormat("SomeClass::Constructor()\n"
17235                "  : a(a)\n"
17236                "  , b(b)\n"
17237                "  , c(c) {}",
17238                Style);
17239 
17240   Style.ConstructorInitializerIndentWidth = 0;
17241   verifyFormat("SomeClass::Constructor()\n"
17242                ": a(a)\n"
17243                ", b(b)\n"
17244                ", c(c) {}",
17245                Style);
17246 
17247   Style.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
17248   Style.ConstructorInitializerIndentWidth = 4;
17249   verifyFormat("SomeClass::Constructor() : aaaaaaaa(aaaaaaaa) {}", Style);
17250   verifyFormat(
17251       "SomeClass::Constructor() : aaaaa(aaaaa), aaaaa(aaaaa), aaaaa(aaaaa)\n",
17252       Style);
17253   verifyFormat(
17254       "SomeClass::Constructor()\n"
17255       "    : aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa), aaaaaaaa(aaaaaaaa) {}",
17256       Style);
17257   Style.ConstructorInitializerIndentWidth = 4;
17258   Style.ColumnLimit = 60;
17259   verifyFormat("SomeClass::Constructor()\n"
17260                "    : aaaaaaaa(aaaaaaaa)\n"
17261                "    , aaaaaaaa(aaaaaaaa)\n"
17262                "    , aaaaaaaa(aaaaaaaa) {}",
17263                Style);
17264 }
17265 
17266 TEST_F(FormatTest, Destructors) {
17267   verifyFormat("void F(int &i) { i.~int(); }");
17268   verifyFormat("void F(int &i) { i->~int(); }");
17269 }
17270 
17271 TEST_F(FormatTest, FormatsWithWebKitStyle) {
17272   FormatStyle Style = getWebKitStyle();
17273 
17274   // Don't indent in outer namespaces.
17275   verifyFormat("namespace outer {\n"
17276                "int i;\n"
17277                "namespace inner {\n"
17278                "    int i;\n"
17279                "} // namespace inner\n"
17280                "} // namespace outer\n"
17281                "namespace other_outer {\n"
17282                "int i;\n"
17283                "}",
17284                Style);
17285 
17286   // Don't indent case labels.
17287   verifyFormat("switch (variable) {\n"
17288                "case 1:\n"
17289                "case 2:\n"
17290                "    doSomething();\n"
17291                "    break;\n"
17292                "default:\n"
17293                "    ++variable;\n"
17294                "}",
17295                Style);
17296 
17297   // Wrap before binary operators.
17298   EXPECT_EQ("void f()\n"
17299             "{\n"
17300             "    if (aaaaaaaaaaaaaaaa\n"
17301             "        && bbbbbbbbbbbbbbbbbbbbbbbb\n"
17302             "        && (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
17303             "        return;\n"
17304             "}",
17305             format("void f() {\n"
17306                    "if (aaaaaaaaaaaaaaaa\n"
17307                    "&& bbbbbbbbbbbbbbbbbbbbbbbb\n"
17308                    "&& (cccccccccccccccccccccccccc || dddddddddddddddddddd))\n"
17309                    "return;\n"
17310                    "}",
17311                    Style));
17312 
17313   // Allow functions on a single line.
17314   verifyFormat("void f() { return; }", Style);
17315 
17316   // Allow empty blocks on a single line and insert a space in empty blocks.
17317   EXPECT_EQ("void f() { }", format("void f() {}", Style));
17318   EXPECT_EQ("while (true) { }", format("while (true) {}", Style));
17319   // However, don't merge non-empty short loops.
17320   EXPECT_EQ("while (true) {\n"
17321             "    continue;\n"
17322             "}",
17323             format("while (true) { continue; }", Style));
17324 
17325   // Constructor initializers are formatted one per line with the "," on the
17326   // new line.
17327   verifyFormat("Constructor()\n"
17328                "    : aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaaaaaaaaaaa)\n"
17329                "    , aaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaa, // break\n"
17330                "          aaaaaaaaaaaaaa)\n"
17331                "    , aaaaaaaaaaaaaaaaaaaaaaa()\n"
17332                "{\n"
17333                "}",
17334                Style);
17335   verifyFormat("SomeClass::Constructor()\n"
17336                "    : a(a)\n"
17337                "{\n"
17338                "}",
17339                Style);
17340   EXPECT_EQ("SomeClass::Constructor()\n"
17341             "    : a(a)\n"
17342             "{\n"
17343             "}",
17344             format("SomeClass::Constructor():a(a){}", Style));
17345   verifyFormat("SomeClass::Constructor()\n"
17346                "    : a(a)\n"
17347                "    , b(b)\n"
17348                "    , c(c)\n"
17349                "{\n"
17350                "}",
17351                Style);
17352   verifyFormat("SomeClass::Constructor()\n"
17353                "    : a(a)\n"
17354                "{\n"
17355                "    foo();\n"
17356                "    bar();\n"
17357                "}",
17358                Style);
17359 
17360   // Access specifiers should be aligned left.
17361   verifyFormat("class C {\n"
17362                "public:\n"
17363                "    int i;\n"
17364                "};",
17365                Style);
17366 
17367   // Do not align comments.
17368   verifyFormat("int a; // Do not\n"
17369                "double b; // align comments.",
17370                Style);
17371 
17372   // Do not align operands.
17373   EXPECT_EQ("ASSERT(aaaa\n"
17374             "    || bbbb);",
17375             format("ASSERT ( aaaa\n||bbbb);", Style));
17376 
17377   // Accept input's line breaks.
17378   EXPECT_EQ("if (aaaaaaaaaaaaaaa\n"
17379             "    || bbbbbbbbbbbbbbb) {\n"
17380             "    i++;\n"
17381             "}",
17382             format("if (aaaaaaaaaaaaaaa\n"
17383                    "|| bbbbbbbbbbbbbbb) { i++; }",
17384                    Style));
17385   EXPECT_EQ("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) {\n"
17386             "    i++;\n"
17387             "}",
17388             format("if (aaaaaaaaaaaaaaa || bbbbbbbbbbbbbbb) { i++; }", Style));
17389 
17390   // Don't automatically break all macro definitions (llvm.org/PR17842).
17391   verifyFormat("#define aNumber 10", Style);
17392   // However, generally keep the line breaks that the user authored.
17393   EXPECT_EQ("#define aNumber \\\n"
17394             "    10",
17395             format("#define aNumber \\\n"
17396                    " 10",
17397                    Style));
17398 
17399   // Keep empty and one-element array literals on a single line.
17400   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[]\n"
17401             "                                  copyItems:YES];",
17402             format("NSArray*a=[[NSArray alloc] initWithArray:@[]\n"
17403                    "copyItems:YES];",
17404                    Style));
17405   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\" ]\n"
17406             "                                  copyItems:YES];",
17407             format("NSArray*a=[[NSArray alloc]initWithArray:@[ @\"a\" ]\n"
17408                    "             copyItems:YES];",
17409                    Style));
17410   // FIXME: This does not seem right, there should be more indentation before
17411   // the array literal's entries. Nested blocks have the same problem.
17412   EXPECT_EQ("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
17413             "    @\"a\",\n"
17414             "    @\"a\"\n"
17415             "]\n"
17416             "                                  copyItems:YES];",
17417             format("NSArray* a = [[NSArray alloc] initWithArray:@[\n"
17418                    "     @\"a\",\n"
17419                    "     @\"a\"\n"
17420                    "     ]\n"
17421                    "       copyItems:YES];",
17422                    Style));
17423   EXPECT_EQ(
17424       "NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
17425       "                                  copyItems:YES];",
17426       format("NSArray* a = [[NSArray alloc] initWithArray:@[ @\"a\", @\"a\" ]\n"
17427              "   copyItems:YES];",
17428              Style));
17429 
17430   verifyFormat("[self.a b:c c:d];", Style);
17431   EXPECT_EQ("[self.a b:c\n"
17432             "        c:d];",
17433             format("[self.a b:c\n"
17434                    "c:d];",
17435                    Style));
17436 }
17437 
17438 TEST_F(FormatTest, FormatsLambdas) {
17439   verifyFormat("int c = [b]() mutable { return [&b] { return b++; }(); }();\n");
17440   verifyFormat(
17441       "int c = [b]() mutable noexcept { return [&b] { return b++; }(); }();\n");
17442   verifyFormat("int c = [&] { [=] { return b++; }(); }();\n");
17443   verifyFormat("int c = [&, &a, a] { [=, c, &d] { return b++; }(); }();\n");
17444   verifyFormat("int c = [&a, &a, a] { [=, a, b, &c] { return b++; }(); }();\n");
17445   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] { return b++; }(); }}\n");
17446   verifyFormat("auto c = {[&a, &a, a] { [=, a, b, &c] {}(); }}\n");
17447   verifyFormat("auto c = [a = [b = 42] {}] {};\n");
17448   verifyFormat("auto c = [a = &i + 10, b = [] {}] {};\n");
17449   verifyFormat("int x = f(*+[] {});");
17450   verifyFormat("void f() {\n"
17451                "  other(x.begin(), x.end(), [&](int, int) { return 1; });\n"
17452                "}\n");
17453   verifyFormat("void f() {\n"
17454                "  other(x.begin(), //\n"
17455                "        x.end(),   //\n"
17456                "        [&](int, int) { return 1; });\n"
17457                "}\n");
17458   verifyFormat("void f() {\n"
17459                "  other.other.other.other.other(\n"
17460                "      x.begin(), x.end(),\n"
17461                "      [something, rather](int, int, int, int, int, int, int) { "
17462                "return 1; });\n"
17463                "}\n");
17464   verifyFormat(
17465       "void f() {\n"
17466       "  other.other.other.other.other(\n"
17467       "      x.begin(), x.end(),\n"
17468       "      [something, rather](int, int, int, int, int, int, int) {\n"
17469       "        //\n"
17470       "      });\n"
17471       "}\n");
17472   verifyFormat("SomeFunction([]() { // A cool function...\n"
17473                "  return 43;\n"
17474                "});");
17475   EXPECT_EQ("SomeFunction([]() {\n"
17476             "#define A a\n"
17477             "  return 43;\n"
17478             "});",
17479             format("SomeFunction([](){\n"
17480                    "#define A a\n"
17481                    "return 43;\n"
17482                    "});"));
17483   verifyFormat("void f() {\n"
17484                "  SomeFunction([](decltype(x), A *a) {});\n"
17485                "  SomeFunction([](typeof(x), A *a) {});\n"
17486                "  SomeFunction([](_Atomic(x), A *a) {});\n"
17487                "  SomeFunction([](__underlying_type(x), A *a) {});\n"
17488                "}");
17489   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
17490                "    [](const aaaaaaaaaa &a) { return a; });");
17491   verifyFormat("string abc = SomeFunction(aaaaaaaaaaaaa, aaaaa, []() {\n"
17492                "  SomeOtherFunctioooooooooooooooooooooooooon();\n"
17493                "});");
17494   verifyFormat("Constructor()\n"
17495                "    : Field([] { // comment\n"
17496                "        int i;\n"
17497                "      }) {}");
17498   verifyFormat("auto my_lambda = [](const string &some_parameter) {\n"
17499                "  return some_parameter.size();\n"
17500                "};");
17501   verifyFormat("std::function<std::string(const std::string &)> my_lambda =\n"
17502                "    [](const string &s) { return s; };");
17503   verifyFormat("int i = aaaaaa ? 1 //\n"
17504                "               : [] {\n"
17505                "                   return 2; //\n"
17506                "                 }();");
17507   verifyFormat("llvm::errs() << \"number of twos is \"\n"
17508                "             << std::count_if(v.begin(), v.end(), [](int x) {\n"
17509                "                  return x == 2; // force break\n"
17510                "                });");
17511   verifyFormat("return aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
17512                "    [=](int iiiiiiiiiiii) {\n"
17513                "      return aaaaaaaaaaaaaaaaaaaaaaa !=\n"
17514                "             aaaaaaaaaaaaaaaaaaaaaaa;\n"
17515                "    });",
17516                getLLVMStyleWithColumns(60));
17517   verifyFormat("SomeFunction({[&] {\n"
17518                "                // comment\n"
17519                "              },\n"
17520                "              [&] {\n"
17521                "                // comment\n"
17522                "              }});");
17523   verifyFormat("SomeFunction({[&] {\n"
17524                "  // comment\n"
17525                "}});");
17526   verifyFormat(
17527       "virtual aaaaaaaaaaaaaaaa(\n"
17528       "    std::function<bool()> bbbbbbbbbbbb = [&]() { return true; },\n"
17529       "    aaaaa aaaaaaaaa);");
17530 
17531   // Lambdas with return types.
17532   verifyFormat("int c = []() -> int { return 2; }();\n");
17533   verifyFormat("int c = []() -> int * { return 2; }();\n");
17534   verifyFormat("int c = []() -> vector<int> { return {2}; }();\n");
17535   verifyFormat("Foo([]() -> std::vector<int> { return {2}; }());");
17536   verifyGoogleFormat("auto a = [&b, c](D* d) -> D* {};");
17537   verifyGoogleFormat("auto a = [&b, c](D* d) -> pair<D*, D*> {};");
17538   verifyGoogleFormat("auto a = [&b, c](D* d) -> D& {};");
17539   verifyGoogleFormat("auto a = [&b, c](D* d) -> const D* {};");
17540   verifyFormat("[a, a]() -> a<1> {};");
17541   verifyFormat("[]() -> foo<5 + 2> { return {}; };");
17542   verifyFormat("[]() -> foo<5 - 2> { return {}; };");
17543   verifyFormat("[]() -> foo<5 / 2> { return {}; };");
17544   verifyFormat("[]() -> foo<5 * 2> { return {}; };");
17545   verifyFormat("[]() -> foo<5 % 2> { return {}; };");
17546   verifyFormat("[]() -> foo<5 << 2> { return {}; };");
17547   verifyFormat("[]() -> foo<!5> { return {}; };");
17548   verifyFormat("[]() -> foo<~5> { return {}; };");
17549   verifyFormat("[]() -> foo<5 | 2> { return {}; };");
17550   verifyFormat("[]() -> foo<5 || 2> { return {}; };");
17551   verifyFormat("[]() -> foo<5 & 2> { return {}; };");
17552   verifyFormat("[]() -> foo<5 && 2> { return {}; };");
17553   verifyFormat("[]() -> foo<5 == 2> { return {}; };");
17554   verifyFormat("[]() -> foo<5 != 2> { return {}; };");
17555   verifyFormat("[]() -> foo<5 >= 2> { return {}; };");
17556   verifyFormat("[]() -> foo<5 <= 2> { return {}; };");
17557   verifyFormat("[]() -> foo<5 < 2> { return {}; };");
17558   verifyFormat("[]() -> foo<2 ? 1 : 0> { return {}; };");
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<5 / 2> { return {}; }};\n"
17570                "} // namespace bar");
17571   verifyFormat("namespace bar {\n"
17572                "// broken:\n"
17573                "auto foo{[]() -> foo<5 * 2> { return {}; }};\n"
17574                "} // namespace bar");
17575   verifyFormat("namespace bar {\n"
17576                "// broken:\n"
17577                "auto foo{[]() -> foo<5 % 2> { return {}; }};\n"
17578                "} // namespace bar");
17579   verifyFormat("namespace bar {\n"
17580                "// broken:\n"
17581                "auto foo{[]() -> foo<5 << 2> { return {}; }};\n"
17582                "} // namespace bar");
17583   verifyFormat("namespace bar {\n"
17584                "// broken:\n"
17585                "auto foo{[]() -> foo<!5> { return {}; }};\n"
17586                "} // namespace bar");
17587   verifyFormat("namespace bar {\n"
17588                "// broken:\n"
17589                "auto foo{[]() -> foo<~5> { return {}; }};\n"
17590                "} // namespace bar");
17591   verifyFormat("namespace bar {\n"
17592                "// broken:\n"
17593                "auto foo{[]() -> foo<5 | 2> { return {}; }};\n"
17594                "} // namespace bar");
17595   verifyFormat("namespace bar {\n"
17596                "// broken:\n"
17597                "auto foo{[]() -> foo<5 || 2> { return {}; }};\n"
17598                "} // namespace bar");
17599   verifyFormat("namespace bar {\n"
17600                "// broken:\n"
17601                "auto foo{[]() -> foo<5 & 2> { return {}; }};\n"
17602                "} // namespace bar");
17603   verifyFormat("namespace bar {\n"
17604                "// broken:\n"
17605                "auto foo{[]() -> foo<5 && 2> { return {}; }};\n"
17606                "} // namespace bar");
17607   verifyFormat("namespace bar {\n"
17608                "// broken:\n"
17609                "auto foo{[]() -> foo<5 == 2> { return {}; }};\n"
17610                "} // namespace bar");
17611   verifyFormat("namespace bar {\n"
17612                "// broken:\n"
17613                "auto foo{[]() -> foo<5 != 2> { return {}; }};\n"
17614                "} // namespace bar");
17615   verifyFormat("namespace bar {\n"
17616                "// broken:\n"
17617                "auto foo{[]() -> foo<5 >= 2> { return {}; }};\n"
17618                "} // namespace bar");
17619   verifyFormat("namespace bar {\n"
17620                "// broken:\n"
17621                "auto foo{[]() -> foo<5 <= 2> { return {}; }};\n"
17622                "} // namespace bar");
17623   verifyFormat("namespace bar {\n"
17624                "// broken:\n"
17625                "auto foo{[]() -> foo<5 < 2> { return {}; }};\n"
17626                "} // namespace bar");
17627   verifyFormat("namespace bar {\n"
17628                "// broken:\n"
17629                "auto foo{[]() -> foo<2 ? 1 : 0> { return {}; }};\n"
17630                "} // namespace bar");
17631   verifyFormat("[]() -> a<1> {};");
17632   verifyFormat("[]() -> a<1> { ; };");
17633   verifyFormat("[]() -> a<1> { ; }();");
17634   verifyFormat("[a, a]() -> a<true> {};");
17635   verifyFormat("[]() -> a<true> {};");
17636   verifyFormat("[]() -> a<true> { ; };");
17637   verifyFormat("[]() -> a<true> { ; }();");
17638   verifyFormat("[a, a]() -> a<false> {};");
17639   verifyFormat("[]() -> a<false> {};");
17640   verifyFormat("[]() -> a<false> { ; };");
17641   verifyFormat("[]() -> a<false> { ; }();");
17642   verifyFormat("auto foo{[]() -> foo<false> { ; }};");
17643   verifyFormat("namespace bar {\n"
17644                "auto foo{[]() -> foo<false> { ; }};\n"
17645                "} // namespace bar");
17646   verifyFormat("auto aaaaaaaa = [](int i, // break for some reason\n"
17647                "                   int j) -> int {\n"
17648                "  return ffffffffffffffffffffffffffffffffffffffffffff(i * j);\n"
17649                "};");
17650   verifyFormat(
17651       "aaaaaaaaaaaaaaaaaaaaaa(\n"
17652       "    [](aaaaaaaaaaaaaaaaaaaaaaaaaaa &aaa) -> aaaaaaaaaaaaaaaa {\n"
17653       "      return aaaaaaaaaaaaaaaaa;\n"
17654       "    });",
17655       getLLVMStyleWithColumns(70));
17656   verifyFormat("[]() //\n"
17657                "    -> int {\n"
17658                "  return 1; //\n"
17659                "};");
17660   verifyFormat("[]() -> Void<T...> {};");
17661   verifyFormat("[a, b]() -> Tuple<T...> { return {}; };");
17662 
17663   // Lambdas with explicit template argument lists.
17664   verifyFormat(
17665       "auto L = []<template <typename> class T, class U>(T<U> &&a) {};\n");
17666 
17667   // Multiple lambdas in the same parentheses change indentation rules. These
17668   // lambdas are forced to start on new lines.
17669   verifyFormat("SomeFunction(\n"
17670                "    []() {\n"
17671                "      //\n"
17672                "    },\n"
17673                "    []() {\n"
17674                "      //\n"
17675                "    });");
17676 
17677   // A lambda passed as arg0 is always pushed to the next line.
17678   verifyFormat("SomeFunction(\n"
17679                "    [this] {\n"
17680                "      //\n"
17681                "    },\n"
17682                "    1);\n");
17683 
17684   // A multi-line lambda passed as arg1 forces arg0 to be pushed out, just like
17685   // the arg0 case above.
17686   auto Style = getGoogleStyle();
17687   Style.BinPackArguments = false;
17688   verifyFormat("SomeFunction(\n"
17689                "    a,\n"
17690                "    [this] {\n"
17691                "      //\n"
17692                "    },\n"
17693                "    b);\n",
17694                Style);
17695   verifyFormat("SomeFunction(\n"
17696                "    a,\n"
17697                "    [this] {\n"
17698                "      //\n"
17699                "    },\n"
17700                "    b);\n");
17701 
17702   // A lambda with a very long line forces arg0 to be pushed out irrespective of
17703   // the BinPackArguments value (as long as the code is wide enough).
17704   verifyFormat(
17705       "something->SomeFunction(\n"
17706       "    a,\n"
17707       "    [this] {\n"
17708       "      "
17709       "D0000000000000000000000000000000000000000000000000000000000001();\n"
17710       "    },\n"
17711       "    b);\n");
17712 
17713   // A multi-line lambda is pulled up as long as the introducer fits on the
17714   // previous line and there are no further args.
17715   verifyFormat("function(1, [this, that] {\n"
17716                "  //\n"
17717                "});\n");
17718   verifyFormat("function([this, that] {\n"
17719                "  //\n"
17720                "});\n");
17721   // FIXME: this format is not ideal and we should consider forcing the first
17722   // arg onto its own line.
17723   verifyFormat("function(a, b, c, //\n"
17724                "         d, [this, that] {\n"
17725                "           //\n"
17726                "         });\n");
17727 
17728   // Multiple lambdas are treated correctly even when there is a short arg0.
17729   verifyFormat("SomeFunction(\n"
17730                "    1,\n"
17731                "    [this] {\n"
17732                "      //\n"
17733                "    },\n"
17734                "    [this] {\n"
17735                "      //\n"
17736                "    },\n"
17737                "    1);\n");
17738 
17739   // More complex introducers.
17740   verifyFormat("return [i, args...] {};");
17741 
17742   // Not lambdas.
17743   verifyFormat("constexpr char hello[]{\"hello\"};");
17744   verifyFormat("double &operator[](int i) { return 0; }\n"
17745                "int i;");
17746   verifyFormat("std::unique_ptr<int[]> foo() {}");
17747   verifyFormat("int i = a[a][a]->f();");
17748   verifyFormat("int i = (*b)[a]->f();");
17749 
17750   // Other corner cases.
17751   verifyFormat("void f() {\n"
17752                "  bar([]() {} // Did not respect SpacesBeforeTrailingComments\n"
17753                "  );\n"
17754                "}");
17755 
17756   // Lambdas created through weird macros.
17757   verifyFormat("void f() {\n"
17758                "  MACRO((const AA &a) { return 1; });\n"
17759                "  MACRO((AA &a) { return 1; });\n"
17760                "}");
17761 
17762   verifyFormat("if (blah_blah(whatever, whatever, [] {\n"
17763                "      doo_dah();\n"
17764                "      doo_dah();\n"
17765                "    })) {\n"
17766                "}");
17767   verifyFormat("if constexpr (blah_blah(whatever, whatever, [] {\n"
17768                "                doo_dah();\n"
17769                "                doo_dah();\n"
17770                "              })) {\n"
17771                "}");
17772   verifyFormat("if CONSTEXPR (blah_blah(whatever, whatever, [] {\n"
17773                "                doo_dah();\n"
17774                "                doo_dah();\n"
17775                "              })) {\n"
17776                "}");
17777   verifyFormat("auto lambda = []() {\n"
17778                "  int a = 2\n"
17779                "#if A\n"
17780                "          + 2\n"
17781                "#endif\n"
17782                "      ;\n"
17783                "};");
17784 
17785   // Lambdas with complex multiline introducers.
17786   verifyFormat(
17787       "aaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
17788       "    [aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa]()\n"
17789       "        -> ::std::unordered_set<\n"
17790       "            aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa> {\n"
17791       "      //\n"
17792       "    });");
17793 
17794   FormatStyle DoNotMerge = getLLVMStyle();
17795   DoNotMerge.AllowShortLambdasOnASingleLine = FormatStyle::SLS_None;
17796   verifyFormat("auto c = []() {\n"
17797                "  return b;\n"
17798                "};",
17799                "auto c = []() { return b; };", DoNotMerge);
17800   verifyFormat("auto c = []() {\n"
17801                "};",
17802                " auto c = []() {};", DoNotMerge);
17803 
17804   FormatStyle MergeEmptyOnly = getLLVMStyle();
17805   MergeEmptyOnly.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Empty;
17806   verifyFormat("auto c = []() {\n"
17807                "  return b;\n"
17808                "};",
17809                "auto c = []() {\n"
17810                "  return b;\n"
17811                " };",
17812                MergeEmptyOnly);
17813   verifyFormat("auto c = []() {};",
17814                "auto c = []() {\n"
17815                "};",
17816                MergeEmptyOnly);
17817 
17818   FormatStyle MergeInline = getLLVMStyle();
17819   MergeInline.AllowShortLambdasOnASingleLine = FormatStyle::SLS_Inline;
17820   verifyFormat("auto c = []() {\n"
17821                "  return b;\n"
17822                "};",
17823                "auto c = []() { return b; };", MergeInline);
17824   verifyFormat("function([]() { return b; })", "function([]() { return b; })",
17825                MergeInline);
17826   verifyFormat("function([]() { return b; }, a)",
17827                "function([]() { return b; }, a)", MergeInline);
17828   verifyFormat("function(a, []() { return b; })",
17829                "function(a, []() { return b; })", MergeInline);
17830 
17831   // Check option "BraceWrapping.BeforeLambdaBody" and different state of
17832   // AllowShortLambdasOnASingleLine
17833   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
17834   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
17835   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
17836   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17837       FormatStyle::ShortLambdaStyle::SLS_None;
17838   verifyFormat("FctWithOneNestedLambdaInline_SLS_None(\n"
17839                "    []()\n"
17840                "    {\n"
17841                "      return 17;\n"
17842                "    });",
17843                LLVMWithBeforeLambdaBody);
17844   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_None(\n"
17845                "    []()\n"
17846                "    {\n"
17847                "    });",
17848                LLVMWithBeforeLambdaBody);
17849   verifyFormat("auto fct_SLS_None = []()\n"
17850                "{\n"
17851                "  return 17;\n"
17852                "};",
17853                LLVMWithBeforeLambdaBody);
17854   verifyFormat("TwoNestedLambdas_SLS_None(\n"
17855                "    []()\n"
17856                "    {\n"
17857                "      return Call(\n"
17858                "          []()\n"
17859                "          {\n"
17860                "            return 17;\n"
17861                "          });\n"
17862                "    });",
17863                LLVMWithBeforeLambdaBody);
17864   verifyFormat("void Fct()\n"
17865                "{\n"
17866                "  return {[]()\n"
17867                "          {\n"
17868                "            return 17;\n"
17869                "          }};\n"
17870                "}",
17871                LLVMWithBeforeLambdaBody);
17872 
17873   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17874       FormatStyle::ShortLambdaStyle::SLS_Empty;
17875   verifyFormat("FctWithOneNestedLambdaInline_SLS_Empty(\n"
17876                "    []()\n"
17877                "    {\n"
17878                "      return 17;\n"
17879                "    });",
17880                LLVMWithBeforeLambdaBody);
17881   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Empty([]() {});",
17882                LLVMWithBeforeLambdaBody);
17883   verifyFormat("FctWithOneNestedLambdaEmptyInsideAVeryVeryVeryVeryVeryVeryVeryL"
17884                "ongFunctionName_SLS_Empty(\n"
17885                "    []() {});",
17886                LLVMWithBeforeLambdaBody);
17887   verifyFormat("FctWithMultipleParams_SLS_Empty(A, B,\n"
17888                "                                []()\n"
17889                "                                {\n"
17890                "                                  return 17;\n"
17891                "                                });",
17892                LLVMWithBeforeLambdaBody);
17893   verifyFormat("auto fct_SLS_Empty = []()\n"
17894                "{\n"
17895                "  return 17;\n"
17896                "};",
17897                LLVMWithBeforeLambdaBody);
17898   verifyFormat("TwoNestedLambdas_SLS_Empty(\n"
17899                "    []()\n"
17900                "    {\n"
17901                "      return Call([]() {});\n"
17902                "    });",
17903                LLVMWithBeforeLambdaBody);
17904   verifyFormat("TwoNestedLambdas_SLS_Empty(A,\n"
17905                "                           []()\n"
17906                "                           {\n"
17907                "                             return Call([]() {});\n"
17908                "                           });",
17909                LLVMWithBeforeLambdaBody);
17910   verifyFormat(
17911       "FctWithLongLineInLambda_SLS_Empty(\n"
17912       "    []()\n"
17913       "    {\n"
17914       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17915       "                               AndShouldNotBeConsiderAsInline,\n"
17916       "                               LambdaBodyMustBeBreak);\n"
17917       "    });",
17918       LLVMWithBeforeLambdaBody);
17919 
17920   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17921       FormatStyle::ShortLambdaStyle::SLS_Inline;
17922   verifyFormat("FctWithOneNestedLambdaInline_SLS_Inline([]() { return 17; });",
17923                LLVMWithBeforeLambdaBody);
17924   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_Inline([]() {});",
17925                LLVMWithBeforeLambdaBody);
17926   verifyFormat("auto fct_SLS_Inline = []()\n"
17927                "{\n"
17928                "  return 17;\n"
17929                "};",
17930                LLVMWithBeforeLambdaBody);
17931   verifyFormat("TwoNestedLambdas_SLS_Inline([]() { return Call([]() { return "
17932                "17; }); });",
17933                LLVMWithBeforeLambdaBody);
17934   verifyFormat(
17935       "FctWithLongLineInLambda_SLS_Inline(\n"
17936       "    []()\n"
17937       "    {\n"
17938       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17939       "                               AndShouldNotBeConsiderAsInline,\n"
17940       "                               LambdaBodyMustBeBreak);\n"
17941       "    });",
17942       LLVMWithBeforeLambdaBody);
17943   verifyFormat("FctWithMultipleParams_SLS_Inline("
17944                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
17945                "                                 []() { return 17; });",
17946                LLVMWithBeforeLambdaBody);
17947   verifyFormat(
17948       "FctWithMultipleParams_SLS_Inline(FirstParam, []() { return 17; });",
17949       LLVMWithBeforeLambdaBody);
17950 
17951   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
17952       FormatStyle::ShortLambdaStyle::SLS_All;
17953   verifyFormat("FctWithOneNestedLambdaInline_SLS_All([]() { return 17; });",
17954                LLVMWithBeforeLambdaBody);
17955   verifyFormat("FctWithOneNestedLambdaEmpty_SLS_All([]() {});",
17956                LLVMWithBeforeLambdaBody);
17957   verifyFormat("auto fct_SLS_All = []() { return 17; };",
17958                LLVMWithBeforeLambdaBody);
17959   verifyFormat("FctWithOneParam_SLS_All(\n"
17960                "    []()\n"
17961                "    {\n"
17962                "      // A cool function...\n"
17963                "      return 43;\n"
17964                "    });",
17965                LLVMWithBeforeLambdaBody);
17966   verifyFormat("FctWithMultipleParams_SLS_All("
17967                "VeryLongParameterThatShouldAskToBeOnMultiLine,\n"
17968                "                              []() { return 17; });",
17969                LLVMWithBeforeLambdaBody);
17970   verifyFormat("FctWithMultipleParams_SLS_All(A, []() { return 17; });",
17971                LLVMWithBeforeLambdaBody);
17972   verifyFormat("FctWithMultipleParams_SLS_All(A, B, []() { return 17; });",
17973                LLVMWithBeforeLambdaBody);
17974   verifyFormat(
17975       "FctWithLongLineInLambda_SLS_All(\n"
17976       "    []()\n"
17977       "    {\n"
17978       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17979       "                               AndShouldNotBeConsiderAsInline,\n"
17980       "                               LambdaBodyMustBeBreak);\n"
17981       "    });",
17982       LLVMWithBeforeLambdaBody);
17983   verifyFormat(
17984       "auto fct_SLS_All = []()\n"
17985       "{\n"
17986       "  return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
17987       "                           AndShouldNotBeConsiderAsInline,\n"
17988       "                           LambdaBodyMustBeBreak);\n"
17989       "};",
17990       LLVMWithBeforeLambdaBody);
17991   LLVMWithBeforeLambdaBody.BinPackParameters = false;
17992   verifyFormat("FctAllOnSameLine_SLS_All([]() { return S; }, Fst, Second);",
17993                LLVMWithBeforeLambdaBody);
17994   verifyFormat(
17995       "FctWithLongLineInLambda_SLS_All([]() { return SomeValueNotSoLong; },\n"
17996       "                                FirstParam,\n"
17997       "                                SecondParam,\n"
17998       "                                ThirdParam,\n"
17999       "                                FourthParam);",
18000       LLVMWithBeforeLambdaBody);
18001   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
18002                "    []() { return "
18003                "SomeValueVeryVeryVeryVeryVeryVeryVeryVeryVeryLong; },\n"
18004                "    FirstParam,\n"
18005                "    SecondParam,\n"
18006                "    ThirdParam,\n"
18007                "    FourthParam);",
18008                LLVMWithBeforeLambdaBody);
18009   verifyFormat(
18010       "FctWithLongLineInLambda_SLS_All(FirstParam,\n"
18011       "                                SecondParam,\n"
18012       "                                ThirdParam,\n"
18013       "                                FourthParam,\n"
18014       "                                []() { return SomeValueNotSoLong; });",
18015       LLVMWithBeforeLambdaBody);
18016   verifyFormat("FctWithLongLineInLambda_SLS_All(\n"
18017                "    []()\n"
18018                "    {\n"
18019                "      return "
18020                "HereAVeryLongLineThatWillBeFormattedOnMultipleLineAndShouldNotB"
18021                "eConsiderAsInline;\n"
18022                "    });",
18023                LLVMWithBeforeLambdaBody);
18024   verifyFormat(
18025       "FctWithLongLineInLambda_SLS_All(\n"
18026       "    []()\n"
18027       "    {\n"
18028       "      return HereAVeryLongLine(ThatWillBeFormatted, OnMultipleLine,\n"
18029       "                               AndShouldNotBeConsiderAsInline,\n"
18030       "                               LambdaBodyMustBeBreak);\n"
18031       "    });",
18032       LLVMWithBeforeLambdaBody);
18033   verifyFormat("FctWithTwoParams_SLS_All(\n"
18034                "    []()\n"
18035                "    {\n"
18036                "      // A cool function...\n"
18037                "      return 43;\n"
18038                "    },\n"
18039                "    87);",
18040                LLVMWithBeforeLambdaBody);
18041   verifyFormat("FctWithTwoParams_SLS_All([]() { return 43; }, 87);",
18042                LLVMWithBeforeLambdaBody);
18043   verifyFormat("FctWithOneNestedLambdas_SLS_All([]() { return 17; });",
18044                LLVMWithBeforeLambdaBody);
18045   verifyFormat(
18046       "TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; }); });",
18047       LLVMWithBeforeLambdaBody);
18048   verifyFormat("TwoNestedLambdas_SLS_All([]() { return Call([]() { return 17; "
18049                "}); }, x);",
18050                LLVMWithBeforeLambdaBody);
18051   verifyFormat("TwoNestedLambdas_SLS_All(\n"
18052                "    []()\n"
18053                "    {\n"
18054                "      // A cool function...\n"
18055                "      return Call([]() { return 17; });\n"
18056                "    });",
18057                LLVMWithBeforeLambdaBody);
18058   verifyFormat("TwoNestedLambdas_SLS_All(\n"
18059                "    []()\n"
18060                "    {\n"
18061                "      return Call(\n"
18062                "          []()\n"
18063                "          {\n"
18064                "            // A cool function...\n"
18065                "            return 17;\n"
18066                "          });\n"
18067                "    });",
18068                LLVMWithBeforeLambdaBody);
18069 }
18070 
18071 TEST_F(FormatTest, LambdaWithLineComments) {
18072   FormatStyle LLVMWithBeforeLambdaBody = getLLVMStyle();
18073   LLVMWithBeforeLambdaBody.BreakBeforeBraces = FormatStyle::BS_Custom;
18074   LLVMWithBeforeLambdaBody.BraceWrapping.BeforeLambdaBody = true;
18075   LLVMWithBeforeLambdaBody.AllowShortLambdasOnASingleLine =
18076       FormatStyle::ShortLambdaStyle::SLS_All;
18077 
18078   verifyFormat("auto k = []() { return; }", LLVMWithBeforeLambdaBody);
18079   verifyFormat("auto k = []() // comment\n"
18080                "{ return; }",
18081                LLVMWithBeforeLambdaBody);
18082   verifyFormat("auto k = []() /* comment */ { return; }",
18083                LLVMWithBeforeLambdaBody);
18084   verifyFormat("auto k = []() /* comment */ /* comment */ { return; }",
18085                LLVMWithBeforeLambdaBody);
18086   verifyFormat("auto k = []() // X\n"
18087                "{ return; }",
18088                LLVMWithBeforeLambdaBody);
18089   verifyFormat(
18090       "auto k = []() // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n"
18091       "{ return; }",
18092       LLVMWithBeforeLambdaBody);
18093 }
18094 
18095 TEST_F(FormatTest, EmptyLinesInLambdas) {
18096   verifyFormat("auto lambda = []() {\n"
18097                "  x(); //\n"
18098                "};",
18099                "auto lambda = []() {\n"
18100                "\n"
18101                "  x(); //\n"
18102                "\n"
18103                "};");
18104 }
18105 
18106 TEST_F(FormatTest, FormatsBlocks) {
18107   FormatStyle ShortBlocks = getLLVMStyle();
18108   ShortBlocks.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
18109   verifyFormat("int (^Block)(int, int);", ShortBlocks);
18110   verifyFormat("int (^Block1)(int, int) = ^(int i, int j)", ShortBlocks);
18111   verifyFormat("void (^block)(int) = ^(id test) { int i; };", ShortBlocks);
18112   verifyFormat("void (^block)(int) = ^(int test) { int i; };", ShortBlocks);
18113   verifyFormat("void (^block)(int) = ^id(int test) { int i; };", ShortBlocks);
18114   verifyFormat("void (^block)(int) = ^int(int test) { int i; };", ShortBlocks);
18115 
18116   verifyFormat("foo(^{ bar(); });", ShortBlocks);
18117   verifyFormat("foo(a, ^{ bar(); });", ShortBlocks);
18118   verifyFormat("{ void (^block)(Object *x); }", ShortBlocks);
18119 
18120   verifyFormat("[operation setCompletionBlock:^{\n"
18121                "  [self onOperationDone];\n"
18122                "}];");
18123   verifyFormat("int i = {[operation setCompletionBlock:^{\n"
18124                "  [self onOperationDone];\n"
18125                "}]};");
18126   verifyFormat("[operation setCompletionBlock:^(int *i) {\n"
18127                "  f();\n"
18128                "}];");
18129   verifyFormat("int a = [operation block:^int(int *i) {\n"
18130                "  return 1;\n"
18131                "}];");
18132   verifyFormat("[myObject doSomethingWith:arg1\n"
18133                "                      aaa:^int(int *a) {\n"
18134                "                        return 1;\n"
18135                "                      }\n"
18136                "                      bbb:f(a * bbbbbbbb)];");
18137 
18138   verifyFormat("[operation setCompletionBlock:^{\n"
18139                "  [self.delegate newDataAvailable];\n"
18140                "}];",
18141                getLLVMStyleWithColumns(60));
18142   verifyFormat("dispatch_async(_fileIOQueue, ^{\n"
18143                "  NSString *path = [self sessionFilePath];\n"
18144                "  if (path) {\n"
18145                "    // ...\n"
18146                "  }\n"
18147                "});");
18148   verifyFormat("[[SessionService sharedService]\n"
18149                "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
18150                "      if (window) {\n"
18151                "        [self windowDidLoad:window];\n"
18152                "      } else {\n"
18153                "        [self errorLoadingWindow];\n"
18154                "      }\n"
18155                "    }];");
18156   verifyFormat("void (^largeBlock)(void) = ^{\n"
18157                "  // ...\n"
18158                "};\n",
18159                getLLVMStyleWithColumns(40));
18160   verifyFormat("[[SessionService sharedService]\n"
18161                "    loadWindowWithCompletionBlock: //\n"
18162                "        ^(SessionWindow *window) {\n"
18163                "          if (window) {\n"
18164                "            [self windowDidLoad:window];\n"
18165                "          } else {\n"
18166                "            [self errorLoadingWindow];\n"
18167                "          }\n"
18168                "        }];",
18169                getLLVMStyleWithColumns(60));
18170   verifyFormat("[myObject doSomethingWith:arg1\n"
18171                "    firstBlock:^(Foo *a) {\n"
18172                "      // ...\n"
18173                "      int i;\n"
18174                "    }\n"
18175                "    secondBlock:^(Bar *b) {\n"
18176                "      // ...\n"
18177                "      int i;\n"
18178                "    }\n"
18179                "    thirdBlock:^Foo(Bar *b) {\n"
18180                "      // ...\n"
18181                "      int i;\n"
18182                "    }];");
18183   verifyFormat("[myObject doSomethingWith:arg1\n"
18184                "               firstBlock:-1\n"
18185                "              secondBlock:^(Bar *b) {\n"
18186                "                // ...\n"
18187                "                int i;\n"
18188                "              }];");
18189 
18190   verifyFormat("f(^{\n"
18191                "  @autoreleasepool {\n"
18192                "    if (a) {\n"
18193                "      g();\n"
18194                "    }\n"
18195                "  }\n"
18196                "});");
18197   verifyFormat("Block b = ^int *(A *a, B *b) {}");
18198   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
18199                "};");
18200 
18201   FormatStyle FourIndent = getLLVMStyle();
18202   FourIndent.ObjCBlockIndentWidth = 4;
18203   verifyFormat("[operation setCompletionBlock:^{\n"
18204                "    [self onOperationDone];\n"
18205                "}];",
18206                FourIndent);
18207 }
18208 
18209 TEST_F(FormatTest, FormatsBlocksWithZeroColumnWidth) {
18210   FormatStyle ZeroColumn = getLLVMStyle();
18211   ZeroColumn.ColumnLimit = 0;
18212 
18213   verifyFormat("[[SessionService sharedService] "
18214                "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
18215                "  if (window) {\n"
18216                "    [self windowDidLoad:window];\n"
18217                "  } else {\n"
18218                "    [self errorLoadingWindow];\n"
18219                "  }\n"
18220                "}];",
18221                ZeroColumn);
18222   EXPECT_EQ("[[SessionService sharedService]\n"
18223             "    loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
18224             "      if (window) {\n"
18225             "        [self windowDidLoad:window];\n"
18226             "      } else {\n"
18227             "        [self errorLoadingWindow];\n"
18228             "      }\n"
18229             "    }];",
18230             format("[[SessionService sharedService]\n"
18231                    "loadWindowWithCompletionBlock:^(SessionWindow *window) {\n"
18232                    "                if (window) {\n"
18233                    "    [self windowDidLoad:window];\n"
18234                    "  } else {\n"
18235                    "    [self errorLoadingWindow];\n"
18236                    "  }\n"
18237                    "}];",
18238                    ZeroColumn));
18239   verifyFormat("[myObject doSomethingWith:arg1\n"
18240                "    firstBlock:^(Foo *a) {\n"
18241                "      // ...\n"
18242                "      int i;\n"
18243                "    }\n"
18244                "    secondBlock:^(Bar *b) {\n"
18245                "      // ...\n"
18246                "      int i;\n"
18247                "    }\n"
18248                "    thirdBlock:^Foo(Bar *b) {\n"
18249                "      // ...\n"
18250                "      int i;\n"
18251                "    }];",
18252                ZeroColumn);
18253   verifyFormat("f(^{\n"
18254                "  @autoreleasepool {\n"
18255                "    if (a) {\n"
18256                "      g();\n"
18257                "    }\n"
18258                "  }\n"
18259                "});",
18260                ZeroColumn);
18261   verifyFormat("void (^largeBlock)(void) = ^{\n"
18262                "  // ...\n"
18263                "};",
18264                ZeroColumn);
18265 
18266   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Always;
18267   EXPECT_EQ("void (^largeBlock)(void) = ^{ int i; };",
18268             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
18269   ZeroColumn.AllowShortBlocksOnASingleLine = FormatStyle::SBS_Never;
18270   EXPECT_EQ("void (^largeBlock)(void) = ^{\n"
18271             "  int i;\n"
18272             "};",
18273             format("void   (^largeBlock)(void) = ^{ int   i; };", ZeroColumn));
18274 }
18275 
18276 TEST_F(FormatTest, SupportsCRLF) {
18277   EXPECT_EQ("int a;\r\n"
18278             "int b;\r\n"
18279             "int c;\r\n",
18280             format("int a;\r\n"
18281                    "  int b;\r\n"
18282                    "    int c;\r\n",
18283                    getLLVMStyle()));
18284   EXPECT_EQ("int a;\r\n"
18285             "int b;\r\n"
18286             "int c;\r\n",
18287             format("int a;\r\n"
18288                    "  int b;\n"
18289                    "    int c;\r\n",
18290                    getLLVMStyle()));
18291   EXPECT_EQ("int a;\n"
18292             "int b;\n"
18293             "int c;\n",
18294             format("int a;\r\n"
18295                    "  int b;\n"
18296                    "    int c;\n",
18297                    getLLVMStyle()));
18298   EXPECT_EQ("\"aaaaaaa \"\r\n"
18299             "\"bbbbbbb\";\r\n",
18300             format("\"aaaaaaa bbbbbbb\";\r\n", getLLVMStyleWithColumns(10)));
18301   EXPECT_EQ("#define A \\\r\n"
18302             "  b;      \\\r\n"
18303             "  c;      \\\r\n"
18304             "  d;\r\n",
18305             format("#define A \\\r\n"
18306                    "  b; \\\r\n"
18307                    "  c; d; \r\n",
18308                    getGoogleStyle()));
18309 
18310   EXPECT_EQ("/*\r\n"
18311             "multi line block comments\r\n"
18312             "should not introduce\r\n"
18313             "an extra carriage return\r\n"
18314             "*/\r\n",
18315             format("/*\r\n"
18316                    "multi line block comments\r\n"
18317                    "should not introduce\r\n"
18318                    "an extra carriage return\r\n"
18319                    "*/\r\n"));
18320   EXPECT_EQ("/*\r\n"
18321             "\r\n"
18322             "*/",
18323             format("/*\r\n"
18324                    "    \r\r\r\n"
18325                    "*/"));
18326 
18327   FormatStyle style = getLLVMStyle();
18328 
18329   style.DeriveLineEnding = true;
18330   style.UseCRLF = false;
18331   EXPECT_EQ("union FooBarBazQux {\n"
18332             "  int foo;\n"
18333             "  int bar;\n"
18334             "  int baz;\n"
18335             "};",
18336             format("union FooBarBazQux {\r\n"
18337                    "  int foo;\n"
18338                    "  int bar;\r\n"
18339                    "  int baz;\n"
18340                    "};",
18341                    style));
18342   style.UseCRLF = true;
18343   EXPECT_EQ("union FooBarBazQux {\r\n"
18344             "  int foo;\r\n"
18345             "  int bar;\r\n"
18346             "  int baz;\r\n"
18347             "};",
18348             format("union FooBarBazQux {\r\n"
18349                    "  int foo;\n"
18350                    "  int bar;\r\n"
18351                    "  int baz;\n"
18352                    "};",
18353                    style));
18354 
18355   style.DeriveLineEnding = false;
18356   style.UseCRLF = false;
18357   EXPECT_EQ("union FooBarBazQux {\n"
18358             "  int foo;\n"
18359             "  int bar;\n"
18360             "  int baz;\n"
18361             "  int qux;\n"
18362             "};",
18363             format("union FooBarBazQux {\r\n"
18364                    "  int foo;\n"
18365                    "  int bar;\r\n"
18366                    "  int baz;\n"
18367                    "  int qux;\r\n"
18368                    "};",
18369                    style));
18370   style.UseCRLF = true;
18371   EXPECT_EQ("union FooBarBazQux {\r\n"
18372             "  int foo;\r\n"
18373             "  int bar;\r\n"
18374             "  int baz;\r\n"
18375             "  int qux;\r\n"
18376             "};",
18377             format("union FooBarBazQux {\r\n"
18378                    "  int foo;\n"
18379                    "  int bar;\r\n"
18380                    "  int baz;\n"
18381                    "  int qux;\n"
18382                    "};",
18383                    style));
18384 
18385   style.DeriveLineEnding = true;
18386   style.UseCRLF = false;
18387   EXPECT_EQ("union FooBarBazQux {\r\n"
18388             "  int foo;\r\n"
18389             "  int bar;\r\n"
18390             "  int baz;\r\n"
18391             "  int qux;\r\n"
18392             "};",
18393             format("union FooBarBazQux {\r\n"
18394                    "  int foo;\n"
18395                    "  int bar;\r\n"
18396                    "  int baz;\n"
18397                    "  int qux;\r\n"
18398                    "};",
18399                    style));
18400   style.UseCRLF = true;
18401   EXPECT_EQ("union FooBarBazQux {\n"
18402             "  int foo;\n"
18403             "  int bar;\n"
18404             "  int baz;\n"
18405             "  int qux;\n"
18406             "};",
18407             format("union FooBarBazQux {\r\n"
18408                    "  int foo;\n"
18409                    "  int bar;\r\n"
18410                    "  int baz;\n"
18411                    "  int qux;\n"
18412                    "};",
18413                    style));
18414 }
18415 
18416 TEST_F(FormatTest, MunchSemicolonAfterBlocks) {
18417   verifyFormat("MY_CLASS(C) {\n"
18418                "  int i;\n"
18419                "  int j;\n"
18420                "};");
18421 }
18422 
18423 TEST_F(FormatTest, ConfigurableContinuationIndentWidth) {
18424   FormatStyle TwoIndent = getLLVMStyleWithColumns(15);
18425   TwoIndent.ContinuationIndentWidth = 2;
18426 
18427   EXPECT_EQ("int i =\n"
18428             "  longFunction(\n"
18429             "    arg);",
18430             format("int i = longFunction(arg);", TwoIndent));
18431 
18432   FormatStyle SixIndent = getLLVMStyleWithColumns(20);
18433   SixIndent.ContinuationIndentWidth = 6;
18434 
18435   EXPECT_EQ("int i =\n"
18436             "      longFunction(\n"
18437             "            arg);",
18438             format("int i = longFunction(arg);", SixIndent));
18439 }
18440 
18441 TEST_F(FormatTest, WrappedClosingParenthesisIndent) {
18442   FormatStyle Style = getLLVMStyle();
18443   verifyFormat("int Foo::getter(\n"
18444                "    //\n"
18445                ") const {\n"
18446                "  return foo;\n"
18447                "}",
18448                Style);
18449   verifyFormat("void Foo::setter(\n"
18450                "    //\n"
18451                ") {\n"
18452                "  foo = 1;\n"
18453                "}",
18454                Style);
18455 }
18456 
18457 TEST_F(FormatTest, SpacesInAngles) {
18458   FormatStyle Spaces = getLLVMStyle();
18459   Spaces.SpacesInAngles = true;
18460 
18461   verifyFormat("static_cast< int >(arg);", Spaces);
18462   verifyFormat("template < typename T0, typename T1 > void f() {}", Spaces);
18463   verifyFormat("f< int, float >();", Spaces);
18464   verifyFormat("template <> g() {}", Spaces);
18465   verifyFormat("template < std::vector< int > > f() {}", Spaces);
18466   verifyFormat("std::function< void(int, int) > fct;", Spaces);
18467   verifyFormat("void inFunction() { std::function< void(int, int) > fct; }",
18468                Spaces);
18469 
18470   Spaces.Standard = FormatStyle::LS_Cpp03;
18471   Spaces.SpacesInAngles = true;
18472   verifyFormat("A< A< int > >();", Spaces);
18473 
18474   Spaces.SpacesInAngles = false;
18475   verifyFormat("A<A<int> >();", Spaces);
18476 
18477   Spaces.Standard = FormatStyle::LS_Cpp11;
18478   Spaces.SpacesInAngles = true;
18479   verifyFormat("A< A< int > >();", Spaces);
18480 
18481   Spaces.SpacesInAngles = false;
18482   verifyFormat("A<A<int>>();", Spaces);
18483 }
18484 
18485 TEST_F(FormatTest, SpaceAfterTemplateKeyword) {
18486   FormatStyle Style = getLLVMStyle();
18487   Style.SpaceAfterTemplateKeyword = false;
18488   verifyFormat("template<int> void foo();", Style);
18489 }
18490 
18491 TEST_F(FormatTest, TripleAngleBrackets) {
18492   verifyFormat("f<<<1, 1>>>();");
18493   verifyFormat("f<<<1, 1, 1, s>>>();");
18494   verifyFormat("f<<<a, b, c, d>>>();");
18495   EXPECT_EQ("f<<<1, 1>>>();", format("f <<< 1, 1 >>> ();"));
18496   verifyFormat("f<param><<<1, 1>>>();");
18497   verifyFormat("f<1><<<1, 1>>>();");
18498   EXPECT_EQ("f<param><<<1, 1>>>();", format("f< param > <<< 1, 1 >>> ();"));
18499   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
18500                "aaaaaaaaaaa<<<\n    1, 1>>>();");
18501   verifyFormat("aaaaaaaaaaaaaaa<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaa>\n"
18502                "    <<<aaaaaaaaa, aaaaaaaaaa, aaaaaaaaaaaaaaaaaa>>>();");
18503 }
18504 
18505 TEST_F(FormatTest, MergeLessLessAtEnd) {
18506   verifyFormat("<<");
18507   EXPECT_EQ("< < <", format("\\\n<<<"));
18508   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
18509                "aaallvm::outs() <<");
18510   verifyFormat("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
18511                "aaaallvm::outs()\n    <<");
18512 }
18513 
18514 TEST_F(FormatTest, HandleUnbalancedImplicitBracesAcrossPPBranches) {
18515   std::string code = "#if A\n"
18516                      "#if B\n"
18517                      "a.\n"
18518                      "#endif\n"
18519                      "    a = 1;\n"
18520                      "#else\n"
18521                      "#endif\n"
18522                      "#if C\n"
18523                      "#else\n"
18524                      "#endif\n";
18525   EXPECT_EQ(code, format(code));
18526 }
18527 
18528 TEST_F(FormatTest, HandleConflictMarkers) {
18529   // Git/SVN conflict markers.
18530   EXPECT_EQ("int a;\n"
18531             "void f() {\n"
18532             "  callme(some(parameter1,\n"
18533             "<<<<<<< text by the vcs\n"
18534             "              parameter2),\n"
18535             "||||||| text by the vcs\n"
18536             "              parameter2),\n"
18537             "         parameter3,\n"
18538             "======= text by the vcs\n"
18539             "              parameter2, parameter3),\n"
18540             ">>>>>>> text by the vcs\n"
18541             "         otherparameter);\n",
18542             format("int a;\n"
18543                    "void f() {\n"
18544                    "  callme(some(parameter1,\n"
18545                    "<<<<<<< text by the vcs\n"
18546                    "  parameter2),\n"
18547                    "||||||| text by the vcs\n"
18548                    "  parameter2),\n"
18549                    "  parameter3,\n"
18550                    "======= text by the vcs\n"
18551                    "  parameter2,\n"
18552                    "  parameter3),\n"
18553                    ">>>>>>> text by the vcs\n"
18554                    "  otherparameter);\n"));
18555 
18556   // Perforce markers.
18557   EXPECT_EQ("void f() {\n"
18558             "  function(\n"
18559             ">>>> text by the vcs\n"
18560             "      parameter,\n"
18561             "==== text by the vcs\n"
18562             "      parameter,\n"
18563             "==== text by the vcs\n"
18564             "      parameter,\n"
18565             "<<<< text by the vcs\n"
18566             "      parameter);\n",
18567             format("void f() {\n"
18568                    "  function(\n"
18569                    ">>>> text by the vcs\n"
18570                    "  parameter,\n"
18571                    "==== text by the vcs\n"
18572                    "  parameter,\n"
18573                    "==== text by the vcs\n"
18574                    "  parameter,\n"
18575                    "<<<< text by the vcs\n"
18576                    "  parameter);\n"));
18577 
18578   EXPECT_EQ("<<<<<<<\n"
18579             "|||||||\n"
18580             "=======\n"
18581             ">>>>>>>",
18582             format("<<<<<<<\n"
18583                    "|||||||\n"
18584                    "=======\n"
18585                    ">>>>>>>"));
18586 
18587   EXPECT_EQ("<<<<<<<\n"
18588             "|||||||\n"
18589             "int i;\n"
18590             "=======\n"
18591             ">>>>>>>",
18592             format("<<<<<<<\n"
18593                    "|||||||\n"
18594                    "int i;\n"
18595                    "=======\n"
18596                    ">>>>>>>"));
18597 
18598   // FIXME: Handle parsing of macros around conflict markers correctly:
18599   EXPECT_EQ("#define Macro \\\n"
18600             "<<<<<<<\n"
18601             "Something \\\n"
18602             "|||||||\n"
18603             "Else \\\n"
18604             "=======\n"
18605             "Other \\\n"
18606             ">>>>>>>\n"
18607             "    End int i;\n",
18608             format("#define Macro \\\n"
18609                    "<<<<<<<\n"
18610                    "  Something \\\n"
18611                    "|||||||\n"
18612                    "  Else \\\n"
18613                    "=======\n"
18614                    "  Other \\\n"
18615                    ">>>>>>>\n"
18616                    "  End\n"
18617                    "int i;\n"));
18618 }
18619 
18620 TEST_F(FormatTest, DisableRegions) {
18621   EXPECT_EQ("int i;\n"
18622             "// clang-format off\n"
18623             "  int j;\n"
18624             "// clang-format on\n"
18625             "int k;",
18626             format(" int  i;\n"
18627                    "   // clang-format off\n"
18628                    "  int j;\n"
18629                    " // clang-format on\n"
18630                    "   int   k;"));
18631   EXPECT_EQ("int i;\n"
18632             "/* clang-format off */\n"
18633             "  int j;\n"
18634             "/* clang-format on */\n"
18635             "int k;",
18636             format(" int  i;\n"
18637                    "   /* clang-format off */\n"
18638                    "  int j;\n"
18639                    " /* clang-format on */\n"
18640                    "   int   k;"));
18641 
18642   // Don't reflow comments within disabled regions.
18643   EXPECT_EQ("// clang-format off\n"
18644             "// long long long long long long line\n"
18645             "/* clang-format on */\n"
18646             "/* long long long\n"
18647             " * long long long\n"
18648             " * line */\n"
18649             "int i;\n"
18650             "/* clang-format off */\n"
18651             "/* long long long long long long line */\n",
18652             format("// clang-format off\n"
18653                    "// long long long long long long line\n"
18654                    "/* clang-format on */\n"
18655                    "/* long long long long long long line */\n"
18656                    "int i;\n"
18657                    "/* clang-format off */\n"
18658                    "/* long long long long long long line */\n",
18659                    getLLVMStyleWithColumns(20)));
18660 }
18661 
18662 TEST_F(FormatTest, DoNotCrashOnInvalidInput) {
18663   format("? ) =");
18664   verifyNoCrash("#define a\\\n /**/}");
18665 }
18666 
18667 TEST_F(FormatTest, FormatsTableGenCode) {
18668   FormatStyle Style = getLLVMStyle();
18669   Style.Language = FormatStyle::LK_TableGen;
18670   verifyFormat("include \"a.td\"\ninclude \"b.td\"", Style);
18671 }
18672 
18673 TEST_F(FormatTest, ArrayOfTemplates) {
18674   EXPECT_EQ("auto a = new unique_ptr<int>[10];",
18675             format("auto a = new unique_ptr<int > [ 10];"));
18676 
18677   FormatStyle Spaces = getLLVMStyle();
18678   Spaces.SpacesInSquareBrackets = true;
18679   EXPECT_EQ("auto a = new unique_ptr<int>[ 10 ];",
18680             format("auto a = new unique_ptr<int > [10];", Spaces));
18681 }
18682 
18683 TEST_F(FormatTest, ArrayAsTemplateType) {
18684   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[10]>;",
18685             format("auto a = unique_ptr < Foo < Bar>[ 10]> ;"));
18686 
18687   FormatStyle Spaces = getLLVMStyle();
18688   Spaces.SpacesInSquareBrackets = true;
18689   EXPECT_EQ("auto a = unique_ptr<Foo<Bar>[ 10 ]>;",
18690             format("auto a = unique_ptr < Foo < Bar>[10]> ;", Spaces));
18691 }
18692 
18693 TEST_F(FormatTest, NoSpaceAfterSuper) { verifyFormat("__super::FooBar();"); }
18694 
18695 TEST(FormatStyle, GetStyleWithEmptyFileName) {
18696   llvm::vfs::InMemoryFileSystem FS;
18697   auto Style1 = getStyle("file", "", "Google", "", &FS);
18698   ASSERT_TRUE((bool)Style1);
18699   ASSERT_EQ(*Style1, getGoogleStyle());
18700 }
18701 
18702 TEST(FormatStyle, GetStyleOfFile) {
18703   llvm::vfs::InMemoryFileSystem FS;
18704   // Test 1: format file in the same directory.
18705   ASSERT_TRUE(
18706       FS.addFile("/a/.clang-format", 0,
18707                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM")));
18708   ASSERT_TRUE(
18709       FS.addFile("/a/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
18710   auto Style1 = getStyle("file", "/a/.clang-format", "Google", "", &FS);
18711   ASSERT_TRUE((bool)Style1);
18712   ASSERT_EQ(*Style1, getLLVMStyle());
18713 
18714   // Test 2.1: fallback to default.
18715   ASSERT_TRUE(
18716       FS.addFile("/b/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
18717   auto Style2 = getStyle("file", "/b/test.cpp", "Mozilla", "", &FS);
18718   ASSERT_TRUE((bool)Style2);
18719   ASSERT_EQ(*Style2, getMozillaStyle());
18720 
18721   // Test 2.2: no format on 'none' fallback style.
18722   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
18723   ASSERT_TRUE((bool)Style2);
18724   ASSERT_EQ(*Style2, getNoStyle());
18725 
18726   // Test 2.3: format if config is found with no based style while fallback is
18727   // 'none'.
18728   ASSERT_TRUE(FS.addFile("/b/.clang-format", 0,
18729                          llvm::MemoryBuffer::getMemBuffer("IndentWidth: 2")));
18730   Style2 = getStyle("file", "/b/test.cpp", "none", "", &FS);
18731   ASSERT_TRUE((bool)Style2);
18732   ASSERT_EQ(*Style2, getLLVMStyle());
18733 
18734   // Test 2.4: format if yaml with no based style, while fallback is 'none'.
18735   Style2 = getStyle("{}", "a.h", "none", "", &FS);
18736   ASSERT_TRUE((bool)Style2);
18737   ASSERT_EQ(*Style2, getLLVMStyle());
18738 
18739   // Test 3: format file in parent directory.
18740   ASSERT_TRUE(
18741       FS.addFile("/c/.clang-format", 0,
18742                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google")));
18743   ASSERT_TRUE(FS.addFile("/c/sub/sub/sub/test.cpp", 0,
18744                          llvm::MemoryBuffer::getMemBuffer("int i;")));
18745   auto Style3 = getStyle("file", "/c/sub/sub/sub/test.cpp", "LLVM", "", &FS);
18746   ASSERT_TRUE((bool)Style3);
18747   ASSERT_EQ(*Style3, getGoogleStyle());
18748 
18749   // Test 4: error on invalid fallback style
18750   auto Style4 = getStyle("file", "a.h", "KungFu", "", &FS);
18751   ASSERT_FALSE((bool)Style4);
18752   llvm::consumeError(Style4.takeError());
18753 
18754   // Test 5: error on invalid yaml on command line
18755   auto Style5 = getStyle("{invalid_key=invalid_value}", "a.h", "LLVM", "", &FS);
18756   ASSERT_FALSE((bool)Style5);
18757   llvm::consumeError(Style5.takeError());
18758 
18759   // Test 6: error on invalid style
18760   auto Style6 = getStyle("KungFu", "a.h", "LLVM", "", &FS);
18761   ASSERT_FALSE((bool)Style6);
18762   llvm::consumeError(Style6.takeError());
18763 
18764   // Test 7: found config file, error on parsing it
18765   ASSERT_TRUE(
18766       FS.addFile("/d/.clang-format", 0,
18767                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: LLVM\n"
18768                                                   "InvalidKey: InvalidValue")));
18769   ASSERT_TRUE(
18770       FS.addFile("/d/test.cpp", 0, llvm::MemoryBuffer::getMemBuffer("int i;")));
18771   auto Style7a = getStyle("file", "/d/.clang-format", "LLVM", "", &FS);
18772   ASSERT_FALSE((bool)Style7a);
18773   llvm::consumeError(Style7a.takeError());
18774 
18775   auto Style7b = getStyle("file", "/d/.clang-format", "LLVM", "", &FS, true);
18776   ASSERT_TRUE((bool)Style7b);
18777 
18778   // Test 8: inferred per-language defaults apply.
18779   auto StyleTd = getStyle("file", "x.td", "llvm", "", &FS);
18780   ASSERT_TRUE((bool)StyleTd);
18781   ASSERT_EQ(*StyleTd, getLLVMStyle(FormatStyle::LK_TableGen));
18782 
18783   // Test 9.1: overwriting a file style, when parent no file exists with no
18784   // fallback style
18785   ASSERT_TRUE(FS.addFile(
18786       "/e/sub/.clang-format", 0,
18787       llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: InheritParentConfig\n"
18788                                        "ColumnLimit: 20")));
18789   ASSERT_TRUE(FS.addFile("/e/sub/code.cpp", 0,
18790                          llvm::MemoryBuffer::getMemBuffer("int i;")));
18791   auto Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
18792   ASSERT_TRUE(static_cast<bool>(Style9));
18793   ASSERT_EQ(*Style9, [] {
18794     auto Style = getNoStyle();
18795     Style.ColumnLimit = 20;
18796     return Style;
18797   }());
18798 
18799   // Test 9.2: with LLVM fallback style
18800   Style9 = getStyle("file", "/e/sub/code.cpp", "LLVM", "", &FS);
18801   ASSERT_TRUE(static_cast<bool>(Style9));
18802   ASSERT_EQ(*Style9, [] {
18803     auto Style = getLLVMStyle();
18804     Style.ColumnLimit = 20;
18805     return Style;
18806   }());
18807 
18808   // Test 9.3: with a parent file
18809   ASSERT_TRUE(
18810       FS.addFile("/e/.clang-format", 0,
18811                  llvm::MemoryBuffer::getMemBuffer("BasedOnStyle: Google\n"
18812                                                   "UseTab: Always")));
18813   Style9 = getStyle("file", "/e/sub/code.cpp", "none", "", &FS);
18814   ASSERT_TRUE(static_cast<bool>(Style9));
18815   ASSERT_EQ(*Style9, [] {
18816     auto Style = getGoogleStyle();
18817     Style.ColumnLimit = 20;
18818     Style.UseTab = FormatStyle::UT_Always;
18819     return Style;
18820   }());
18821 
18822   // Test 9.4: propagate more than one level
18823   ASSERT_TRUE(FS.addFile("/e/sub/sub/code.cpp", 0,
18824                          llvm::MemoryBuffer::getMemBuffer("int i;")));
18825   ASSERT_TRUE(FS.addFile("/e/sub/sub/.clang-format", 0,
18826                          llvm::MemoryBuffer::getMemBuffer(
18827                              "BasedOnStyle: InheritParentConfig\n"
18828                              "WhitespaceSensitiveMacros: ['FOO', 'BAR']")));
18829   std::vector<std::string> NonDefaultWhiteSpaceMacros{"FOO", "BAR"};
18830 
18831   const auto SubSubStyle = [&NonDefaultWhiteSpaceMacros] {
18832     auto Style = getGoogleStyle();
18833     Style.ColumnLimit = 20;
18834     Style.UseTab = FormatStyle::UT_Always;
18835     Style.WhitespaceSensitiveMacros = NonDefaultWhiteSpaceMacros;
18836     return Style;
18837   }();
18838 
18839   ASSERT_NE(Style9->WhitespaceSensitiveMacros, NonDefaultWhiteSpaceMacros);
18840   Style9 = getStyle("file", "/e/sub/sub/code.cpp", "none", "", &FS);
18841   ASSERT_TRUE(static_cast<bool>(Style9));
18842   ASSERT_EQ(*Style9, SubSubStyle);
18843 
18844   // Test 9.5: use InheritParentConfig as style name
18845   Style9 =
18846       getStyle("inheritparentconfig", "/e/sub/sub/code.cpp", "none", "", &FS);
18847   ASSERT_TRUE(static_cast<bool>(Style9));
18848   ASSERT_EQ(*Style9, SubSubStyle);
18849 
18850   // Test 9.6: use command line style with inheritance
18851   Style9 = getStyle("{BasedOnStyle: InheritParentConfig}", "/e/sub/code.cpp",
18852                     "none", "", &FS);
18853   ASSERT_TRUE(static_cast<bool>(Style9));
18854   ASSERT_EQ(*Style9, SubSubStyle);
18855 
18856   // Test 9.7: use command line style with inheritance and own config
18857   Style9 = getStyle("{BasedOnStyle: InheritParentConfig, "
18858                     "WhitespaceSensitiveMacros: ['FOO', 'BAR']}",
18859                     "/e/sub/code.cpp", "none", "", &FS);
18860   ASSERT_TRUE(static_cast<bool>(Style9));
18861   ASSERT_EQ(*Style9, SubSubStyle);
18862 
18863   // Test 9.8: use inheritance from a file without BasedOnStyle
18864   ASSERT_TRUE(FS.addFile("/e/withoutbase/.clang-format", 0,
18865                          llvm::MemoryBuffer::getMemBuffer("ColumnLimit: 123")));
18866   ASSERT_TRUE(
18867       FS.addFile("/e/withoutbase/sub/.clang-format", 0,
18868                  llvm::MemoryBuffer::getMemBuffer(
18869                      "BasedOnStyle: InheritParentConfig\nIndentWidth: 7")));
18870   // Make sure we do not use the fallback style
18871   Style9 = getStyle("file", "/e/withoutbase/code.cpp", "google", "", &FS);
18872   ASSERT_TRUE(static_cast<bool>(Style9));
18873   ASSERT_EQ(*Style9, [] {
18874     auto Style = getLLVMStyle();
18875     Style.ColumnLimit = 123;
18876     return Style;
18877   }());
18878 
18879   Style9 = getStyle("file", "/e/withoutbase/sub/code.cpp", "google", "", &FS);
18880   ASSERT_TRUE(static_cast<bool>(Style9));
18881   ASSERT_EQ(*Style9, [] {
18882     auto Style = getLLVMStyle();
18883     Style.ColumnLimit = 123;
18884     Style.IndentWidth = 7;
18885     return Style;
18886   }());
18887 }
18888 
18889 TEST_F(ReplacementTest, FormatCodeAfterReplacements) {
18890   // Column limit is 20.
18891   std::string Code = "Type *a =\n"
18892                      "    new Type();\n"
18893                      "g(iiiii, 0, jjjjj,\n"
18894                      "  0, kkkkk, 0, mm);\n"
18895                      "int  bad     = format   ;";
18896   std::string Expected = "auto a = new Type();\n"
18897                          "g(iiiii, nullptr,\n"
18898                          "  jjjjj, nullptr,\n"
18899                          "  kkkkk, nullptr,\n"
18900                          "  mm);\n"
18901                          "int  bad     = format   ;";
18902   FileID ID = Context.createInMemoryFile("format.cpp", Code);
18903   tooling::Replacements Replaces = toReplacements(
18904       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 6,
18905                             "auto "),
18906        tooling::Replacement(Context.Sources, Context.getLocation(ID, 3, 10), 1,
18907                             "nullptr"),
18908        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 3), 1,
18909                             "nullptr"),
18910        tooling::Replacement(Context.Sources, Context.getLocation(ID, 4, 13), 1,
18911                             "nullptr")});
18912 
18913   format::FormatStyle Style = format::getLLVMStyle();
18914   Style.ColumnLimit = 20; // Set column limit to 20 to increase readibility.
18915   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
18916   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
18917       << llvm::toString(FormattedReplaces.takeError()) << "\n";
18918   auto Result = applyAllReplacements(Code, *FormattedReplaces);
18919   EXPECT_TRUE(static_cast<bool>(Result));
18920   EXPECT_EQ(Expected, *Result);
18921 }
18922 
18923 TEST_F(ReplacementTest, SortIncludesAfterReplacement) {
18924   std::string Code = "#include \"a.h\"\n"
18925                      "#include \"c.h\"\n"
18926                      "\n"
18927                      "int main() {\n"
18928                      "  return 0;\n"
18929                      "}";
18930   std::string Expected = "#include \"a.h\"\n"
18931                          "#include \"b.h\"\n"
18932                          "#include \"c.h\"\n"
18933                          "\n"
18934                          "int main() {\n"
18935                          "  return 0;\n"
18936                          "}";
18937   FileID ID = Context.createInMemoryFile("fix.cpp", Code);
18938   tooling::Replacements Replaces = toReplacements(
18939       {tooling::Replacement(Context.Sources, Context.getLocation(ID, 1, 1), 0,
18940                             "#include \"b.h\"\n")});
18941 
18942   format::FormatStyle Style = format::getLLVMStyle();
18943   Style.SortIncludes = FormatStyle::SI_CaseSensitive;
18944   auto FormattedReplaces = formatReplacements(Code, Replaces, Style);
18945   EXPECT_TRUE(static_cast<bool>(FormattedReplaces))
18946       << llvm::toString(FormattedReplaces.takeError()) << "\n";
18947   auto Result = applyAllReplacements(Code, *FormattedReplaces);
18948   EXPECT_TRUE(static_cast<bool>(Result));
18949   EXPECT_EQ(Expected, *Result);
18950 }
18951 
18952 TEST_F(FormatTest, FormatSortsUsingDeclarations) {
18953   EXPECT_EQ("using std::cin;\n"
18954             "using std::cout;",
18955             format("using std::cout;\n"
18956                    "using std::cin;",
18957                    getGoogleStyle()));
18958 }
18959 
18960 TEST_F(FormatTest, UTF8CharacterLiteralCpp03) {
18961   format::FormatStyle Style = format::getLLVMStyle();
18962   Style.Standard = FormatStyle::LS_Cpp03;
18963   // cpp03 recognize this string as identifier u8 and literal character 'a'
18964   EXPECT_EQ("auto c = u8 'a';", format("auto c = u8'a';", Style));
18965 }
18966 
18967 TEST_F(FormatTest, UTF8CharacterLiteralCpp11) {
18968   // u8'a' is a C++17 feature, utf8 literal character, LS_Cpp11 covers
18969   // all modes, including C++11, C++14 and C++17
18970   EXPECT_EQ("auto c = u8'a';", format("auto c = u8'a';"));
18971 }
18972 
18973 TEST_F(FormatTest, DoNotFormatLikelyXml) {
18974   EXPECT_EQ("<!-- ;> -->", format("<!-- ;> -->", getGoogleStyle()));
18975   EXPECT_EQ(" <!-- >; -->", format(" <!-- >; -->", getGoogleStyle()));
18976 }
18977 
18978 TEST_F(FormatTest, StructuredBindings) {
18979   // Structured bindings is a C++17 feature.
18980   // all modes, including C++11, C++14 and C++17
18981   verifyFormat("auto [a, b] = f();");
18982   EXPECT_EQ("auto [a, b] = f();", format("auto[a, b] = f();"));
18983   EXPECT_EQ("const auto [a, b] = f();", format("const   auto[a, b] = f();"));
18984   EXPECT_EQ("auto const [a, b] = f();", format("auto  const[a, b] = f();"));
18985   EXPECT_EQ("auto const volatile [a, b] = f();",
18986             format("auto  const   volatile[a, b] = f();"));
18987   EXPECT_EQ("auto [a, b, c] = f();", format("auto   [  a  ,  b,c   ] = f();"));
18988   EXPECT_EQ("auto &[a, b, c] = f();",
18989             format("auto   &[  a  ,  b,c   ] = f();"));
18990   EXPECT_EQ("auto &&[a, b, c] = f();",
18991             format("auto   &&[  a  ,  b,c   ] = f();"));
18992   EXPECT_EQ("auto const &[a, b] = f();", format("auto  const&[a, b] = f();"));
18993   EXPECT_EQ("auto const volatile &&[a, b] = f();",
18994             format("auto  const  volatile  &&[a, b] = f();"));
18995   EXPECT_EQ("auto const &&[a, b] = f();",
18996             format("auto  const   &&  [a, b] = f();"));
18997   EXPECT_EQ("const auto &[a, b] = f();",
18998             format("const  auto  &  [a, b] = f();"));
18999   EXPECT_EQ("const auto volatile &&[a, b] = f();",
19000             format("const  auto   volatile  &&[a, b] = f();"));
19001   EXPECT_EQ("volatile const auto &&[a, b] = f();",
19002             format("volatile  const  auto   &&[a, b] = f();"));
19003   EXPECT_EQ("const auto &&[a, b] = f();",
19004             format("const  auto  &&  [a, b] = f();"));
19005 
19006   // Make sure we don't mistake structured bindings for lambdas.
19007   FormatStyle PointerMiddle = getLLVMStyle();
19008   PointerMiddle.PointerAlignment = FormatStyle::PAS_Middle;
19009   verifyFormat("auto [a1, b]{A * i};", getGoogleStyle());
19010   verifyFormat("auto [a2, b]{A * i};", getLLVMStyle());
19011   verifyFormat("auto [a3, b]{A * i};", PointerMiddle);
19012   verifyFormat("auto const [a1, b]{A * i};", getGoogleStyle());
19013   verifyFormat("auto const [a2, b]{A * i};", getLLVMStyle());
19014   verifyFormat("auto const [a3, b]{A * i};", PointerMiddle);
19015   verifyFormat("auto const& [a1, b]{A * i};", getGoogleStyle());
19016   verifyFormat("auto const &[a2, b]{A * i};", getLLVMStyle());
19017   verifyFormat("auto const & [a3, b]{A * i};", PointerMiddle);
19018   verifyFormat("auto const&& [a1, b]{A * i};", getGoogleStyle());
19019   verifyFormat("auto const &&[a2, b]{A * i};", getLLVMStyle());
19020   verifyFormat("auto const && [a3, b]{A * i};", PointerMiddle);
19021 
19022   EXPECT_EQ("for (const auto &&[a, b] : some_range) {\n}",
19023             format("for (const auto   &&   [a, b] : some_range) {\n}"));
19024   EXPECT_EQ("for (const auto &[a, b] : some_range) {\n}",
19025             format("for (const auto   &   [a, b] : some_range) {\n}"));
19026   EXPECT_EQ("for (const auto [a, b] : some_range) {\n}",
19027             format("for (const auto[a, b] : some_range) {\n}"));
19028   EXPECT_EQ("auto [x, y](expr);", format("auto[x,y]  (expr);"));
19029   EXPECT_EQ("auto &[x, y](expr);", format("auto  &  [x,y]  (expr);"));
19030   EXPECT_EQ("auto &&[x, y](expr);", format("auto  &&  [x,y]  (expr);"));
19031   EXPECT_EQ("auto const &[x, y](expr);",
19032             format("auto  const  &  [x,y]  (expr);"));
19033   EXPECT_EQ("auto const &&[x, y](expr);",
19034             format("auto  const  &&  [x,y]  (expr);"));
19035   EXPECT_EQ("auto [x, y]{expr};", format("auto[x,y]     {expr};"));
19036   EXPECT_EQ("auto const &[x, y]{expr};",
19037             format("auto  const  &  [x,y]  {expr};"));
19038   EXPECT_EQ("auto const &&[x, y]{expr};",
19039             format("auto  const  &&  [x,y]  {expr};"));
19040 
19041   format::FormatStyle Spaces = format::getLLVMStyle();
19042   Spaces.SpacesInSquareBrackets = true;
19043   verifyFormat("auto [ a, b ] = f();", Spaces);
19044   verifyFormat("auto &&[ a, b ] = f();", Spaces);
19045   verifyFormat("auto &[ a, b ] = f();", Spaces);
19046   verifyFormat("auto const &&[ a, b ] = f();", Spaces);
19047   verifyFormat("auto const &[ a, b ] = f();", Spaces);
19048 }
19049 
19050 TEST_F(FormatTest, FileAndCode) {
19051   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.cc", ""));
19052   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.m", ""));
19053   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.mm", ""));
19054   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", ""));
19055   EXPECT_EQ(FormatStyle::LK_ObjC,
19056             guessLanguage("foo.h", "@interface Foo\n@end\n"));
19057   EXPECT_EQ(
19058       FormatStyle::LK_ObjC,
19059       guessLanguage("foo.h", "#define TRY(x, y) @try { x; } @finally { y; }"));
19060   EXPECT_EQ(FormatStyle::LK_ObjC,
19061             guessLanguage("foo.h", "#define AVAIL(x) @available(x, *))"));
19062   EXPECT_EQ(FormatStyle::LK_ObjC, guessLanguage("foo.h", "@class Foo;"));
19063   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo", ""));
19064   EXPECT_EQ(FormatStyle::LK_ObjC,
19065             guessLanguage("foo", "@interface Foo\n@end\n"));
19066   EXPECT_EQ(FormatStyle::LK_ObjC,
19067             guessLanguage("foo.h", "int DoStuff(CGRect rect);\n"));
19068   EXPECT_EQ(
19069       FormatStyle::LK_ObjC,
19070       guessLanguage("foo.h",
19071                     "#define MY_POINT_MAKE(x, y) CGPointMake((x), (y));\n"));
19072   EXPECT_EQ(
19073       FormatStyle::LK_Cpp,
19074       guessLanguage("foo.h", "#define FOO(...) auto bar = [] __VA_ARGS__;"));
19075 }
19076 
19077 TEST_F(FormatTest, GuessLanguageWithCpp11AttributeSpecifiers) {
19078   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[noreturn]];"));
19079   EXPECT_EQ(FormatStyle::LK_ObjC,
19080             guessLanguage("foo.h", "array[[calculator getIndex]];"));
19081   EXPECT_EQ(FormatStyle::LK_Cpp,
19082             guessLanguage("foo.h", "[[noreturn, deprecated(\"so sorry\")]];"));
19083   EXPECT_EQ(
19084       FormatStyle::LK_Cpp,
19085       guessLanguage("foo.h", "[[noreturn, deprecated(\"gone, sorry\")]];"));
19086   EXPECT_EQ(FormatStyle::LK_ObjC,
19087             guessLanguage("foo.h", "[[noreturn foo] bar];"));
19088   EXPECT_EQ(FormatStyle::LK_Cpp,
19089             guessLanguage("foo.h", "[[clang::fallthrough]];"));
19090   EXPECT_EQ(FormatStyle::LK_ObjC,
19091             guessLanguage("foo.h", "[[clang:fallthrough] foo];"));
19092   EXPECT_EQ(FormatStyle::LK_Cpp,
19093             guessLanguage("foo.h", "[[gsl::suppress(\"type\")]];"));
19094   EXPECT_EQ(FormatStyle::LK_Cpp,
19095             guessLanguage("foo.h", "[[using clang: fallthrough]];"));
19096   EXPECT_EQ(FormatStyle::LK_ObjC,
19097             guessLanguage("foo.h", "[[abusing clang:fallthrough] bar];"));
19098   EXPECT_EQ(FormatStyle::LK_Cpp,
19099             guessLanguage("foo.h", "[[using gsl: suppress(\"type\")]];"));
19100   EXPECT_EQ(
19101       FormatStyle::LK_Cpp,
19102       guessLanguage("foo.h", "for (auto &&[endpoint, stream] : streams_)"));
19103   EXPECT_EQ(
19104       FormatStyle::LK_Cpp,
19105       guessLanguage("foo.h",
19106                     "[[clang::callable_when(\"unconsumed\", \"unknown\")]]"));
19107   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "[[foo::bar, ...]]"));
19108 }
19109 
19110 TEST_F(FormatTest, GuessLanguageWithCaret) {
19111   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^);"));
19112   EXPECT_EQ(FormatStyle::LK_Cpp, guessLanguage("foo.h", "FOO(^, Bar);"));
19113   EXPECT_EQ(FormatStyle::LK_ObjC,
19114             guessLanguage("foo.h", "int(^)(char, float);"));
19115   EXPECT_EQ(FormatStyle::LK_ObjC,
19116             guessLanguage("foo.h", "int(^foo)(char, float);"));
19117   EXPECT_EQ(FormatStyle::LK_ObjC,
19118             guessLanguage("foo.h", "int(^foo[10])(char, float);"));
19119   EXPECT_EQ(FormatStyle::LK_ObjC,
19120             guessLanguage("foo.h", "int(^foo[kNumEntries])(char, float);"));
19121   EXPECT_EQ(
19122       FormatStyle::LK_ObjC,
19123       guessLanguage("foo.h", "int(^foo[(kNumEntries + 10)])(char, float);"));
19124 }
19125 
19126 TEST_F(FormatTest, GuessLanguageWithPragmas) {
19127   EXPECT_EQ(FormatStyle::LK_Cpp,
19128             guessLanguage("foo.h", "__pragma(warning(disable:))"));
19129   EXPECT_EQ(FormatStyle::LK_Cpp,
19130             guessLanguage("foo.h", "#pragma(warning(disable:))"));
19131   EXPECT_EQ(FormatStyle::LK_Cpp,
19132             guessLanguage("foo.h", "_Pragma(warning(disable:))"));
19133 }
19134 
19135 TEST_F(FormatTest, FormatsInlineAsmSymbolicNames) {
19136   // ASM symbolic names are identifiers that must be surrounded by [] without
19137   // space in between:
19138   // https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#InputOperands
19139 
19140   // Example from https://bugs.llvm.org/show_bug.cgi?id=45108.
19141   verifyFormat(R"(//
19142 asm volatile("mrs %x[result], FPCR" : [result] "=r"(result));
19143 )");
19144 
19145   // A list of several ASM symbolic names.
19146   verifyFormat(R"(asm("mov %[e], %[d]" : [d] "=rm"(d), [e] "rm"(*e));)");
19147 
19148   // ASM symbolic names in inline ASM with inputs and outputs.
19149   verifyFormat(R"(//
19150 asm("cmoveq %1, %2, %[result]"
19151     : [result] "=r"(result)
19152     : "r"(test), "r"(new), "[result]"(old));
19153 )");
19154 
19155   // ASM symbolic names in inline ASM with no outputs.
19156   verifyFormat(R"(asm("mov %[e], %[d]" : : [d] "=rm"(d), [e] "rm"(*e));)");
19157 }
19158 
19159 TEST_F(FormatTest, GuessedLanguageWithInlineAsmClobbers) {
19160   EXPECT_EQ(FormatStyle::LK_Cpp,
19161             guessLanguage("foo.h", "void f() {\n"
19162                                    "  asm (\"mov %[e], %[d]\"\n"
19163                                    "     : [d] \"=rm\" (d)\n"
19164                                    "       [e] \"rm\" (*e));\n"
19165                                    "}"));
19166   EXPECT_EQ(FormatStyle::LK_Cpp,
19167             guessLanguage("foo.h", "void f() {\n"
19168                                    "  _asm (\"mov %[e], %[d]\"\n"
19169                                    "     : [d] \"=rm\" (d)\n"
19170                                    "       [e] \"rm\" (*e));\n"
19171                                    "}"));
19172   EXPECT_EQ(FormatStyle::LK_Cpp,
19173             guessLanguage("foo.h", "void f() {\n"
19174                                    "  __asm (\"mov %[e], %[d]\"\n"
19175                                    "     : [d] \"=rm\" (d)\n"
19176                                    "       [e] \"rm\" (*e));\n"
19177                                    "}"));
19178   EXPECT_EQ(FormatStyle::LK_Cpp,
19179             guessLanguage("foo.h", "void f() {\n"
19180                                    "  __asm__ (\"mov %[e], %[d]\"\n"
19181                                    "     : [d] \"=rm\" (d)\n"
19182                                    "       [e] \"rm\" (*e));\n"
19183                                    "}"));
19184   EXPECT_EQ(FormatStyle::LK_Cpp,
19185             guessLanguage("foo.h", "void f() {\n"
19186                                    "  asm (\"mov %[e], %[d]\"\n"
19187                                    "     : [d] \"=rm\" (d),\n"
19188                                    "       [e] \"rm\" (*e));\n"
19189                                    "}"));
19190   EXPECT_EQ(FormatStyle::LK_Cpp,
19191             guessLanguage("foo.h", "void f() {\n"
19192                                    "  asm volatile (\"mov %[e], %[d]\"\n"
19193                                    "     : [d] \"=rm\" (d)\n"
19194                                    "       [e] \"rm\" (*e));\n"
19195                                    "}"));
19196 }
19197 
19198 TEST_F(FormatTest, GuessLanguageWithChildLines) {
19199   EXPECT_EQ(FormatStyle::LK_Cpp,
19200             guessLanguage("foo.h", "#define FOO ({ std::string s; })"));
19201   EXPECT_EQ(FormatStyle::LK_ObjC,
19202             guessLanguage("foo.h", "#define FOO ({ NSString *s; })"));
19203   EXPECT_EQ(
19204       FormatStyle::LK_Cpp,
19205       guessLanguage("foo.h", "#define FOO ({ foo(); ({ std::string s; }) })"));
19206   EXPECT_EQ(
19207       FormatStyle::LK_ObjC,
19208       guessLanguage("foo.h", "#define FOO ({ foo(); ({ NSString *s; }) })"));
19209 }
19210 
19211 TEST_F(FormatTest, TypenameMacros) {
19212   std::vector<std::string> TypenameMacros = {"STACK_OF", "LIST", "TAILQ_ENTRY"};
19213 
19214   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=30353
19215   FormatStyle Google = getGoogleStyleWithColumns(0);
19216   Google.TypenameMacros = TypenameMacros;
19217   verifyFormat("struct foo {\n"
19218                "  int bar;\n"
19219                "  TAILQ_ENTRY(a) bleh;\n"
19220                "};",
19221                Google);
19222 
19223   FormatStyle Macros = getLLVMStyle();
19224   Macros.TypenameMacros = TypenameMacros;
19225 
19226   verifyFormat("STACK_OF(int) a;", Macros);
19227   verifyFormat("STACK_OF(int) *a;", Macros);
19228   verifyFormat("STACK_OF(int const *) *a;", Macros);
19229   verifyFormat("STACK_OF(int *const) *a;", Macros);
19230   verifyFormat("STACK_OF(int, string) a;", Macros);
19231   verifyFormat("STACK_OF(LIST(int)) a;", Macros);
19232   verifyFormat("STACK_OF(LIST(int)) a, b;", Macros);
19233   verifyFormat("for (LIST(int) *a = NULL; a;) {\n}", Macros);
19234   verifyFormat("STACK_OF(int) f(LIST(int) *arg);", Macros);
19235   verifyFormat("vector<LIST(uint64_t) *attr> x;", Macros);
19236   verifyFormat("vector<LIST(uint64_t) *const> f(LIST(uint64_t) *arg);", Macros);
19237 
19238   Macros.PointerAlignment = FormatStyle::PAS_Left;
19239   verifyFormat("STACK_OF(int)* a;", Macros);
19240   verifyFormat("STACK_OF(int*)* a;", Macros);
19241   verifyFormat("x = (STACK_OF(uint64_t))*a;", Macros);
19242   verifyFormat("x = (STACK_OF(uint64_t))&a;", Macros);
19243   verifyFormat("vector<STACK_OF(uint64_t)* attr> x;", Macros);
19244 }
19245 
19246 TEST_F(FormatTest, AtomicQualifier) {
19247   // Check that we treate _Atomic as a type and not a function call
19248   FormatStyle Google = getGoogleStyleWithColumns(0);
19249   verifyFormat("struct foo {\n"
19250                "  int a1;\n"
19251                "  _Atomic(a) a2;\n"
19252                "  _Atomic(_Atomic(int) *const) a3;\n"
19253                "};",
19254                Google);
19255   verifyFormat("_Atomic(uint64_t) a;");
19256   verifyFormat("_Atomic(uint64_t) *a;");
19257   verifyFormat("_Atomic(uint64_t const *) *a;");
19258   verifyFormat("_Atomic(uint64_t *const) *a;");
19259   verifyFormat("_Atomic(const uint64_t *) *a;");
19260   verifyFormat("_Atomic(uint64_t) a;");
19261   verifyFormat("_Atomic(_Atomic(uint64_t)) a;");
19262   verifyFormat("_Atomic(_Atomic(uint64_t)) a, b;");
19263   verifyFormat("for (_Atomic(uint64_t) *a = NULL; a;) {\n}");
19264   verifyFormat("_Atomic(uint64_t) f(_Atomic(uint64_t) *arg);");
19265 
19266   verifyFormat("_Atomic(uint64_t) *s(InitValue);");
19267   verifyFormat("_Atomic(uint64_t) *s{InitValue};");
19268   FormatStyle Style = getLLVMStyle();
19269   Style.PointerAlignment = FormatStyle::PAS_Left;
19270   verifyFormat("_Atomic(uint64_t)* s(InitValue);", Style);
19271   verifyFormat("_Atomic(uint64_t)* s{InitValue};", Style);
19272   verifyFormat("_Atomic(int)* a;", Style);
19273   verifyFormat("_Atomic(int*)* a;", Style);
19274   verifyFormat("vector<_Atomic(uint64_t)* attr> x;", Style);
19275 
19276   Style.SpacesInCStyleCastParentheses = true;
19277   Style.SpacesInParentheses = false;
19278   verifyFormat("x = ( _Atomic(uint64_t) )*a;", Style);
19279   Style.SpacesInCStyleCastParentheses = false;
19280   Style.SpacesInParentheses = true;
19281   verifyFormat("x = (_Atomic( uint64_t ))*a;", Style);
19282   verifyFormat("x = (_Atomic( uint64_t ))&a;", Style);
19283 }
19284 
19285 TEST_F(FormatTest, AmbersandInLamda) {
19286   // Test case reported in https://bugs.llvm.org/show_bug.cgi?id=41899
19287   FormatStyle AlignStyle = getLLVMStyle();
19288   AlignStyle.PointerAlignment = FormatStyle::PAS_Left;
19289   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
19290   AlignStyle.PointerAlignment = FormatStyle::PAS_Right;
19291   verifyFormat("auto lambda = [&a = a]() { a = 2; };", AlignStyle);
19292 }
19293 
19294 TEST_F(FormatTest, SpacesInConditionalStatement) {
19295   FormatStyle Spaces = getLLVMStyle();
19296   Spaces.SpacesInConditionalStatement = true;
19297   verifyFormat("for ( int i = 0; i; i++ )\n  continue;", Spaces);
19298   verifyFormat("if ( !a )\n  return;", Spaces);
19299   verifyFormat("if ( a )\n  return;", Spaces);
19300   verifyFormat("if constexpr ( a )\n  return;", Spaces);
19301   verifyFormat("switch ( a )\ncase 1:\n  return;", Spaces);
19302   verifyFormat("while ( a )\n  return;", Spaces);
19303   verifyFormat("while ( (a && b) )\n  return;", Spaces);
19304   verifyFormat("do {\n} while ( 1 != 0 );", Spaces);
19305   verifyFormat("try {\n} catch ( const std::exception & ) {\n}", Spaces);
19306   // Check that space on the left of "::" is inserted as expected at beginning
19307   // of condition.
19308   verifyFormat("while ( ::func() )\n  return;", Spaces);
19309 }
19310 
19311 TEST_F(FormatTest, AlternativeOperators) {
19312   // Test case for ensuring alternate operators are not
19313   // combined with their right most neighbour.
19314   verifyFormat("int a and b;");
19315   verifyFormat("int a and_eq b;");
19316   verifyFormat("int a bitand b;");
19317   verifyFormat("int a bitor b;");
19318   verifyFormat("int a compl b;");
19319   verifyFormat("int a not b;");
19320   verifyFormat("int a not_eq b;");
19321   verifyFormat("int a or b;");
19322   verifyFormat("int a xor b;");
19323   verifyFormat("int a xor_eq b;");
19324   verifyFormat("return this not_eq bitand other;");
19325   verifyFormat("bool operator not_eq(const X bitand other)");
19326 
19327   verifyFormat("int a and 5;");
19328   verifyFormat("int a and_eq 5;");
19329   verifyFormat("int a bitand 5;");
19330   verifyFormat("int a bitor 5;");
19331   verifyFormat("int a compl 5;");
19332   verifyFormat("int a not 5;");
19333   verifyFormat("int a not_eq 5;");
19334   verifyFormat("int a or 5;");
19335   verifyFormat("int a xor 5;");
19336   verifyFormat("int a xor_eq 5;");
19337 
19338   verifyFormat("int a compl(5);");
19339   verifyFormat("int a not(5);");
19340 
19341   /* FIXME handle alternate tokens
19342    * https://en.cppreference.com/w/cpp/language/operator_alternative
19343   // alternative tokens
19344   verifyFormat("compl foo();");     //  ~foo();
19345   verifyFormat("foo() <%%>;");      // foo();
19346   verifyFormat("void foo() <%%>;"); // void foo(){}
19347   verifyFormat("int a <:1:>;");     // int a[1];[
19348   verifyFormat("%:define ABC abc"); // #define ABC abc
19349   verifyFormat("%:%:");             // ##
19350   */
19351 }
19352 
19353 TEST_F(FormatTest, STLWhileNotDefineChed) {
19354   verifyFormat("#if defined(while)\n"
19355                "#define while EMIT WARNING C4005\n"
19356                "#endif // while");
19357 }
19358 
19359 TEST_F(FormatTest, OperatorSpacing) {
19360   FormatStyle Style = getLLVMStyle();
19361   Style.PointerAlignment = FormatStyle::PAS_Right;
19362   verifyFormat("Foo::operator*();", Style);
19363   verifyFormat("Foo::operator void *();", Style);
19364   verifyFormat("Foo::operator void **();", Style);
19365   verifyFormat("Foo::operator void *&();", Style);
19366   verifyFormat("Foo::operator void *&&();", Style);
19367   verifyFormat("Foo::operator void const *();", Style);
19368   verifyFormat("Foo::operator void const **();", Style);
19369   verifyFormat("Foo::operator void const *&();", Style);
19370   verifyFormat("Foo::operator void const *&&();", Style);
19371   verifyFormat("Foo::operator()(void *);", Style);
19372   verifyFormat("Foo::operator*(void *);", Style);
19373   verifyFormat("Foo::operator*();", Style);
19374   verifyFormat("Foo::operator**();", Style);
19375   verifyFormat("Foo::operator&();", Style);
19376   verifyFormat("Foo::operator<int> *();", 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("Foo::operator<int> *&();", Style);
19385   verifyFormat("Foo::operator<Foo> *&();", Style);
19386   verifyFormat("Foo::operator<int> *&&();", Style);
19387   verifyFormat("Foo::operator<Foo> *&&();", Style);
19388   verifyFormat("operator*(int (*)(), class Foo);", Style);
19389 
19390   verifyFormat("Foo::operator&();", Style);
19391   verifyFormat("Foo::operator void &();", Style);
19392   verifyFormat("Foo::operator void const &();", Style);
19393   verifyFormat("Foo::operator()(void &);", Style);
19394   verifyFormat("Foo::operator&(void &);", Style);
19395   verifyFormat("Foo::operator&();", Style);
19396   verifyFormat("operator&(int (&)(), class Foo);", Style);
19397 
19398   verifyFormat("Foo::operator&&();", Style);
19399   verifyFormat("Foo::operator**();", Style);
19400   verifyFormat("Foo::operator void &&();", Style);
19401   verifyFormat("Foo::operator void const &&();", Style);
19402   verifyFormat("Foo::operator()(void &&);", Style);
19403   verifyFormat("Foo::operator&&(void &&);", Style);
19404   verifyFormat("Foo::operator&&();", Style);
19405   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
19406   verifyFormat("operator const nsTArrayRight<E> &()", Style);
19407   verifyFormat("[[nodiscard]] operator const nsTArrayRight<E, Allocator> &()",
19408                Style);
19409   verifyFormat("operator void **()", Style);
19410   verifyFormat("operator const FooRight<Object> &()", Style);
19411   verifyFormat("operator const FooRight<Object> *()", Style);
19412   verifyFormat("operator const FooRight<Object> **()", Style);
19413   verifyFormat("operator const FooRight<Object> *&()", Style);
19414   verifyFormat("operator const FooRight<Object> *&&()", Style);
19415 
19416   Style.PointerAlignment = FormatStyle::PAS_Left;
19417   verifyFormat("Foo::operator*();", Style);
19418   verifyFormat("Foo::operator**();", Style);
19419   verifyFormat("Foo::operator void*();", Style);
19420   verifyFormat("Foo::operator void**();", Style);
19421   verifyFormat("Foo::operator void*&();", Style);
19422   verifyFormat("Foo::operator void*&&();", Style);
19423   verifyFormat("Foo::operator void const*();", Style);
19424   verifyFormat("Foo::operator void const**();", Style);
19425   verifyFormat("Foo::operator void const*&();", Style);
19426   verifyFormat("Foo::operator void const*&&();", Style);
19427   verifyFormat("Foo::operator/*comment*/ void*();", Style);
19428   verifyFormat("Foo::operator/*a*/ const /*b*/ void*();", Style);
19429   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void*();", Style);
19430   verifyFormat("Foo::operator()(void*);", Style);
19431   verifyFormat("Foo::operator*(void*);", Style);
19432   verifyFormat("Foo::operator*();", Style);
19433   verifyFormat("Foo::operator<int>*();", Style);
19434   verifyFormat("Foo::operator<Foo>*();", Style);
19435   verifyFormat("Foo::operator<int>**();", Style);
19436   verifyFormat("Foo::operator<Foo>**();", Style);
19437   verifyFormat("Foo::operator<Foo>*&();", Style);
19438   verifyFormat("Foo::operator<int>&();", Style);
19439   verifyFormat("Foo::operator<Foo>&();", Style);
19440   verifyFormat("Foo::operator<int>&&();", Style);
19441   verifyFormat("Foo::operator<Foo>&&();", Style);
19442   verifyFormat("Foo::operator<int>*&();", Style);
19443   verifyFormat("Foo::operator<Foo>*&();", Style);
19444   verifyFormat("operator*(int (*)(), class Foo);", Style);
19445 
19446   verifyFormat("Foo::operator&();", Style);
19447   verifyFormat("Foo::operator void&();", Style);
19448   verifyFormat("Foo::operator void const&();", Style);
19449   verifyFormat("Foo::operator/*comment*/ void&();", Style);
19450   verifyFormat("Foo::operator/*a*/ const /*b*/ void&();", Style);
19451   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&();", Style);
19452   verifyFormat("Foo::operator()(void&);", Style);
19453   verifyFormat("Foo::operator&(void&);", Style);
19454   verifyFormat("Foo::operator&();", Style);
19455   verifyFormat("operator&(int (&)(), class Foo);", Style);
19456 
19457   verifyFormat("Foo::operator&&();", Style);
19458   verifyFormat("Foo::operator void&&();", Style);
19459   verifyFormat("Foo::operator void const&&();", Style);
19460   verifyFormat("Foo::operator/*comment*/ void&&();", Style);
19461   verifyFormat("Foo::operator/*a*/ const /*b*/ void&&();", Style);
19462   verifyFormat("Foo::operator/*a*/ volatile /*b*/ void&&();", Style);
19463   verifyFormat("Foo::operator()(void&&);", Style);
19464   verifyFormat("Foo::operator&&(void&&);", Style);
19465   verifyFormat("Foo::operator&&();", Style);
19466   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
19467   verifyFormat("operator const nsTArrayLeft<E>&()", Style);
19468   verifyFormat("[[nodiscard]] operator const nsTArrayLeft<E, Allocator>&()",
19469                Style);
19470   verifyFormat("operator void**()", Style);
19471   verifyFormat("operator const FooLeft<Object>&()", Style);
19472   verifyFormat("operator const FooLeft<Object>*()", Style);
19473   verifyFormat("operator const FooLeft<Object>**()", Style);
19474   verifyFormat("operator const FooLeft<Object>*&()", Style);
19475   verifyFormat("operator const FooLeft<Object>*&&()", Style);
19476 
19477   // PR45107
19478   verifyFormat("operator Vector<String>&();", Style);
19479   verifyFormat("operator const Vector<String>&();", Style);
19480   verifyFormat("operator foo::Bar*();", Style);
19481   verifyFormat("operator const Foo<X>::Bar<Y>*();", Style);
19482   verifyFormat("operator/*a*/ const /*b*/ Foo /*c*/<X> /*d*/ ::Bar<Y>*();",
19483                Style);
19484 
19485   Style.PointerAlignment = FormatStyle::PAS_Middle;
19486   verifyFormat("Foo::operator*();", Style);
19487   verifyFormat("Foo::operator void *();", Style);
19488   verifyFormat("Foo::operator()(void *);", Style);
19489   verifyFormat("Foo::operator*(void *);", Style);
19490   verifyFormat("Foo::operator*();", Style);
19491   verifyFormat("operator*(int (*)(), class Foo);", Style);
19492 
19493   verifyFormat("Foo::operator&();", Style);
19494   verifyFormat("Foo::operator void &();", Style);
19495   verifyFormat("Foo::operator void const &();", Style);
19496   verifyFormat("Foo::operator()(void &);", Style);
19497   verifyFormat("Foo::operator&(void &);", Style);
19498   verifyFormat("Foo::operator&();", Style);
19499   verifyFormat("operator&(int (&)(), class Foo);", Style);
19500 
19501   verifyFormat("Foo::operator&&();", Style);
19502   verifyFormat("Foo::operator void &&();", Style);
19503   verifyFormat("Foo::operator void const &&();", Style);
19504   verifyFormat("Foo::operator()(void &&);", Style);
19505   verifyFormat("Foo::operator&&(void &&);", Style);
19506   verifyFormat("Foo::operator&&();", Style);
19507   verifyFormat("operator&&(int(&&)(), class Foo);", Style);
19508 }
19509 
19510 TEST_F(FormatTest, OperatorPassedAsAFunctionPtr) {
19511   FormatStyle Style = getLLVMStyle();
19512   // PR46157
19513   verifyFormat("foo(operator+, -42);", Style);
19514   verifyFormat("foo(operator++, -42);", Style);
19515   verifyFormat("foo(operator--, -42);", Style);
19516   verifyFormat("foo(-42, operator--);", Style);
19517   verifyFormat("foo(-42, operator, );", Style);
19518   verifyFormat("foo(operator, , -42);", Style);
19519 }
19520 
19521 TEST_F(FormatTest, WhitespaceSensitiveMacros) {
19522   FormatStyle Style = getLLVMStyle();
19523   Style.WhitespaceSensitiveMacros.push_back("FOO");
19524 
19525   // Don't use the helpers here, since 'mess up' will change the whitespace
19526   // and these are all whitespace sensitive by definition
19527   EXPECT_EQ("FOO(String-ized&Messy+But(: :Still)=Intentional);",
19528             format("FOO(String-ized&Messy+But(: :Still)=Intentional);", Style));
19529   EXPECT_EQ(
19530       "FOO(String-ized&Messy+But\\(: :Still)=Intentional);",
19531       format("FOO(String-ized&Messy+But\\(: :Still)=Intentional);", Style));
19532   EXPECT_EQ("FOO(String-ized&Messy+But,: :Still=Intentional);",
19533             format("FOO(String-ized&Messy+But,: :Still=Intentional);", Style));
19534   EXPECT_EQ("FOO(String-ized&Messy+But,: :\n"
19535             "       Still=Intentional);",
19536             format("FOO(String-ized&Messy+But,: :\n"
19537                    "       Still=Intentional);",
19538                    Style));
19539   Style.AlignConsecutiveAssignments = FormatStyle::ACS_Consecutive;
19540   EXPECT_EQ("FOO(String-ized=&Messy+But,: :\n"
19541             "       Still=Intentional);",
19542             format("FOO(String-ized=&Messy+But,: :\n"
19543                    "       Still=Intentional);",
19544                    Style));
19545 
19546   Style.ColumnLimit = 21;
19547   EXPECT_EQ("FOO(String-ized&Messy+But: :Still=Intentional);",
19548             format("FOO(String-ized&Messy+But: :Still=Intentional);", Style));
19549 }
19550 
19551 TEST_F(FormatTest, VeryLongNamespaceCommentSplit) {
19552   // These tests are not in NamespaceFixer because that doesn't
19553   // test its interaction with line wrapping
19554   FormatStyle Style = getLLVMStyle();
19555   Style.ColumnLimit = 80;
19556   verifyFormat("namespace {\n"
19557                "int i;\n"
19558                "int j;\n"
19559                "} // namespace",
19560                Style);
19561 
19562   verifyFormat("namespace AAA {\n"
19563                "int i;\n"
19564                "int j;\n"
19565                "} // namespace AAA",
19566                Style);
19567 
19568   EXPECT_EQ("namespace Averyveryveryverylongnamespace {\n"
19569             "int i;\n"
19570             "int j;\n"
19571             "} // namespace Averyveryveryverylongnamespace",
19572             format("namespace Averyveryveryverylongnamespace {\n"
19573                    "int i;\n"
19574                    "int j;\n"
19575                    "}",
19576                    Style));
19577 
19578   EXPECT_EQ(
19579       "namespace "
19580       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
19581       "    went::mad::now {\n"
19582       "int i;\n"
19583       "int j;\n"
19584       "} // namespace\n"
19585       "  // "
19586       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
19587       "went::mad::now",
19588       format("namespace "
19589              "would::it::save::you::a::lot::of::time::if_::i::"
19590              "just::gave::up::and_::went::mad::now {\n"
19591              "int i;\n"
19592              "int j;\n"
19593              "}",
19594              Style));
19595 
19596   // This used to duplicate the comment again and again on subsequent runs
19597   EXPECT_EQ(
19598       "namespace "
19599       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::\n"
19600       "    went::mad::now {\n"
19601       "int i;\n"
19602       "int j;\n"
19603       "} // namespace\n"
19604       "  // "
19605       "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::and_::"
19606       "went::mad::now",
19607       format("namespace "
19608              "would::it::save::you::a::lot::of::time::if_::i::"
19609              "just::gave::up::and_::went::mad::now {\n"
19610              "int i;\n"
19611              "int j;\n"
19612              "} // namespace\n"
19613              "  // "
19614              "would::it::save::you::a::lot::of::time::if_::i::just::gave::up::"
19615              "and_::went::mad::now",
19616              Style));
19617 }
19618 
19619 TEST_F(FormatTest, LikelyUnlikely) {
19620   FormatStyle Style = getLLVMStyle();
19621 
19622   verifyFormat("if (argc > 5) [[unlikely]] {\n"
19623                "  return 29;\n"
19624                "}",
19625                Style);
19626 
19627   verifyFormat("if (argc > 5) [[likely]] {\n"
19628                "  return 29;\n"
19629                "}",
19630                Style);
19631 
19632   verifyFormat("if (argc > 5) [[unlikely]] {\n"
19633                "  return 29;\n"
19634                "} else [[likely]] {\n"
19635                "  return 42;\n"
19636                "}\n",
19637                Style);
19638 
19639   verifyFormat("if (argc > 5) [[unlikely]] {\n"
19640                "  return 29;\n"
19641                "} else if (argc > 10) [[likely]] {\n"
19642                "  return 99;\n"
19643                "} else {\n"
19644                "  return 42;\n"
19645                "}\n",
19646                Style);
19647 
19648   verifyFormat("if (argc > 5) [[gnu::unused]] {\n"
19649                "  return 29;\n"
19650                "}",
19651                Style);
19652 }
19653 
19654 TEST_F(FormatTest, PenaltyIndentedWhitespace) {
19655   verifyFormat("Constructor()\n"
19656                "    : aaaaaa(aaaaaa), aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19657                "                          aaaa(aaaaaaaaaaaaaaaaaa, "
19658                "aaaaaaaaaaaaaaaaaat))");
19659   verifyFormat("Constructor()\n"
19660                "    : aaaaaaaaaaaaa(aaaaaa), "
19661                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)");
19662 
19663   FormatStyle StyleWithWhitespacePenalty = getLLVMStyle();
19664   StyleWithWhitespacePenalty.PenaltyIndentedWhitespace = 5;
19665   verifyFormat("Constructor()\n"
19666                "    : aaaaaa(aaaaaa),\n"
19667                "      aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(\n"
19668                "          aaaa(aaaaaaaaaaaaaaaaaa, aaaaaaaaaaaaaaaaaat))",
19669                StyleWithWhitespacePenalty);
19670   verifyFormat("Constructor()\n"
19671                "    : aaaaaaaaaaaaa(aaaaaa), "
19672                "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(aaaaaaaaaaaaaaaaaa)",
19673                StyleWithWhitespacePenalty);
19674 }
19675 
19676 TEST_F(FormatTest, LLVMDefaultStyle) {
19677   FormatStyle Style = getLLVMStyle();
19678   verifyFormat("extern \"C\" {\n"
19679                "int foo();\n"
19680                "}",
19681                Style);
19682 }
19683 TEST_F(FormatTest, GNUDefaultStyle) {
19684   FormatStyle Style = getGNUStyle();
19685   verifyFormat("extern \"C\"\n"
19686                "{\n"
19687                "  int foo ();\n"
19688                "}",
19689                Style);
19690 }
19691 TEST_F(FormatTest, MozillaDefaultStyle) {
19692   FormatStyle Style = getMozillaStyle();
19693   verifyFormat("extern \"C\"\n"
19694                "{\n"
19695                "  int foo();\n"
19696                "}",
19697                Style);
19698 }
19699 TEST_F(FormatTest, GoogleDefaultStyle) {
19700   FormatStyle Style = getGoogleStyle();
19701   verifyFormat("extern \"C\" {\n"
19702                "int foo();\n"
19703                "}",
19704                Style);
19705 }
19706 TEST_F(FormatTest, ChromiumDefaultStyle) {
19707   FormatStyle Style = getChromiumStyle(FormatStyle::LanguageKind::LK_Cpp);
19708   verifyFormat("extern \"C\" {\n"
19709                "int foo();\n"
19710                "}",
19711                Style);
19712 }
19713 TEST_F(FormatTest, MicrosoftDefaultStyle) {
19714   FormatStyle Style = getMicrosoftStyle(FormatStyle::LanguageKind::LK_Cpp);
19715   verifyFormat("extern \"C\"\n"
19716                "{\n"
19717                "    int foo();\n"
19718                "}",
19719                Style);
19720 }
19721 TEST_F(FormatTest, WebKitDefaultStyle) {
19722   FormatStyle Style = getWebKitStyle();
19723   verifyFormat("extern \"C\" {\n"
19724                "int foo();\n"
19725                "}",
19726                Style);
19727 }
19728 
19729 TEST_F(FormatTest, ConceptsAndRequires) {
19730   FormatStyle Style = getLLVMStyle();
19731   Style.AllowShortFunctionsOnASingleLine = FormatStyle::SFS_None;
19732 
19733   verifyFormat("template <typename T>\n"
19734                "concept Hashable = requires(T a) {\n"
19735                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
19736                "};",
19737                Style);
19738   verifyFormat("template <typename T>\n"
19739                "concept EqualityComparable = requires(T a, T b) {\n"
19740                "  { a == b } -> bool;\n"
19741                "};",
19742                Style);
19743   verifyFormat("template <typename T>\n"
19744                "concept EqualityComparable = requires(T a, T b) {\n"
19745                "  { a == b } -> bool;\n"
19746                "  { a != b } -> bool;\n"
19747                "};",
19748                Style);
19749   verifyFormat("template <typename T>\n"
19750                "concept EqualityComparable = requires(T a, T b) {\n"
19751                "  { a == b } -> bool;\n"
19752                "  { a != b } -> bool;\n"
19753                "};",
19754                Style);
19755 
19756   verifyFormat("template <typename It>\n"
19757                "requires Iterator<It>\n"
19758                "void sort(It begin, It end) {\n"
19759                "  //....\n"
19760                "}",
19761                Style);
19762 
19763   verifyFormat("template <typename T>\n"
19764                "concept Large = sizeof(T) > 10;",
19765                Style);
19766 
19767   verifyFormat("template <typename T, typename U>\n"
19768                "concept FooableWith = requires(T t, U u) {\n"
19769                "  typename T::foo_type;\n"
19770                "  { t.foo(u) } -> typename T::foo_type;\n"
19771                "  t++;\n"
19772                "};\n"
19773                "void doFoo(FooableWith<int> auto t) {\n"
19774                "  t.foo(3);\n"
19775                "}",
19776                Style);
19777   verifyFormat("template <typename T>\n"
19778                "concept Context = sizeof(T) == 1;",
19779                Style);
19780   verifyFormat("template <typename T>\n"
19781                "concept Context = is_specialization_of_v<context, T>;",
19782                Style);
19783   verifyFormat("template <typename T>\n"
19784                "concept Node = std::is_object_v<T>;",
19785                Style);
19786   verifyFormat("template <typename T>\n"
19787                "concept Tree = true;",
19788                Style);
19789 
19790   verifyFormat("template <typename T> int g(T i) requires Concept1<I> {\n"
19791                "  //...\n"
19792                "}",
19793                Style);
19794 
19795   verifyFormat(
19796       "template <typename T> int g(T i) requires Concept1<I> && Concept2<I> {\n"
19797       "  //...\n"
19798       "}",
19799       Style);
19800 
19801   verifyFormat(
19802       "template <typename T> int g(T i) requires Concept1<I> || Concept2<I> {\n"
19803       "  //...\n"
19804       "}",
19805       Style);
19806 
19807   verifyFormat("template <typename T>\n"
19808                "veryveryvery_long_return_type g(T i) requires Concept1<I> || "
19809                "Concept2<I> {\n"
19810                "  //...\n"
19811                "}",
19812                Style);
19813 
19814   verifyFormat("template <typename T>\n"
19815                "veryveryvery_long_return_type g(T i) requires Concept1<I> && "
19816                "Concept2<I> {\n"
19817                "  //...\n"
19818                "}",
19819                Style);
19820 
19821   verifyFormat(
19822       "template <typename T>\n"
19823       "veryveryvery_long_return_type g(T i) requires Concept1 && Concept2 {\n"
19824       "  //...\n"
19825       "}",
19826       Style);
19827 
19828   verifyFormat(
19829       "template <typename T>\n"
19830       "veryveryvery_long_return_type g(T i) requires Concept1 || Concept2 {\n"
19831       "  //...\n"
19832       "}",
19833       Style);
19834 
19835   verifyFormat("template <typename It>\n"
19836                "requires Foo<It>() && Bar<It> {\n"
19837                "  //....\n"
19838                "}",
19839                Style);
19840 
19841   verifyFormat("template <typename It>\n"
19842                "requires Foo<Bar<It>>() && Bar<Foo<It, It>> {\n"
19843                "  //....\n"
19844                "}",
19845                Style);
19846 
19847   verifyFormat("template <typename It>\n"
19848                "requires Foo<Bar<It, It>>() && Bar<Foo<It, It>> {\n"
19849                "  //....\n"
19850                "}",
19851                Style);
19852 
19853   verifyFormat(
19854       "template <typename It>\n"
19855       "requires Foo<Bar<It>, Baz<It>>() && Bar<Foo<It>, Baz<It, It>> {\n"
19856       "  //....\n"
19857       "}",
19858       Style);
19859 
19860   Style.IndentRequires = true;
19861   verifyFormat("template <typename It>\n"
19862                "  requires Iterator<It>\n"
19863                "void sort(It begin, It end) {\n"
19864                "  //....\n"
19865                "}",
19866                Style);
19867   verifyFormat("template <std::size index_>\n"
19868                "  requires(index_ < sizeof...(Children_))\n"
19869                "Tree auto &child() {\n"
19870                "  // ...\n"
19871                "}",
19872                Style);
19873 
19874   Style.SpaceBeforeParens = FormatStyle::SBPO_Always;
19875   verifyFormat("template <typename T>\n"
19876                "concept Hashable = requires (T a) {\n"
19877                "  { std::hash<T>{}(a) } -> std::convertible_to<std::size_t>;\n"
19878                "};",
19879                Style);
19880 
19881   verifyFormat("template <class T = void>\n"
19882                "  requires EqualityComparable<T> || Same<T, void>\n"
19883                "struct equal_to;",
19884                Style);
19885 
19886   verifyFormat("template <class T>\n"
19887                "  requires requires {\n"
19888                "    T{};\n"
19889                "    T (int);\n"
19890                "  }\n",
19891                Style);
19892 
19893   Style.ColumnLimit = 78;
19894   verifyFormat("template <typename T>\n"
19895                "concept Context = Traits<typename T::traits_type> and\n"
19896                "    Interface<typename T::interface_type> and\n"
19897                "    Request<typename T::request_type> and\n"
19898                "    Response<typename T::response_type> and\n"
19899                "    ContextExtension<typename T::extension_type> and\n"
19900                "    ::std::is_copy_constructable<T> and "
19901                "::std::is_move_constructable<T> and\n"
19902                "    requires (T c) {\n"
19903                "  { c.response; } -> Response;\n"
19904                "} and requires (T c) {\n"
19905                "  { c.request; } -> Request;\n"
19906                "}\n",
19907                Style);
19908 
19909   verifyFormat("template <typename T>\n"
19910                "concept Context = Traits<typename T::traits_type> or\n"
19911                "    Interface<typename T::interface_type> or\n"
19912                "    Request<typename T::request_type> or\n"
19913                "    Response<typename T::response_type> or\n"
19914                "    ContextExtension<typename T::extension_type> or\n"
19915                "    ::std::is_copy_constructable<T> or "
19916                "::std::is_move_constructable<T> or\n"
19917                "    requires (T c) {\n"
19918                "  { c.response; } -> Response;\n"
19919                "} or requires (T c) {\n"
19920                "  { c.request; } -> Request;\n"
19921                "}\n",
19922                Style);
19923 
19924   verifyFormat("template <typename T>\n"
19925                "concept Context = Traits<typename T::traits_type> &&\n"
19926                "    Interface<typename T::interface_type> &&\n"
19927                "    Request<typename T::request_type> &&\n"
19928                "    Response<typename T::response_type> &&\n"
19929                "    ContextExtension<typename T::extension_type> &&\n"
19930                "    ::std::is_copy_constructable<T> && "
19931                "::std::is_move_constructable<T> &&\n"
19932                "    requires (T c) {\n"
19933                "  { c.response; } -> Response;\n"
19934                "} && requires (T c) {\n"
19935                "  { c.request; } -> Request;\n"
19936                "}\n",
19937                Style);
19938 
19939   verifyFormat("template <typename T>\nconcept someConcept = Constraint1<T> && "
19940                "Constraint2<T>;");
19941 
19942   Style.BreakBeforeBraces = FormatStyle::BS_Custom;
19943   Style.BraceWrapping.AfterFunction = true;
19944   Style.BraceWrapping.AfterClass = true;
19945   Style.AlwaysBreakTemplateDeclarations = FormatStyle::BTDS_Yes;
19946   Style.BreakConstructorInitializers = FormatStyle::BCIS_BeforeColon;
19947   verifyFormat("void Foo () requires (std::copyable<T>)\n"
19948                "{\n"
19949                "  return\n"
19950                "}\n",
19951                Style);
19952 
19953   verifyFormat("void Foo () requires std::copyable<T>\n"
19954                "{\n"
19955                "  return\n"
19956                "}\n",
19957                Style);
19958 
19959   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
19960                "  requires (std::invocable<F, std::invoke_result_t<Args>...>)\n"
19961                "struct constant;",
19962                Style);
19963 
19964   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
19965                "  requires std::invocable<F, std::invoke_result_t<Args>...>\n"
19966                "struct constant;",
19967                Style);
19968 
19969   verifyFormat("template <class T>\n"
19970                "class plane_with_very_very_very_long_name\n"
19971                "{\n"
19972                "  constexpr plane_with_very_very_very_long_name () requires "
19973                "std::copyable<T>\n"
19974                "      : plane_with_very_very_very_long_name (1)\n"
19975                "  {\n"
19976                "  }\n"
19977                "}\n",
19978                Style);
19979 
19980   verifyFormat("template <class T>\n"
19981                "class plane_with_long_name\n"
19982                "{\n"
19983                "  constexpr plane_with_long_name () requires std::copyable<T>\n"
19984                "      : plane_with_long_name (1)\n"
19985                "  {\n"
19986                "  }\n"
19987                "}\n",
19988                Style);
19989 
19990   Style.BreakBeforeConceptDeclarations = false;
19991   verifyFormat("template <typename T> concept Tree = true;", Style);
19992 
19993   Style.IndentRequires = false;
19994   verifyFormat("template <std::semiregular F, std::semiregular... Args>\n"
19995                "requires (std::invocable<F, std::invoke_result_t<Args>...>) "
19996                "struct constant;",
19997                Style);
19998 }
19999 
20000 TEST_F(FormatTest, StatementAttributeLikeMacros) {
20001   FormatStyle Style = getLLVMStyle();
20002   StringRef Source = "void Foo::slot() {\n"
20003                      "  unsigned char MyChar = 'x';\n"
20004                      "  emit signal(MyChar);\n"
20005                      "  Q_EMIT signal(MyChar);\n"
20006                      "}";
20007 
20008   EXPECT_EQ(Source, format(Source, Style));
20009 
20010   Style.AlignConsecutiveDeclarations = FormatStyle::ACS_Consecutive;
20011   EXPECT_EQ("void Foo::slot() {\n"
20012             "  unsigned char MyChar = 'x';\n"
20013             "  emit          signal(MyChar);\n"
20014             "  Q_EMIT signal(MyChar);\n"
20015             "}",
20016             format(Source, Style));
20017 
20018   Style.StatementAttributeLikeMacros.push_back("emit");
20019   EXPECT_EQ(Source, format(Source, Style));
20020 
20021   Style.StatementAttributeLikeMacros = {};
20022   EXPECT_EQ("void Foo::slot() {\n"
20023             "  unsigned char MyChar = 'x';\n"
20024             "  emit          signal(MyChar);\n"
20025             "  Q_EMIT        signal(MyChar);\n"
20026             "}",
20027             format(Source, Style));
20028 }
20029 
20030 TEST_F(FormatTest, IndentAccessModifiers) {
20031   FormatStyle Style = getLLVMStyle();
20032   Style.IndentAccessModifiers = true;
20033   // Members are *two* levels below the record;
20034   // Style.IndentWidth == 2, thus yielding a 4 spaces wide indentation.
20035   verifyFormat("class C {\n"
20036                "    int i;\n"
20037                "};\n",
20038                Style);
20039   verifyFormat("union C {\n"
20040                "    int i;\n"
20041                "    unsigned u;\n"
20042                "};\n",
20043                Style);
20044   // Access modifiers should be indented one level below the record.
20045   verifyFormat("class C {\n"
20046                "  public:\n"
20047                "    int i;\n"
20048                "};\n",
20049                Style);
20050   verifyFormat("struct S {\n"
20051                "  private:\n"
20052                "    class C {\n"
20053                "        int j;\n"
20054                "\n"
20055                "      public:\n"
20056                "        C();\n"
20057                "    };\n"
20058                "\n"
20059                "  public:\n"
20060                "    int i;\n"
20061                "};\n",
20062                Style);
20063   // Enumerations are not records and should be unaffected.
20064   Style.AllowShortEnumsOnASingleLine = false;
20065   verifyFormat("enum class E\n"
20066                "{\n"
20067                "  A,\n"
20068                "  B\n"
20069                "};\n",
20070                Style);
20071   // Test with a different indentation width;
20072   // also proves that the result is Style.AccessModifierOffset agnostic.
20073   Style.IndentWidth = 3;
20074   verifyFormat("class C {\n"
20075                "   public:\n"
20076                "      int i;\n"
20077                "};\n",
20078                Style);
20079 }
20080 
20081 TEST_F(FormatTest, LimitlessStringsAndComments) {
20082   auto Style = getLLVMStyleWithColumns(0);
20083   constexpr StringRef Code =
20084       "/**\n"
20085       " * This is a multiline comment with quite some long lines, at least for "
20086       "the LLVM Style.\n"
20087       " * We will redo this with strings and line comments. Just to  check if "
20088       "everything is working.\n"
20089       " */\n"
20090       "bool foo() {\n"
20091       "  /* Single line multi line comment. */\n"
20092       "  const std::string String = \"This is a multiline string with quite "
20093       "some long lines, at least for the LLVM Style.\"\n"
20094       "                             \"We already did it with multi line "
20095       "comments, and we will do it with line comments. Just to check if "
20096       "everything is working.\";\n"
20097       "  // This is a line comment (block) with quite some long lines, at "
20098       "least for the LLVM Style.\n"
20099       "  // We already did this with multi line comments and strings. Just to "
20100       "check if everything is working.\n"
20101       "  const std::string SmallString = \"Hello World\";\n"
20102       "  // Small line comment\n"
20103       "  return String.size() > SmallString.size();\n"
20104       "}";
20105   EXPECT_EQ(Code, format(Code, Style));
20106 }
20107 } // namespace
20108 } // namespace format
20109 } // namespace clang
20110